Ejemplo n.º 1
0
 private void DoDirectPayment(HttpContext context)
 {
     DoDirectPaymentReq req = new DoDirectPaymentReq();
     req.DoDirectPaymentRequest = new DoDirectPaymentRequestType();
     req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails = new DoDirectPaymentRequestDetailsType();
     req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard = new CreditCardDetailsType();
     req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.PaymentDetails = new PaymentDetailsType();
     req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.PaymentDetails.OrderTotal = new BasicAmountType();
     req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.PaymentDetails.ShipToAddress = new AddressType();
     req.DoDirectPaymentRequest.Version = "78.0";
     req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.CreditCardNumber = context.Request.Params["cardNum"];
     req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.CreditCardType = (CreditCardTypeType)EnumUtils.getValue(context.Request.Params["creditcardType"], typeof(CreditCardTypeType));
     req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.CVV2 = context.Request.Params["cvv2Num"];
     req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.ExpMonth = System.Convert.ToInt32(context.Request.Params["expDateMonth"]);
     req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.ExpYear = System.Convert.ToInt32(context.Request.Params["expDateYear"]);
     req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.PaymentAction = (PaymentActionCodeType)EnumUtils.getValue(context.Request.Params["paymentType"], typeof(PaymentActionCodeType));
     req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.PaymentDetails.OrderTotal.currencyID = (CurrencyCodeType)EnumUtils.getValue(context.Request.Params["currencyCode"], typeof(CurrencyCodeType));
     req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.PaymentDetails.OrderTotal.value = context.Request.Params["amount"];
     req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.PaymentDetails.ShipToAddress.Street1 = context.Request.Params["addr1"];
     req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.PaymentDetails.ShipToAddress.Street2 = context.Request.Params["addr2"];
     req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.PaymentDetails.ShipToAddress.CityName = context.Request.Params["city"];
     req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.PaymentDetails.ShipToAddress.StateOrProvince = context.Request.Params["state"];
     req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.PaymentDetails.ShipToAddress.PostalCode = context.Request.Params["zipCode"];
     req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.PaymentDetails.ShipToAddress.Country =(CountryCodeType)EnumUtils.getValue(context.Request.Params["countryCode"], typeof(CountryCodeType));
     req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.PaymentDetails.ShipToAddress.Name = context.Request.Params["firstName"] + context.Request.Params["lastName"];
     req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.CardOwner = new PayerInfoType();
     req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.CardOwner.PayerName = new PersonNameType();
     req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.CardOwner.PayerCountry = (CountryCodeType)EnumUtils.getValue(context.Request.Params["countryCode"], typeof(CountryCodeType));
     req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.CardOwner.PayerName.FirstName=context.Request.Params["firstName"];
     req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.CardOwner.PayerName.LastName = context.Request.Params["lastName"];
     req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.CardOwner.Address = new AddressType();
     req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.CardOwner.Address.Street1 = context.Request.Params["addr1"];
     req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.CardOwner.Address.Street2 = context.Request.Params["addr2"];
     req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.CardOwner.Address.CityName = context.Request.Params["city"];
     req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.CardOwner.Address.StateOrProvince = context.Request.Params["state"];
     req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.CardOwner.Address.PostalCode = context.Request.Params["zipCode"];
     req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.CardOwner.Address.Country = (CountryCodeType)EnumUtils.getValue(context.Request.Params["countryCode"], typeof(CountryCodeType));
     req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.CardOwner.Address.Name = context.Request.Params["firstName"] + context.Request.Params["lastName"];
     try
     {
         PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService();
         DoDirectPaymentResponseType resp = service.DoDirectPayment(req);
         context.Response.Write("<html><body><textarea rows=30 cols=80>");
         ObjectDumper.Write(resp, 5, context.Response.Output);
         context.Response.Write("</textarea></body></html>");
     }
     catch (System.Exception e)
     {
         context.Response.Write(e.Message);
     }
 }
        protected ProcessPaymentResult AuthorizeOrSale(ProcessPaymentRequest processPaymentRequest, bool authorizeOnly)
        {
            var result = new ProcessPaymentResult();

            var customer = _customerService.GetCustomerById(processPaymentRequest.CustomerId);
            if (customer == null)
                throw new Exception("Customer cannot be loaded");

            var req = new DoDirectPaymentReq();
            req.DoDirectPaymentRequest = new DoDirectPaymentRequestType();
            req.DoDirectPaymentRequest.Version = GetApiVersion();
            var details = new DoDirectPaymentRequestDetailsType();
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails = details;
            details.IPAddress = _webHelper.GetCurrentIpAddress() ?? "";
            if (authorizeOnly)
                details.PaymentAction = PaymentActionCodeType.AUTHORIZATION;
            else
                details.PaymentAction = PaymentActionCodeType.SALE;
            //credit card
            details.CreditCard = new CreditCardDetailsType();
            details.CreditCard.CreditCardNumber = processPaymentRequest.CreditCardNumber;
            details.CreditCard.CreditCardType = GetPaypalCreditCardType(processPaymentRequest.CreditCardType);
            details.CreditCard.ExpMonth = processPaymentRequest.CreditCardExpireMonth;
            details.CreditCard.ExpYear = processPaymentRequest.CreditCardExpireYear;
            details.CreditCard.CVV2 = processPaymentRequest.CreditCardCvv2;
            details.CreditCard.CardOwner = new PayerInfoType();
            var country = EngineContext.Current.Resolve<ICountryService>().GetCountryById(customer.BillingAddress.CountryId);
            details.CreditCard.CardOwner.PayerCountry = GetPaypalCountryCodeType(country);
            //billing address
            details.CreditCard.CardOwner.Address = new AddressType();
            details.CreditCard.CardOwner.Address.Street1 = customer.BillingAddress.Address1;
            details.CreditCard.CardOwner.Address.Street2 = customer.BillingAddress.Address2;
            details.CreditCard.CardOwner.Address.CityName = customer.BillingAddress.City;
            if (customer.BillingAddress.StateProvinceId != 0)
            {
                var state = EngineContext.Current.Resolve<IStateProvinceService>().GetStateProvinceById(customer.BillingAddress.StateProvinceId);
                details.CreditCard.CardOwner.Address.StateOrProvince = state.Abbreviation;
            }
            else
                details.CreditCard.CardOwner.Address.StateOrProvince = "CA";
            details.CreditCard.CardOwner.Address.Country = GetPaypalCountryCodeType(country);
            details.CreditCard.CardOwner.Address.PostalCode = customer.BillingAddress.ZipPostalCode;
            details.CreditCard.CardOwner.Payer = customer.BillingAddress.Email;
            details.CreditCard.CardOwner.PayerName = new PersonNameType();
            details.CreditCard.CardOwner.PayerName.FirstName = customer.BillingAddress.FirstName;
            details.CreditCard.CardOwner.PayerName.LastName = customer.BillingAddress.LastName;
            //order totals
            var payPalCurrency = PaypalHelper.GetPaypalCurrency(_currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId));
            details.PaymentDetails = new PaymentDetailsType();
            details.PaymentDetails.OrderTotal = new BasicAmountType();
            details.PaymentDetails.OrderTotal.value = Math.Round(processPaymentRequest.OrderTotal, 2).ToString("N", new CultureInfo("en-us"));
            details.PaymentDetails.OrderTotal.currencyID = payPalCurrency;
            details.PaymentDetails.Custom = processPaymentRequest.OrderGuid.ToString();
            details.PaymentDetails.ButtonSource = "nopCommerceCart";
            //shipping
            if (customer.ShippingAddress != null)
            {
                if (customer.ShippingAddress.StateProvinceId != 0 && customer.ShippingAddress.CountryId != 0)
                {
                    var state = EngineContext.Current.Resolve<IStateProvinceService>().GetStateProvinceById(customer.ShippingAddress.StateProvinceId);
                    var countryshipping = EngineContext.Current.Resolve<ICountryService>().GetCountryById(customer.ShippingAddress.CountryId);

                    var shippingAddress = new AddressType();
                    shippingAddress.Name = customer.ShippingAddress.FirstName + " " + customer.ShippingAddress.LastName;
                    shippingAddress.Street1 = customer.ShippingAddress.Address1;
                    shippingAddress.Street2 = customer.ShippingAddress.Address2;
                    shippingAddress.CityName = customer.ShippingAddress.City;
                    shippingAddress.StateOrProvince = state.Abbreviation;
                    shippingAddress.PostalCode = customer.ShippingAddress.ZipPostalCode;
                    shippingAddress.Country = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), countryshipping.TwoLetterIsoCode, true);
                    details.PaymentDetails.ShipToAddress = shippingAddress;
                }
            }

            //send request
            var service = GetService();
            DoDirectPaymentResponseType response = service.DoDirectPayment(req);

            string error;
            bool success = PaypalHelper.CheckSuccess(response, out error);
            if (success)
            {
                result.AvsResult = response.AVSCode;
                result.AuthorizationTransactionCode = response.CVV2Code;
                if (authorizeOnly)
                {
                    result.AuthorizationTransactionId = response.TransactionID;
                    result.AuthorizationTransactionResult = response.Ack.ToString();

                    result.NewPaymentStatus = PaymentStatus.Authorized;
                }
                else
                {
                    result.CaptureTransactionId = response.TransactionID;
                    result.CaptureTransactionResult = response.Ack.ToString();

                    result.NewPaymentStatus = PaymentStatus.Paid;
                }
            }
            else
            {
                result.AddError(error);
            }
            return result;
        }
        /// <summary>
        /// 
        /// </summary>
        ///<param name="doDirectPaymentReq"></param>
        ///<param name="credential">An explicit ICredential object that you want to authenticate this call against</param> 
        public DoDirectPaymentResponseType DoDirectPayment(DoDirectPaymentReq doDirectPaymentReq, ICredential credential)
        {
            setStandardParams(doDirectPaymentReq.DoDirectPaymentRequest);
            DefaultSOAPAPICallHandler defaultHandler = new DefaultSOAPAPICallHandler(this.config, doDirectPaymentReq.ToXMLString(null, "DoDirectPaymentReq"), null, null);
            IAPICallPreHandler apiCallPreHandler = new MerchantAPICallPreHandler(this.config, defaultHandler, credential);
            ((MerchantAPICallPreHandler) apiCallPreHandler).SDKName = SDKName;
            ((MerchantAPICallPreHandler) apiCallPreHandler).SDKVersion = SDKVersion;
            ((MerchantAPICallPreHandler) apiCallPreHandler).PortName = "PayPalAPIAA";

            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.LoadXml(Call(apiCallPreHandler));
            return new DoDirectPaymentResponseType(
                xmlDocument.SelectSingleNode("*[local-name()='Envelope']/*[local-name()='Body']/*[local-name()='DoDirectPaymentResponse']")
            );
        }
 /// <summary> 
 /// 
 /// </summary>
 ///<param name="doDirectPaymentReq"></param>
 public DoDirectPaymentResponseType DoDirectPayment(DoDirectPaymentReq doDirectPaymentReq)
 {
     return DoDirectPayment(doDirectPaymentReq,(string) null);
 }
        private DoDirectPaymentReq GetDoDirectPaymentRequest(ProcessPaymentEvaluationContext context)
        {
            var retVal = new DoDirectPaymentReq();

            retVal.DoDirectPaymentRequest = new DoDirectPaymentRequestType();
            retVal.DoDirectPaymentRequest.Version = GetApiVersion();
            var details = new DoDirectPaymentRequestDetailsType();
            retVal.DoDirectPaymentRequest.DoDirectPaymentRequestDetails = details;
            details.PaymentAction = PaymentActionCodeType.SALE;

            //credit card
            details.CreditCard = GetCreditCardDetails(context);


            //order totals
            details.PaymentDetails = new PaymentDetailsType();
            details.PaymentDetails.OrderTotal = new BasicAmountType();
            details.PaymentDetails.OrderTotal.value = FormatMoney(context.Payment.Sum);
            details.PaymentDetails.OrderTotal.currencyID = (CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), context.Order.Currency.ToString());
            details.PaymentDetails.Custom = context.Order.Id;
            details.PaymentDetails.ButtonSource = "virtoCommerceManagerCart";

            return retVal;
        }
 /**
   *AUTO_GENERATED
  	  */
 public DoDirectPaymentResponseType DoDirectPayment(DoDirectPaymentReq doDirectPaymentReq, string apiUserName)
 {
     IAPICallPreHandler apiCallPreHandler = null;
      		string portName = "PayPalAPIAA";
     setStandardParams(doDirectPaymentReq.DoDirectPaymentRequest);
     DefaultSOAPAPICallHandler defaultHandler = new DefaultSOAPAPICallHandler(doDirectPaymentReq.ToXMLString(null, "DoDirectPaymentReq"), null, null);
     apiCallPreHandler = new MerchantAPICallPreHandler(defaultHandler, apiUserName, getAccessToken(), getAccessTokenSecret());
     ((MerchantAPICallPreHandler) apiCallPreHandler).SDKName = SDKName;
     ((MerchantAPICallPreHandler) apiCallPreHandler).SDKVersion = SDKVersion;
     ((MerchantAPICallPreHandler) apiCallPreHandler).PortName = portName;
     string response = Call(apiCallPreHandler);
     XmlDocument xmlDocument = new XmlDocument();
     xmlDocument.LoadXml(response);
     XmlNode xmlNode = xmlDocument.SelectSingleNode("*[local-name()='Envelope']/*[local-name()='Body']/*[local-name()='DoDirectPaymentResponse']");
     return new DoDirectPaymentResponseType(xmlNode);
 }
        protected void Submit_Click(object sender, EventArgs e)
        {
            // Create request object
            DoDirectPaymentRequestType request = new DoDirectPaymentRequestType();
            DoDirectPaymentRequestDetailsType requestDetails = new DoDirectPaymentRequestDetailsType();
            request.DoDirectPaymentRequestDetails = requestDetails;

            // (Optional) How you want to obtain payment. It is one of the following values:
            // * Authorization – This payment is a basic authorization subject to settlement with PayPal Authorization and Capture.
            // * Sale – This is a final sale for which you are requesting payment (default).
            // Note: Order is not allowed for Direct Payment.
            requestDetails.PaymentAction = (PaymentActionCodeType)
                Enum.Parse(typeof(PaymentActionCodeType), paymentType.SelectedValue);

            // (Required) Information about the credit card to be charged.
            CreditCardDetailsType creditCard = new CreditCardDetailsType();
            requestDetails.CreditCard = creditCard;
            PayerInfoType payer = new PayerInfoType();
            // (Optional) First and last name of buyer.
            PersonNameType name = new PersonNameType();
            name.FirstName = firstName.Value;
            name.LastName = lastName.Value;
            payer.PayerName = name;
            // (Required) Details about the owner of the credit card.
            creditCard.CardOwner = payer;

            // (Required) Credit card number.
            creditCard.CreditCardNumber = creditCardNumber.Value;
            // (Optional) Type of credit card. For UK, only Maestro, MasterCard, Discover, and Visa are allowable. For Canada, only MasterCard and Visa are allowable and Interac debit cards are not supported. It is one of the following values:
            // * Visa
            // * MasterCard
            // * Discover
            // * Amex
            // * Maestro: See note.
            // Note: If the credit card type is Maestro, you must set currencyId to GBP. In addition, you must specify either StartMonth and StartYear or IssueNumber.
            creditCard.CreditCardType = (CreditCardTypeType)
                Enum.Parse(typeof(CreditCardTypeType), creditCardType.SelectedValue);
            // Card Verification Value, version 2. Your Merchant Account settings determine whether this field is required. To comply with credit card processing regulations, you must not store this value after a transaction has been completed.
            // Character length and limitations: For Visa, MasterCard, and Discover, the value is exactly 3 digits. For American Express, the value is exactly 4 digits.
            creditCard.CVV2 = cvv2Number.Value;
            string[] cardExpiryDetails = cardExpiryDate.Text.Split(new char[] { '/' });
            if (cardExpiryDetails.Length == 2)
            {
                // (Required) Credit card expiration month.
                creditCard.ExpMonth = Convert.ToInt32(cardExpiryDetails[0]);
                // (Required) Credit card expiration year.
                creditCard.ExpYear = Convert.ToInt32(cardExpiryDetails[1]);
            }

            requestDetails.PaymentDetails = new PaymentDetailsType();
            // (Optional) Your URL for receiving Instant Payment Notification (IPN) about this transaction. If you do not specify this value in the request, the notification URL from your Merchant Profile is used, if one exists.
            // Important: The notify URL applies only to DoExpressCheckoutPayment. This value is ignored when set in SetExpressCheckout or GetExpressCheckoutDetails.
            requestDetails.PaymentDetails.NotifyURL = ipnNotificationUrl.Value.Trim();

            // (Optional) Buyer's shipping address information.
            AddressType billingAddr = new AddressType();
            if (firstName.Value != string.Empty && lastName.Value != string.Empty
                && street1.Value != string.Empty && country.Value != string.Empty)
            {
                billingAddr.Name = payerName.Value;
                // (Required) First street address.
                billingAddr.Street1 = street1.Value;
                // (Optional) Second street address.
                billingAddr.Street2 = street2.Value;
                // (Required) Name of city.
                billingAddr.CityName = city.Value;
                // (Required) State or province.
                billingAddr.StateOrProvince = state.Value;
                // (Required) Country code.
                billingAddr.Country = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), country.Value);
                // (Required) U.S. ZIP code or other country-specific postal code.
                billingAddr.PostalCode = postalCode.Value;

                // (Optional) Phone number.
                billingAddr.Phone = phone.Value;

                payer.Address = billingAddr;
            }

            // (Required) The total cost of the transaction to the buyer. If shipping cost and tax charges are known, include them in this value. If not, this value should be the current subtotal of the order. If the transaction includes one or more one-time purchases, this field must be equal to the sum of the purchases. This field must be set to a value greater than 0.
            // Note: You must set the currencyID attribute to one of the 3-character currency codes for any of the supported PayPal currencies.
            CurrencyCodeType currency = (CurrencyCodeType)
                Enum.Parse(typeof(CurrencyCodeType), currencyCode.SelectedValue);
            BasicAmountType paymentAmount = new BasicAmountType(currency, amount.Value);
            requestDetails.PaymentDetails.OrderTotal = paymentAmount;

            // Invoke the API
            DoDirectPaymentReq wrapper = new DoDirectPaymentReq();
            wrapper.DoDirectPaymentRequest = request;

            // Configuration map containing signature credentials and other required configuration.
            // For a full list of configuration parameters refer in wiki page
            // [https://github.com/paypal/sdk-core-dotnet/wiki/SDK-Configuration-Parameters]
            Dictionary<string, string> configurationMap = Configuration.GetAcctAndConfig();

            // Create the PayPalAPIInterfaceServiceService service object to make the API call
            PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(configurationMap);

            // # API call
            // Invoke the DoDirectPayment method in service wrapper object
            DoDirectPaymentResponseType response = service.DoDirectPayment(wrapper);

            // Check for API return status
            setKeyResponseObjects(service, response);
        }
        public ITransactionProcessResult Process(ITransactionProcessRequest request, bool authorizeOnly = false)
        {
            var user = _userService.Get(request.UserId);
            if (user == null)
            {
                throw new mobSocialException($"Can't find the user with Id {request.UserId}");
            }
            var creditCard = new CreditCardDetailsType() {
                CreditCardNumber = request.GetParameterAs<string>(PaymentParameterNames.CardNumber),
                CVV2 = request.GetParameterAs<string>(PaymentParameterNames.SecurityCode),
                ExpMonth = request.GetParameterAs<int>(PaymentParameterNames.ExpireMonth),
                ExpYear = request.GetParameterAs<int>(PaymentParameterNames.ExpireYear),
                CreditCardType = PayPalHelper.GeCreditCardTypeType(request.GetParameterAs<string>(PaymentParameterNames.CardIssuerType)),
                CardOwner = new PayerInfoType()
            };

            var paypalCurrency = PayPalHelper.GetPaypalCurrency(request.CurrencyIsoCode);
            var doDirectPaymentRequestDetails = new DoDirectPaymentRequestDetailsType() {
                IPAddress = WebHelper.GetClientIpAddress(),
                PaymentAction = authorizeOnly ? PaymentActionCodeType.AUTHORIZATION : PaymentActionCodeType.SALE,
                CreditCard = creditCard,
                PaymentDetails = new PaymentDetailsType() {
                    OrderTotal = new BasicAmountType() {
                        value = Math.Round(request.Amount, 2).ToString("N", new CultureInfo("en-US")),
                        currencyID = paypalCurrency
                    },
                    Custom = request.TransactionUniqueId,
                    ButtonSource = "mobSocial"
                }
            };

            var doDirectPaymentRequest = new DoDirectPaymentRequestType {
                Version = ApiVersion,
                DoDirectPaymentRequestDetails = doDirectPaymentRequestDetails
            };

            var paymentRequest = new DoDirectPaymentReq {
                DoDirectPaymentRequest = doDirectPaymentRequest
            };

            var service = GetPayPalApiInterfaceServiceService();
            var paypalResponse = service.DoDirectPayment(paymentRequest);

            var result = new TransactionResult();

            string error;
            var success = PayPalHelper.ParseResponseSuccess(paypalResponse, out error);
            if (success)
            {
                result.Success = true;
                result.SetParameter(PaymentParameterNames.AvsCode, paypalResponse.AVSCode);
                result.SetParameter(PaymentParameterNames.Cvv2Code, paypalResponse.CVV2Code);

                if (authorizeOnly)
                {
                    result.SetParameter(PaymentParameterNames.AuthorizationId, paypalResponse.TransactionID);
                    result.SetParameter(PaymentParameterNames.AuthorizationResult, paypalResponse.Ack);
                }
                else
                {
                    result.SetParameter(PaymentParameterNames.CaptureId, paypalResponse.TransactionID);
                    result.SetParameter(PaymentParameterNames.CaptureResult, paypalResponse.Ack);
                }
            }
            else
            {
                result.SetParameter(PaymentParameterNames.ErrorMessage, error);
            }

            return result;
        }
    // # DoDirectPaymentAPIOperation
    // The MassPay API operation makes a payment to one or more PayPal account holders.
    public DoDirectPaymentResponseType DoDirectPaymentAPIOperation()
    {
        // Create the DoDirectPaymentResponseType object
        DoDirectPaymentResponseType responseDoDirectPaymentResponseType = new DoDirectPaymentResponseType();

        try
        {
            // Create the DoDirectPaymentReq object
            DoDirectPaymentReq doDirectPayment = new DoDirectPaymentReq();
            DoDirectPaymentRequestDetailsType doDirectPaymentRequestDetails = new DoDirectPaymentRequestDetailsType();

            // Information about the credit card to be charged.
            CreditCardDetailsType creditCard = new CreditCardDetailsType();

            // Type of credit card. For UK, only Maestro, MasterCard, Discover, and
            // Visa are allowable. For Canada, only MasterCard and Visa are
            // allowable and Interac debit cards are not supported. It is one of the
            // following values:
            //
            // * Visa
            // * MasterCard
            // * Discover
            // * Amex
            // * Solo
            // * Switch
            // * Maestro: See note.
            // `Note:
            // If the credit card type is Maestro, you must set currencyId to GBP.
            // In addition, you must specify either StartMonth and StartYear or
            // IssueNumber.`
            creditCard.CreditCardType = CreditCardTypeType.VISA;

            // Credit Card number
            creditCard.CreditCardNumber = "4770461107194023";

            // ExpiryMonth of credit card
            creditCard.ExpMonth = Convert.ToInt32("12");

            // Expiry Year of credit card
            creditCard.ExpYear = Convert.ToInt32("2021");

            //Details about the owner of the credit card.
            PayerInfoType cardOwner = new PayerInfoType();

            // Email address of buyer.
            cardOwner.Payer = "*****@*****.**";
            creditCard.CardOwner = cardOwner;

            doDirectPaymentRequestDetails.CreditCard = creditCard;

            // Information about the payment
            PaymentDetailsType paymentDetails = new PaymentDetailsType();

            // IPN URL
            // * PayPal Instant Payment Notification is a call back system that is initiated when a transaction is completed        
            // * The transaction related IPN variables will be received on the call back URL specified in the request       
            // * The IPN variables have to be sent back to the PayPal system for validation, upon validation PayPal will send a response string "VERIFIED" or "INVALID"     
            // * PayPal would continuously resend IPN if a wrong IPN is sent        
            paymentDetails.NotifyURL = "http://IPNhost";

            // Total cost of the transaction to the buyer. If shipping cost and tax
            // charges are known, include them in this value. If not, this value
            // should be the current sub-total of the order.
            //
            // If the transaction includes one or more one-time purchases, this field must be equal to
            // the sum of the purchases. Set this field to 0 if the transaction does
            // not include a one-time purchase such as when you set up a billing
            // agreement for a recurring payment that is not immediately charged.
            // When the field is set to 0, purchase-specific fields are ignored.
            //
            // * `Currency Code` - You must set the currencyID attribute to one of the
            // 3-character currency codes for any of the supported PayPal
            // currencies.
            // * `Amount`
            BasicAmountType orderTotal = new BasicAmountType(CurrencyCodeType.USD, "4.00");
            paymentDetails.OrderTotal = orderTotal;
            doDirectPaymentRequestDetails.PaymentDetails = paymentDetails;

            // IP address of the buyer's browser.
            // `Note:
            // PayPal records this IP addresses as a means to detect possible fraud.`
            doDirectPaymentRequestDetails.IPAddress = "127.0.0.1";

            DoDirectPaymentRequestType doDirectPaymentRequest = new DoDirectPaymentRequestType(doDirectPaymentRequestDetails);
            doDirectPayment.DoDirectPaymentRequest = doDirectPaymentRequest;

            // Create the service wrapper object to make the API call
            PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService();

            // # API call
            // Invoke the DoDirectPayment method in service wrapper object
            responseDoDirectPaymentResponseType = service.DoDirectPayment(doDirectPayment);

            if (responseDoDirectPaymentResponseType != null)
            {
                // Response envelope acknowledgement
                string acknowledgement = "DoDirectPayment API Operation - ";
                acknowledgement += responseDoDirectPaymentResponseType.Ack.ToString();
                logger.Info(acknowledgement + "\n");
                Console.WriteLine(acknowledgement + "\n");

                // # Success values
                if (responseDoDirectPaymentResponseType.Ack.ToString().Trim().ToUpper().Equals("SUCCESS"))
                {
                    // Unique identifier of the transaction
                    logger.Info("Transaction ID : " + responseDoDirectPaymentResponseType.TransactionID + "\n");
                    Console.WriteLine("Transaction ID : " + responseDoDirectPaymentResponseType.TransactionID + "\n");

                }
                // # Error Values
                else
                {
                    List<ErrorType> errorMessages = responseDoDirectPaymentResponseType.Errors;
                    foreach (ErrorType error in errorMessages)
                    {
                        logger.Debug("API Error Message : " + error.LongMessage);
                        Console.WriteLine("API Error Message : " + error.LongMessage + "\n");
                    }
                }
            }
        }
        // # Exception log    
        catch (System.Exception ex)
        {
            // Log the exception message       
            logger.Debug("Error Message : " + ex.Message);
            Console.WriteLine("Error Message : " + ex.Message);
        }
        return responseDoDirectPaymentResponseType;
    }
 /**
   *AUTO_GENERATED
  	  */
 public DoDirectPaymentResponseType DoDirectPayment(DoDirectPaymentReq doDirectPaymentReq, string apiUserName)
 {
     setStandardParams(doDirectPaymentReq.DoDirectPaymentRequest);
     string response = Call("DoDirectPayment", doDirectPaymentReq.ToXMLString(), apiUserName);
     XmlDocument xmlDocument = new XmlDocument();
     xmlDocument.LoadXml(response);
     XmlNode xmlNode = xmlDocument.SelectSingleNode("*[local-name()='Envelope']/*[local-name()='Body']/*[local-name()='DoDirectPaymentResponse']");
     return new DoDirectPaymentResponseType(xmlNode);
 }
 public DoDirectPaymentResponseType DoDirectPayment(DoDirectPaymentReq DoDirectPaymentReq)
 {
     return DoDirectPayment(DoDirectPaymentReq, null);
 }
        /**
         *
         */
        public DoDirectPaymentResponseType DoDirectPayment(DoDirectPaymentReq DoDirectPaymentReq, string apiUsername)
        {
            setStandardParams(DoDirectPaymentReq.DoDirectPaymentRequest);
            string resp = call("DoDirectPayment", DoDirectPaymentReq.toXMLString(), apiUsername);

            return new DoDirectPaymentResponseType(resp);
        }
Ejemplo n.º 13
0
        protected void Submit_Click(object sender, EventArgs e)
        {
            // Create request object
            DoDirectPaymentRequestType request = new DoDirectPaymentRequestType();
            DoDirectPaymentRequestDetailsType requestDetails = new DoDirectPaymentRequestDetailsType();
            request.DoDirectPaymentRequestDetails = requestDetails;

            requestDetails.PaymentAction = (PaymentActionCodeType)
                Enum.Parse(typeof(PaymentActionCodeType), paymentType.SelectedValue);

            // Populate card requestDetails
            CreditCardDetailsType creditCard = new CreditCardDetailsType();
            requestDetails.CreditCard = creditCard;
            PayerInfoType payer = new PayerInfoType();
            PersonNameType name = new PersonNameType();
            name.FirstName = firstName.Value;
            name.LastName = lastName.Value;
            payer.PayerName = name;
            creditCard.CardOwner = payer;

            creditCard.CreditCardNumber = creditCardNumber.Value;
            creditCard.CreditCardType = (CreditCardTypeType)
                Enum.Parse(typeof(CreditCardTypeType), creditCardType.SelectedValue);
            creditCard.CVV2 = cvv2Number.Value;
            string[] cardExpiryDetails = cardExpiryDate.Text.Split(new char[] { '/' });
            if (cardExpiryDetails.Length == 2)
            {
                creditCard.ExpMonth = Int32.Parse(cardExpiryDetails[0]);
                creditCard.ExpYear = Int32.Parse(cardExpiryDetails[1]);
            }

            requestDetails.PaymentDetails = new PaymentDetailsType();
            AddressType billingAddr = new AddressType();
            if (firstName.Value != "" && lastName.Value != ""
                && street1.Value != "" && country.Value != "")
            {
                billingAddr.Name = payerName.Value;
                billingAddr.Street1 = street1.Value;
                billingAddr.Street2 = street2.Value;
                billingAddr.CityName = city.Value;
                billingAddr.StateOrProvince = state.Value;
                billingAddr.Country = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), country.Value);
                billingAddr.PostalCode = postalCode.Value;

                //Fix for release
                billingAddr.Phone = phone.Value;

                payer.Address = billingAddr;
            }

            // Populate payment requestDetails
            CurrencyCodeType currency = (CurrencyCodeType)
                Enum.Parse(typeof(CurrencyCodeType), currencyCode.SelectedValue);
            BasicAmountType paymentAmount = new BasicAmountType(currency, amount.Value);
            requestDetails.PaymentDetails.OrderTotal = paymentAmount;

            // Invoke the API
            DoDirectPaymentReq wrapper = new DoDirectPaymentReq();
            wrapper.DoDirectPaymentRequest = request;
            PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService();
            DoDirectPaymentResponseType response = service.DoDirectPayment(wrapper);

            // Check for API return status
            setKeyResponseObjects(service, response);
        }
Ejemplo n.º 14
0
        public ActionResult AddressAndPayment(FormCollection values)
        {
            // fill out basic info
            var cart = ShoppingCartHelper.GetCart(HttpContext);
            ViewData["cart"] = cart;
            var deliveryLocation = LocationHelper.GetDeliveryLocation(HttpContext);
            if (deliveryLocation == null)
            {
                deliveryLocation = db.University_Delivery.First(i => i.UniversityId == 1);
                LocationHelper.SetDeliveryLocation(HttpContext, deliveryLocation);
            }
            ViewData["deliveryLocation"] = deliveryLocation;
            DateTime deliveryTime;
            if (deliveryLocation.DeliveryTime.Hour < DateTime.Now.Hour)
            {
                deliveryTime = DateTime.Now.Date.AddDays(1).AddHours(deliveryLocation.DeliveryTime.Hour);
            }
            else
            {
                deliveryTime = DateTime.Now.Date.AddHours(deliveryLocation.DeliveryTime.Hour);
            }
            ViewData["deliveryTime"] = deliveryTime;
            var totalRewardPoints = db.Rewards.Sum(i => i.Amount);
            ViewData["totalRewardPoints"] = totalRewardPoints;

            //fillout order
            var order = new Order();
            var userId = MembershipHelper.GetUserIdByEmail(HttpContext.User.Identity.Name);
            order.Gross = cart.Gross;
            if (cart.CanUserRewardPoint)
            {
                order.rewardPoints = Convert.ToInt32(values["rewardPoints"]);
            }
            else
            {
                order.rewardPoints = 0;
            }
            order.Savings = order.rewardPoints / 100.0m;
            order.Tax = 0.0m;
            order.Fee = 0.0m;
            order.billingFirstName = values["billingFirstName"];
            order.billingLastName = values["billingLastName"];
            order.billingAddress1 = values["billingAddress1"];
            order.billingAddress2 = values["billingAddress2"];
            order.billingCity = values["billingCity"];
            order.billingState = values["billingState"];
            order.billingZipCode = values["billingZipCode"];
            order.PaymentType = (PaymentType)Enum.Parse(typeof(PaymentType), values["paymentType"]);
            order.cardNumber = values["cardNumber"];
            order.cardExpYear = int.Parse(values["cardExpYear"]);
            order.cardExpMonth = int.Parse(values["cardExpMonth"]);
            order.CSV = values["CSV"];
            order.NeedDeliveryInfo = cart.NeedDeliveryInfo;
            if (cart.NeedDeliveryInfo)
            {
                order.ReceiverFirstName = values["ReceiverFirstName"];
                order.ReceiverLastName = values["ReceiverLastName"];
                order.ReceiverPhoneNumber = values["ReceiverPhoneNumber"];
                order.DeliveryTime = deliveryTime;
            }
            order.PayerEmail = HttpContext.User.Identity.Name;
            order.UserId = userId.Value;
            order.PayerEmail = User.Identity.Name;
            order.OrderDescription = string.Join(",", cart.ShoppingCartItems.Select(i => i.Description).ToList());
            order.DeliveryLocationId = deliveryLocation.LocationId;
            PaymentStatusLevel paymentStatus = PaymentStatusLevel.WaitingForPayment;
            DeliveryInfo deliveryInfo = new DeliveryInfo() { ReceiverFirstName = order.ReceiverFirstName, ReceiverLastName = order.ReceiverLastName };

            if (!TryValidateModel(order))
            {
                return View("AddressAndPayment", "_CheckoutMaster", order);
            }
            else
            {

                if (order.PaymentType == PaymentType.CreditCard)
                {

                    DoDirectPaymentRequestType request = new DoDirectPaymentRequestType();
                    DoDirectPaymentRequestDetailsType requestDetails = new DoDirectPaymentRequestDetailsType();
                    request.DoDirectPaymentRequestDetails = requestDetails;
                    requestDetails.PaymentAction = PaymentActionCodeType.SALE;

                    // Populate card requestDetails
                    CreditCardDetailsType creditCard = new CreditCardDetailsType();
                    requestDetails.CreditCard = creditCard;
                    PayerInfoType payer = new PayerInfoType();
                    PersonNameType name = new PersonNameType();
                    name.FirstName = order.billingFirstName;
                    name.LastName = order.billingLastName;
                    payer.PayerName = name;
                    creditCard.CardOwner = payer;

                    creditCard.CreditCardNumber = order.cardNumber;
                    creditCard.CreditCardType = (CreditCardTypeType)
                        Enum.Parse(typeof(CreditCardTypeType), values["creditCardType"]);
                    creditCard.CVV2 = order.CSV;
                    creditCard.ExpMonth = order.cardExpMonth;
                    creditCard.ExpYear = order.cardExpYear;
                    requestDetails.PaymentDetails = new PaymentDetailsType();
                    AddressType billingAddr = new AddressType();
                    billingAddr.Name = order.billingFirstName + " " + order.billingLastName;
                    billingAddr.Street1 = order.billingAddress1;
                    billingAddr.Street2 = order.billingAddress2;
                    billingAddr.CityName = order.billingCity;
                    billingAddr.StateOrProvince = order.billingState;
                    billingAddr.Country = CountryCodeType.US;
                    billingAddr.PostalCode = order.billingZipCode;
                    payer.Address = billingAddr;
                    // Populate payment requestDetails
                    CurrencyCodeType currency = (CurrencyCodeType)
                        Enum.Parse(typeof(CurrencyCodeType), "USD");
                    BasicAmountType paymentAmount = new BasicAmountType(currency, order.FinalAmount.ToString());
                    requestDetails.PaymentDetails.OrderTotal = paymentAmount;

                    // Invoke the API
                    DoDirectPaymentReq wrapper = new DoDirectPaymentReq();
                    wrapper.DoDirectPaymentRequest = request;

                    PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService();

                    DoDirectPaymentResponseType response = service.DoDirectPayment(wrapper);

                    BillingInfo billingInfo = new BillingInfo()
                    {
                        BillingFirstName = order.billingFirstName,
                        BillingLastName = order.billingLastName,
                        BillingAddress1 = order.billingAddress1,
                        BillingAddress2 = order.billingAddress2,
                        City = order.billingCity,
                        State = order.billingState,
                        ZipCode = order.billingZipCode,
                        CountryCode = CountryCodeType.US
                    };

                    if (response.Ack.Equals(AckCodeType.FAILURE) ||
                        (response.Errors != null && response.Errors.Count > 0))
                    {
                        paymentStatus = PaymentStatusLevel.WaitingForPayment;
                    }
                    else
                    {
                        paymentStatus = PaymentStatusLevel.Paid;
                    }

                    OnPaymentComplete(order.PaymentType, paymentStatus, billingInfo, deliveryInfo, order);

                    if (order.OrderId == 0)
                    {
                        ViewBag.Errors = string.Join(",", response.Errors.Select(i => i.LongMessage).ToList());
                        ViewData["Errors"] = string.Join(",", response.Errors.Select(i => i.LongMessage).ToList());
                        return View("AddressAndPayment", "_CheckoutMaster", order);
                    }
                    return RedirectToAction("PaymentComplete", new { orderId = order.OrderId });
                }
                else if(order.PaymentType == PaymentType.Cash) {
                    paymentStatus = PaymentStatusLevel.WaitingForPayment;
                    OnPaymentComplete(order.PaymentType, paymentStatus, null, deliveryInfo, order);
                    return RedirectToAction("PaymentComplete", new { orderId = order.OrderId });
                }
                else
                {
                    OnPaymentComplete(order.PaymentType, PaymentStatusLevel.Paid, null, deliveryInfo, order);

                    return RedirectToAction("PaymentComplete", new { orderId = order.OrderId });
                }
            }
        }