Person's name associated with this address. Character length and limitations: 32 single-byte alphanumeric characters
        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;
        }
Пример #2
0
		private PaymentDetailsType CreatePayPalPaymentDetails(IInvoice invoice, ProcessorArgumentCollection args = null)
		{
			
			string articleBySkuPath = args.GetArticleBySkuPath(_settings.ArticleBySkuPath.IsEmpty() ? null : GetWebsiteUrl() + _settings.ArticleBySkuPath);
			var currencyCodeType = PayPalCurrency(invoice.CurrencyCode());
			var currencyDecimals = CurrencyDecimals(currencyCodeType);

			decimal itemTotal = 0;
            decimal taxTotal = 0;
			decimal shippingTotal = 0;
			AddressType shipAddress = null;

			var paymentDetailItems = new List<PaymentDetailsItemType>();
			foreach (var item in invoice.Items)
			{
				if (item.LineItemTfKey == Merchello.Core.Constants.TypeFieldKeys.LineItem.TaxKey) 
                {
					taxTotal = item.TotalPrice;
				} 
                else if (item.LineItemTfKey == Merchello.Core.Constants.TypeFieldKeys.LineItem.ShippingKey) 
                {
					shippingTotal = item.TotalPrice;
					var address = item.ExtendedData.GetAddress(Merchello.Core.AddressType.Shipping);
					if (address != null) {
						shipAddress = new AddressType() {
							Name = address.Name,
							Street1 = address.Address1,
							Street2 = address.Address2,
							PostalCode = address.PostalCode,
							CityName = address.Locality,
							StateOrProvince = address.Region,
							CountryName = address.Country().Name,
							Country = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), address.Country().CountryCode, true),
							Phone = address.Phone
						};
					}
				}
                else if (item.LineItemTfKey == Merchello.Core.Constants.TypeFieldKeys.LineItem.DiscountKey)
                {
                    var discountItem = new PaymentDetailsItemType
                    {
                        Name = item.Name,
                        ItemURL = (articleBySkuPath.IsEmpty() ? null : articleBySkuPath + item.Sku),
                        Amount = new BasicAmountType(currencyCodeType, PriceToString(item.Price*-1, currencyDecimals)),
                        Quantity = item.Quantity,
                    };
                    paymentDetailItems.Add(discountItem);
                    itemTotal -= item.TotalPrice;
                } 
                else {
					var paymentItem = new PaymentDetailsItemType {
						Name = item.Name,
						ItemURL = (articleBySkuPath.IsEmpty() ? null : articleBySkuPath + item.Sku),
						Amount = new BasicAmountType(currencyCodeType, PriceToString(item.Price, currencyDecimals)),
						Quantity = item.Quantity,
					};
					paymentDetailItems.Add(paymentItem);
					itemTotal += item.TotalPrice;
				}
			}

			var paymentDetails = new PaymentDetailsType
			{
				PaymentDetailsItem = paymentDetailItems,
				ItemTotal = new BasicAmountType(currencyCodeType, PriceToString(itemTotal, currencyDecimals)),
				TaxTotal = new BasicAmountType(currencyCodeType, PriceToString(taxTotal, currencyDecimals)),
				ShippingTotal = new BasicAmountType(currencyCodeType, PriceToString(shippingTotal, currencyDecimals)),
                OrderTotal = new BasicAmountType(currencyCodeType, PriceToString(invoice.Total, currencyDecimals)),
                PaymentAction = PaymentActionCodeType.ORDER,
				InvoiceID = invoice.InvoiceNumberPrefix + invoice.InvoiceNumber.ToString("0"),
				SellerDetails = new SellerDetailsType { PayPalAccountID = _settings.AccountId },
				PaymentRequestID = "PaymentRequest",
				ShipToAddress = shipAddress,
				NotifyURL = "http://IPNhost"
			};

			return paymentDetails;
		}
Пример #3
0
        private void populateRequestObject(SetExpressCheckoutRequestType request)
        {
            SetExpressCheckoutRequestDetailsType ecDetails = new SetExpressCheckoutRequestDetailsType();
            if(returnUrl.Value != "")
            {
                ecDetails.ReturnURL = returnUrl.Value;
            }
            if(cancelUrl.Value != "")
            {
                ecDetails.CancelURL = cancelUrl.Value;
            }
            if (buyerEmail.Value != "")
            {
                ecDetails.BuyerEmail = buyerEmail.Value;
            }

            //Fix for release
            //NOTE: Setting this field overrides the setting you specified in your Merchant Account Profile
            if (reqConfirmShipping.SelectedIndex != 0)
            {
                ecDetails.ReqConfirmShipping = reqConfirmShipping.SelectedValue;
            }

            if (addressoverride.SelectedIndex != 0)
            {
                ecDetails.AddressOverride = addressoverride.SelectedValue;
            }

            if (noShipping.SelectedIndex != 0)
            {
                ecDetails.NoShipping = noShipping.SelectedValue;
            }
            if (solutionType.SelectedIndex != 0)
            {
                ecDetails.SolutionType = (SolutionTypeType)
                    Enum.Parse(typeof(SolutionTypeType), solutionType.SelectedValue);
            }

            /* Populate payment requestDetails.
             * SetExpressCheckout allows parallel payments of upto 10 payments.
             * This samples shows just one payment.
             */
            PaymentDetailsType paymentDetails = new PaymentDetailsType();
            ecDetails.PaymentDetails.Add(paymentDetails);
            double orderTotal = 0.0;
            double itemTotal = 0.0;
            CurrencyCodeType currency = (CurrencyCodeType)
                Enum.Parse(typeof(CurrencyCodeType), currencyCode.SelectedValue);
            if (shippingTotal.Value != "")
            {
                paymentDetails.ShippingTotal = new BasicAmountType(currency, shippingTotal.Value);
                orderTotal += Double.Parse(shippingTotal.Value);
            }
            if (insuranceTotal.Value != "" && !double.Parse(insuranceTotal.Value).Equals(0.0))
            {
                paymentDetails.InsuranceTotal = new BasicAmountType(currency, insuranceTotal.Value);
                paymentDetails.InsuranceOptionOffered = "true";
                orderTotal += Double.Parse(insuranceTotal.Value);
            }
            if (handlingTotal.Value != "")
            {
                paymentDetails.HandlingTotal = new BasicAmountType(currency, handlingTotal.Value);
                orderTotal += Double.Parse(handlingTotal.Value);
            }
            if (taxTotal.Value != "")
            {
                paymentDetails.TaxTotal = new BasicAmountType(currency, taxTotal.Value);
                orderTotal += Double.Parse(taxTotal.Value);
            }
            if (orderDescription.Value != "")
            {
                paymentDetails.OrderDescription = orderDescription.Value;
            }
            paymentDetails.PaymentAction = (PaymentActionCodeType)
                Enum.Parse(typeof(PaymentActionCodeType), paymentAction.SelectedValue);

            if (shippingName.Value != "" && shippingStreet1.Value != ""
                && shippingCity.Value != "" && shippingState.Value != ""
                && shippingCountry.Value != "" && shippingPostalCode.Value != "")
            {
                AddressType shipAddress = new AddressType();
                shipAddress.Name = shippingName.Value;
                shipAddress.Street1 = shippingStreet1.Value;
                shipAddress.Street2 = shippingStreet2.Value;
                shipAddress.CityName = shippingCity.Value;
                shipAddress.StateOrProvince = shippingState.Value;
                shipAddress.Country = (CountryCodeType)
                    Enum.Parse(typeof(CountryCodeType), shippingCountry.Value);
                shipAddress.PostalCode = shippingPostalCode.Value;

                //Fix for release
                shipAddress.Phone = shippingPhone.Value;

                ecDetails.PaymentDetails[0].ShipToAddress = shipAddress;
            }

            // Each payment can include requestDetails about multiple items
            // This example shows just one payment item
            if (itemName.Value != null && itemAmount.Value != null && itemQuantity.Value != null)
            {
                PaymentDetailsItemType itemDetails = new PaymentDetailsItemType();
                itemDetails.Name = itemName.Value;
                itemDetails.Amount = new BasicAmountType(currency, itemAmount.Value);
                itemDetails.Quantity = Int32.Parse(itemQuantity.Value);
                itemDetails.ItemCategory = (ItemCategoryType)
                    Enum.Parse(typeof(ItemCategoryType), itemCategory.SelectedValue);
                itemTotal += Double.Parse(itemDetails.Amount.value) * itemDetails.Quantity.Value;
                if (salesTax.Value != "")
                {
                    itemDetails.Tax = new BasicAmountType(currency, salesTax.Value);
                    orderTotal += Double.Parse(salesTax.Value);
                }
                if (itemDescription.Value != "")
                {
                    itemDetails.Description = itemDescription.Value;
                }
                paymentDetails.PaymentDetailsItem.Add(itemDetails);
            }

            orderTotal += itemTotal;
            paymentDetails.ItemTotal = new BasicAmountType(currency, itemTotal.ToString());
            paymentDetails.OrderTotal = new BasicAmountType(currency, orderTotal.ToString());

            // Set Billing agreement (for Reference transactions & Recurring payments)
            if (billingAgreementText.Value != "")
            {
                BillingCodeType billingCodeType = (BillingCodeType)
                    Enum.Parse(typeof(BillingCodeType), billingType.SelectedValue);
                BillingAgreementDetailsType baType = new BillingAgreementDetailsType(billingCodeType);
                baType.BillingAgreementDescription = billingAgreementText.Value;
                ecDetails.BillingAgreementDetails.Add(baType);
            }

            //Fix for release
            if (localeCode.SelectedIndex != 0)
            {
                ecDetails.LocaleCode = localeCode.SelectedValue;
            }

            // Set styling attributes for PayPal page
            if (pageStyle.Value != "")
            {
                ecDetails.PageStyle = pageStyle.Value;
            }
            if (cppheaderimage.Value != "")
            {
                ecDetails.cppHeaderImage = cppheaderimage.Value;
            }
            if (cppheaderbordercolor.Value != "")
            {
                ecDetails.cppHeaderBorderColor = cppheaderbordercolor.Value;
            }
            if (cppheaderbackcolor.Value != "")
            {
                ecDetails.cppHeaderBackColor = cppheaderbackcolor.Value;
            }
            if (cpppayflowcolor.Value != "")
            {
                ecDetails.cppPayflowColor = cpppayflowcolor.Value;
            }
            if (brandName.Value != "")
            {
                ecDetails.BrandName = brandName.Value;
            }

            request.SetExpressCheckoutRequestDetails = ecDetails;
        }
Пример #4
0
        public ActionResult PaypalExpress(CheckoutModel model, SolutionTypeType solutionType = SolutionTypeType.SOLE)
        {
            // Create request object
            var request = new SetExpressCheckoutRequestType();
            var ecDetails = new SetExpressCheckoutRequestDetailsType
            {
                CallbackTimeout = "3",
                ReturnURL = Url.Action("PaypalExpressSuccess", "Checkout", null, "http"),
                CancelURL = Url.Action("Index", "Checkout", null, "http"),
                SolutionType = solutionType
            };

            var currency = (CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), Ch.CustomerSession.Currency.ToUpper());
            model = PrepareCheckoutModel(model);
            model.Payments = model.Payments ?? GetPayments().ToArray();
            var payment = _paymentClient.GetPaymentMethod(model.PaymentMethod ?? "Paypal");
            var configMap = payment.CreateSettings();

            //Create Shipping methods
            var shippingMethods = GetShipinngMethodModels();
            var noShippingMethod = !shippingMethods.Any(x => x.IsCurrent);
            string currentShippingOption = null;

            for (var i = 0; i < shippingMethods.Length; i++)
            {
                var shipping = shippingMethods[i];
                var shippingOptionIsDefault = "0";
                if (shipping.IsCurrent || noShippingMethod && i == 0)
                {
                    shippingOptionIsDefault = "1";
                    currentShippingOption = shipping.Method.Name;
                }

                ecDetails.FlatRateShippingOptions.Add(new ShippingOptionType
                {
                    ShippingOptionAmount = new BasicAmountType(currency, FormatMoney(shipping.Price)),
                    ShippingOptionIsDefault = shippingOptionIsDefault,
                    ShippingOptionName = shipping.Method.Name,
                });
            }

            var recalcualteCart = false;

            if (!string.Equals(model.ShippingMethod,currentShippingOption))
            {
                model.ShippingMethod = currentShippingOption;
                recalcualteCart = true;
            }

            if (!string.Equals(model.PaymentMethod, payment.Name))
            {
                model.PaymentMethod = payment.Name;
                recalcualteCart = true;
            }

            if (recalcualteCart)
            {
                //Must recalculate cart as prices could have changed
                RecalculateCart(model);
            }

            // (Optional) Email address of the buyer as entered during checkout. PayPal uses this value to pre-fill the PayPal membership sign-up portion on the PayPal pages.
            if (model.BillingAddress != null && !string.IsNullOrEmpty(model.BillingAddress.Address.Email))
            {
                ecDetails.BuyerEmail = model.BillingAddress.Address.Email;
            }

            ecDetails.NoShipping = "2";
            ecDetails.PaymentDetails.Add(GetPaypalPaymentDetail(currency, PaymentActionCodeType.SALE));
            ecDetails.MaxAmount = new BasicAmountType(currency, FormatMoney(Math.Max(Ch.Cart.Total, Ch.Cart.Subtotal)));
            ecDetails.LocaleCode = new RegionInfo(Thread.CurrentThread.CurrentUICulture.LCID).TwoLetterISORegionName;
            //paymentDetails.OrderDescription = Ch.Cart.Name;

            AddressModel modelAddress = null;

            if (!model.UseForShipping && model.ShippingAddress != null && DoValidateModel(model.ShippingAddress.Address))
            {
                modelAddress = model.ShippingAddress.Address;
            }
            else if (model.BillingAddress != null && DoValidateModel(model.BillingAddress.Address))
            {
                modelAddress = model.BillingAddress.Address;
            }

            if (modelAddress != null)
            {
                ecDetails.AddressOverride = "1";

                var shipAddress = new AddressType
                {
                    Name = string.Format("{0} {1}", modelAddress.FirstName, modelAddress.LastName),
                    Street1 = modelAddress.Line1,
                    Street2 = modelAddress.Line2,
                    CityName = modelAddress.City,
                    StateOrProvince = modelAddress.StateProvince,
                    Country = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), modelAddress.CountryCode.Substring(0, 2)),
                    PostalCode = modelAddress.PostalCode,
                    Phone = modelAddress.DaytimePhoneNumber
                };
                ecDetails.PaymentDetails[0].ShipToAddress = shipAddress;
            }

            request.SetExpressCheckoutRequestDetails = ecDetails;


            // Invoke the API
            var wrapper = new SetExpressCheckoutReq { SetExpressCheckoutRequest = request };

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

            SetExpressCheckoutResponseType setEcResponse = null;

            try
            {
                setEcResponse = service.SetExpressCheckout(wrapper);
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", @"Paypal failure".Localize());
                ModelState.AddModelError("", ex.Message);
            }

            if (setEcResponse != null)
            {
                // Check for API return status
                if (setEcResponse.Ack.Equals(AckCodeType.FAILURE) ||
                    (setEcResponse.Errors != null && setEcResponse.Errors.Count > 0))
                {
                    ModelState.AddModelError("", @"Paypal failure".Localize());

                    foreach (var error in setEcResponse.Errors)
                    {
                        ModelState.AddModelError("", error.LongMessage);
                    }
                }
                else
                {
                    var redirectUrl =
                        string.Format(
                            configMap.ContainsKey("URL")
                                ? configMap["URL"]
                                : "https://www.sandbox.paypal.com/webscr&amp;cmd={0}",
                            "_express-checkout&token=" + setEcResponse.Token);
                    TempData.Add("checkout_" + setEcResponse.Token,model);
                    return Redirect(redirectUrl);
                }
            }

            return View("Index", model);
        }
        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);
        }
Пример #6
0
        private PaymentDetailsType CreatePayPalPaymentDetails(IInvoice invoice, ProcessorArgumentCollection args = null)
        {
            string articleBySkuPath = args.GetArticleBySkuPath(_settings.ArticleBySkuPath.IsEmpty() ? null : GetWebsiteUrl() + _settings.ArticleBySkuPath);
            var    currencyCodeType = PayPalCurrency(invoice.CurrencyCode());
            var    currencyDecimals = CurrencyDecimals(currencyCodeType);

            decimal     itemTotal     = 0;
            decimal     taxTotal      = 0;
            decimal     shippingTotal = 0;
            AddressType shipAddress   = null;

            var paymentDetailItems = new List <PaymentDetailsItemType>();

            foreach (var item in invoice.Items)
            {
                if (item.LineItemTfKey == Merchello.Core.Constants.TypeFieldKeys.LineItem.TaxKey)
                {
                    taxTotal = item.TotalPrice;
                }
                else if (item.LineItemTfKey == Merchello.Core.Constants.TypeFieldKeys.LineItem.ShippingKey)
                {
                    shippingTotal = item.TotalPrice;
                    var address = item.ExtendedData.GetAddress(Merchello.Core.AddressType.Shipping);
                    if (address != null)
                    {
                        shipAddress = new AddressType()
                        {
                            Name            = address.Name,
                            Street1         = address.Address1,
                            Street2         = address.Address2,
                            PostalCode      = address.PostalCode,
                            CityName        = address.Locality,
                            StateOrProvince = address.Region,
                            CountryName     = address.Country().Name,
                            Country         = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), address.Country().CountryCode, true),
                            Phone           = address.Phone
                        };
                    }
                }
                else if (item.LineItemTfKey == Merchello.Core.Constants.TypeFieldKeys.LineItem.DiscountKey)
                {
                    var discountItem = new PaymentDetailsItemType
                    {
                        Name     = item.Name,
                        ItemURL  = (articleBySkuPath.IsEmpty() ? null : articleBySkuPath + item.Sku),
                        Amount   = new BasicAmountType(currencyCodeType, PriceToString(item.Price * -1, currencyDecimals)),
                        Quantity = item.Quantity,
                    };
                    paymentDetailItems.Add(discountItem);
                    itemTotal -= item.TotalPrice;
                }
                else
                {
                    var paymentItem = new PaymentDetailsItemType {
                        Name     = item.Name,
                        ItemURL  = (articleBySkuPath.IsEmpty() ? null : articleBySkuPath + item.Sku),
                        Amount   = new BasicAmountType(currencyCodeType, PriceToString(item.Price, currencyDecimals)),
                        Quantity = item.Quantity,
                    };
                    paymentDetailItems.Add(paymentItem);
                    itemTotal += item.TotalPrice;
                }
            }

            var paymentDetails = new PaymentDetailsType
            {
                PaymentDetailsItem = paymentDetailItems,
                ItemTotal          = new BasicAmountType(currencyCodeType, PriceToString(itemTotal, currencyDecimals)),
                TaxTotal           = new BasicAmountType(currencyCodeType, PriceToString(taxTotal, currencyDecimals)),
                ShippingTotal      = new BasicAmountType(currencyCodeType, PriceToString(shippingTotal, currencyDecimals)),
                OrderTotal         = new BasicAmountType(currencyCodeType, PriceToString(invoice.Total, currencyDecimals)),
                PaymentAction      = PaymentActionCodeType.ORDER,
                InvoiceID          = invoice.InvoiceNumberPrefix + invoice.InvoiceNumber.ToString("0"),
                SellerDetails      = new SellerDetailsType {
                    PayPalAccountID = _settings.AccountId
                },
                PaymentRequestID = "PaymentRequest",
                ShipToAddress    = shipAddress,
                NotifyURL        = "http://IPNhost"
            };

            return(paymentDetails);
        }
Пример #7
0
        private static AddressModel ConvertToPaypalAddress(AddressType address, string name)
        {
            var countryCode = "USA";
            var firstName = address.Name;
            var lastName = address.Name;

            if (address.Country.HasValue)
            {
                try
                {
                    //Paypal uses two letter region code, we use 3 letters in jurisdiction
                    var region = new RegionInfo(address.Country.Value.ToString());
                    countryCode = region.ThreeLetterISORegionName;
                }
                catch
                {
                    //use default
                }
            }

            var splited = address.Name.Split(new[] { ' ' });
            if (!string.IsNullOrEmpty(address.Name) && splited.Length > 1)
            {
                
                firstName = splited[0];
                lastName = splited[1];
            }

            return new AddressModel
            {
                Name = name,
                FirstName = firstName,
                LastName = lastName,
                City = address.CityName,
                CountryCode = countryCode,
                DaytimePhoneNumber = address.Phone ?? "none",
                CountryName = address.CountryName,
                Line1 = address.Street1,
                Line2 = address.Street2,
                PostalCode = address.PostalCode,
                StateProvince = address.StateOrProvince
            };
        }
        private void populateRequest(CreateRecurringPaymentsProfileRequestType request)
        {
            CurrencyCodeType currency = (CurrencyCodeType)
                Enum.Parse(typeof(CurrencyCodeType), "USD");

            // Set EC-Token or Credit card requestDetails
            CreateRecurringPaymentsProfileRequestDetailsType profileDetails = new CreateRecurringPaymentsProfileRequestDetailsType();
            request.CreateRecurringPaymentsProfileRequestDetails = profileDetails;

            if(token.Value != "")
            {
                profileDetails.Token = token.Value;
            }
            else if (creditCardNumber.Value != "" && cvv.Value != "")
            {
                CreditCardDetailsType cc = new CreditCardDetailsType();
                cc.CreditCardNumber = creditCardNumber.Value;
                cc.CVV2 = cvv.Value;
                cc.ExpMonth = Int32.Parse(expMonth.SelectedValue);
                cc.ExpYear = Int32.Parse(expYear.SelectedValue);
                profileDetails.CreditCard = cc;
            }

            // Populate Recurring Payments Profile Details
            RecurringPaymentsProfileDetailsType rpProfileDetails =
                new RecurringPaymentsProfileDetailsType(billingStartDate.Text);
            profileDetails.RecurringPaymentsProfileDetails = rpProfileDetails;
            if(subscriberName.Value != "")
            {
                rpProfileDetails.SubscriberName = subscriberName.Value;
            }
            if(shippingName.Value != "" && shippingStreet1.Value != "" && shippingCity.Value != ""
                && shippingState.Value != "" && shippingPostalCode.Value != "" && shippingCountry.Value != "")
            {
                AddressType shippingAddr = new AddressType();
                shippingAddr.Name = shippingName.Value;
                shippingAddr.Street1 = shippingStreet1.Value;
                shippingAddr.CityName = shippingCity.Value;
                shippingAddr.StateOrProvince = shippingCity.Value;
                shippingAddr.CountryName = shippingCountry.Value;
                shippingAddr.PostalCode = shippingPostalCode.Value;

                if(shippingStreet2.Value != "")
                {
                    shippingAddr.Street2 = shippingStreet2.Value;
                }
                if(shippingPhone.Value != "")
                {
                    shippingAddr.Phone = shippingPhone.Value;
                }
                rpProfileDetails.SubscriberShippingAddress = shippingAddr;
            }

            // Populate schedule requestDetails
            ScheduleDetailsType scheduleDetails = new ScheduleDetailsType();
            profileDetails.ScheduleDetails = scheduleDetails;
            if(profileDescription.Value != "")
            {
                scheduleDetails.Description = profileDescription.Value;
            }
            if(maxFailedPayments.Value != "")
            {
                scheduleDetails.MaxFailedPayments = Int32.Parse(maxFailedPayments.Value);
            }
            if(autoBillOutstandingAmount.SelectedIndex != 0)
            {
                scheduleDetails.AutoBillOutstandingAmount = (AutoBillType)
                    Enum.Parse(typeof(AutoBillType), autoBillOutstandingAmount.SelectedValue);
            }
            if(initialAmount.Value != "")
            {
                ActivationDetailsType activationDetails =
                    new ActivationDetailsType(new BasicAmountType(currency, initialAmount.Value));
                if(failedInitialAmountAction.SelectedIndex != 0)
                {
                    activationDetails.FailedInitialAmountAction = (FailedPaymentActionType)
                        Enum.Parse(typeof(FailedPaymentActionType), failedInitialAmountAction.SelectedValue);
                }
                scheduleDetails.ActivationDetails = activationDetails;
            }
            if(trialBillingAmount.Value != "" && trialBillingFrequency.Value != ""
                    && trialBillingCycles.Value != "")
            {
                int frequency = Int32.Parse(trialBillingFrequency.Value);
                BasicAmountType paymentAmount = new BasicAmountType(currency, trialBillingAmount.Value);
                BillingPeriodType period = (BillingPeriodType)
                    Enum.Parse(typeof(BillingPeriodType), trialBillingPeriod.SelectedValue);
                int numCycles = Int32.Parse(trialBillingCycles.Value);

                BillingPeriodDetailsType trialPeriod = new BillingPeriodDetailsType(period, frequency, paymentAmount);
                trialPeriod.TotalBillingCycles = numCycles;
                if(trialShippingAmount.Value != "")
                {
                    trialPeriod.ShippingAmount = new BasicAmountType(currency, trialShippingAmount.Value);
                }
                if(trialTaxAmount.Value != "")
                {
                    trialPeriod.TaxAmount = new BasicAmountType(currency, trialTaxAmount.Value);
                }

                scheduleDetails.TrialPeriod = trialPeriod;
            }
            if(billingAmount.Value != "" && billingFrequency.Value != ""
                    && totalBillingCycles.Value != "")
            {
                int frequency = Int32.Parse(billingFrequency.Value);
                BasicAmountType paymentAmount = new BasicAmountType(currency, billingAmount.Value);
                BillingPeriodType period = (BillingPeriodType)
                    Enum.Parse(typeof(BillingPeriodType), billingPeriod.SelectedValue);
                int numCycles = Int32.Parse(totalBillingCycles.Value);

                BillingPeriodDetailsType paymentPeriod = new BillingPeriodDetailsType(period, frequency, paymentAmount);
                paymentPeriod.TotalBillingCycles = numCycles;
                if(trialShippingAmount.Value != "")
                {
                    paymentPeriod.ShippingAmount = new BasicAmountType(currency, shippingAmount.Value);
                }
                if(trialTaxAmount.Value != "")
                {
                    paymentPeriod.TaxAmount = new BasicAmountType(currency, taxAmount.Value);
                }
                scheduleDetails.PaymentPeriod = paymentPeriod;
            }
        }
        private void populateRequestObject(SetExpressCheckoutRequestType request)
        {
            SetExpressCheckoutRequestDetailsType ecDetails = new SetExpressCheckoutRequestDetailsType();
            if(returnUrl.Value != string.Empty)
            {
                ecDetails.ReturnURL = returnUrl.Value;
            }
            if(cancelUrl.Value != string.Empty)
            {
                ecDetails.CancelURL = cancelUrl.Value;
            }
            // (Optional) Email address of the buyer as entered during checkout. PayPal uses this value to pre-fill the PayPal membership sign-up portion on the PayPal pages.
            if (buyerEmail.Value != string.Empty)
            {
                ecDetails.BuyerEmail = buyerEmail.Value;
            }

            // Fix for release
            // NOTE: Setting this field overrides the setting you specified in your Merchant Account Profile
            // Indicates whether or not you require the buyer's shipping address on
            // file with PayPal be a confirmed address. For digital goods,
            // this field is required, and you must set it to 0. It is one of the following values:
            //  0 – You do not require the buyer's shipping address be a confirmed address.
            //  1 – You require the buyer's shipping address be a confirmed address.
            //  Note:
            //  Setting this field overrides the setting you specified in your Merchant Account Profile.
            //  Character length and limitations: 1 single-byte numeric character
            if (reqConfirmShipping.SelectedIndex != 0)
            {
                ecDetails.ReqConfirmShipping = reqConfirmShipping.SelectedValue;
            }

            // (Optional) Determines whether or not the PayPal pages should
            //display the shipping address set by you in this SetExpressCheckout request,
            // not the shipping address on file with PayPal for this buyer. Displaying
            // the PayPal street address on file does not allow the buyer to edit that address.
            // It is one of the following values:
            //  0 – The PayPal pages should not display the shipping address.
            //  1 – The PayPal pages should display the shipping address.
            // Character length and limitations: 1 single-byte numeric character
            if (addressoverride.SelectedIndex != 0)
            {
                ecDetails.AddressOverride = addressoverride.SelectedValue;
            }

            if (noShipping.SelectedIndex != 0)
            {
                ecDetails.NoShipping = noShipping.SelectedValue;
            }
            if (solutionType.SelectedIndex != 0)
            {
                ecDetails.SolutionType = (SolutionTypeType)
                    Enum.Parse(typeof(SolutionTypeType), solutionType.SelectedValue);
            }

            /* Populate payment requestDetails.
             * SetExpressCheckout allows parallel payments of upto 10 payments.
             * This samples shows just one payment.
             */
            PaymentDetailsType paymentDetails = new PaymentDetailsType();
            ecDetails.PaymentDetails.Add(paymentDetails);
            // (Required) 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.
            double orderTotal = 0.0;
            // Sum of cost of all items in this order. For digital goods, this field is required.
            double itemTotal = 0.0;
            CurrencyCodeType currency = (CurrencyCodeType)
                Enum.Parse(typeof(CurrencyCodeType), currencyCode.SelectedValue);
            // (Optional) Total shipping costs for this order.
            // Note:
            // You must set the currencyID attribute to one of the 3-character currency codes
            // for any of the supported PayPal currencies.
            // Character length and limitations:
            // Value is a positive number which cannot exceed $10,000 USD in any currency.
            // It includes no currency symbol.
            // It must have 2 decimal places, the decimal separator must be a period (.),
            // and the optional thousands separator must be a comma (,)
            if (shippingTotal.Value != string.Empty)
            {
                paymentDetails.ShippingTotal = new BasicAmountType(currency, shippingTotal.Value);
                orderTotal += Convert.ToDouble(shippingTotal.Value);
            }
            //(Optional) Total shipping insurance costs for this order.
            // The value must be a non-negative currency amount or null if you offer insurance options.
            // Note:
            // You must set the currencyID attribute to one of the 3-character currency
            // codes for any of the supported PayPal currencies.
            // Character length and limitations:
            // Value is a positive number which cannot exceed $10,000 USD in any currency.
            // It includes no currency symbol. It must have 2 decimal places,
            // the decimal separator must be a period (.),
            // and the optional thousands separator must be a comma (,).
            // InsuranceTotal is available since version 53.0.
            if (insuranceTotal.Value != string.Empty && !Convert.ToDouble(insuranceTotal.Value).Equals(0.0))
            {
                paymentDetails.InsuranceTotal = new BasicAmountType(currency, insuranceTotal.Value);
                paymentDetails.InsuranceOptionOffered = "true";
                orderTotal += Convert.ToDouble(insuranceTotal.Value);
            }
            //(Optional) Total handling costs for this order.
            // Note:
            // You must set the currencyID attribute to one of the 3-character currency codes
            // for any of the supported PayPal currencies.
            // Character length and limitations: Value is a positive number which
            // cannot exceed $10,000 USD in any currency.
            // It includes no currency symbol. It must have 2 decimal places,
            // the decimal separator must be a period (.), and the optional
            // thousands separator must be a comma (,).
            if (handlingTotal.Value != string.Empty)
            {
                paymentDetails.HandlingTotal = new BasicAmountType(currency, handlingTotal.Value);
                orderTotal += Convert.ToDouble(handlingTotal.Value);
            }
            //(Optional) Sum of tax for all items in this order.
            // Note:
            // You must set the currencyID attribute to one of the 3-character currency codes
            // for any of the supported PayPal currencies.
            // Character length and limitations: Value is a positive number which
            // cannot exceed $10,000 USD in any currency. It includes no currency symbol.
            // It must have 2 decimal places, the decimal separator must be a period (.),
            // and the optional thousands separator must be a comma (,).
            if (taxTotal.Value != string.Empty)
            {
                paymentDetails.TaxTotal = new BasicAmountType(currency, taxTotal.Value);
                orderTotal += Convert.ToDouble(taxTotal.Value);
            }
            //(Optional) Description of items the buyer is purchasing.
            // Note:
            // The value you specify is available only if the transaction includes a purchase.
            // This field is ignored if you set up a billing agreement for a recurring payment
            // that is not immediately charged.
            // Character length and limitations: 127 single-byte alphanumeric characters
            if (orderDescription.Value != string.Empty)
            {
                paymentDetails.OrderDescription = orderDescription.Value;
            }
            // How you want to obtain payment. When implementing parallel payments,
            // this field is required and must be set to Order.
            // When implementing digital goods, this field is required and must be set to Sale.
            // If the transaction does not include a one-time purchase, this field is ignored.
            // It is one of the following values:
            //   Sale – This is a final sale for which you are requesting payment (default).
            //   Authorization – This payment is a basic authorization subject to settlement with PayPal Authorization and Capture.
            //   Order – This payment is an order authorization subject to settlement with PayPal Authorization and Capture.
            paymentDetails.PaymentAction = (PaymentActionCodeType)
                Enum.Parse(typeof(PaymentActionCodeType), paymentAction.SelectedValue);

            if (shippingName.Value != string.Empty && shippingStreet1.Value != string.Empty
                && shippingCity.Value != string.Empty && shippingState.Value != string.Empty
                && shippingCountry.Value != string.Empty && shippingPostalCode.Value != string.Empty)
            {
                AddressType shipAddress = new AddressType();
                // Person's name associated with this shipping address.
                // It is required if using a shipping address.
                // Character length and limitations: 32 single-byte characters
                shipAddress.Name = shippingName.Value;
                //First street address. It is required if using a shipping address.
                //Character length and limitations: 100 single-byte characters
                shipAddress.Street1 = shippingStreet1.Value;
                //(Optional) Second street address.
                //Character length and limitations: 100 single-byte characters
                shipAddress.Street2 = shippingStreet2.Value;
                //Name of city. It is required if using a shipping address.
                //Character length and limitations: 40 single-byte characters
                shipAddress.CityName = shippingCity.Value;
                // State or province. It is required if using a shipping address.
                // Character length and limitations: 40 single-byte characters
                shipAddress.StateOrProvince = shippingState.Value;
                // Country code. It is required if using a shipping address.
                //  Character length and limitations: 2 single-byte characters
                shipAddress.Country = (CountryCodeType)
                    Enum.Parse(typeof(CountryCodeType), shippingCountry.Value);
                // U.S. ZIP code or other country-specific postal code.
                // It is required if using a U.S. shipping address and may be
                // required for other countries.
                // Character length and limitations: 20 single-byte characters
                shipAddress.PostalCode = shippingPostalCode.Value;

                //Fix for release
                shipAddress.Phone = shippingPhone.Value;

                ecDetails.PaymentDetails[0].ShipToAddress = shipAddress;
            }

            // Each payment can include requestDetails about multiple items
            // This example shows just one payment item
            if (itemName.Value != null && itemAmount.Value != null && itemQuantity.Value != null)
            {
                PaymentDetailsItemType itemDetails = new PaymentDetailsItemType();
                itemDetails.Name = itemName.Value;
                itemDetails.Amount = new BasicAmountType(currency, itemAmount.Value);
                itemDetails.Quantity = Convert.ToInt32(itemQuantity.Value);
                // Indicates whether an item is digital or physical. For digital goods, this field is required and must be set to Digital. It is one of the following values:
                //   1.Digital
                //   2.Physical
                //  This field is available since version 65.1.
                itemDetails.ItemCategory = (ItemCategoryType)
                    Enum.Parse(typeof(ItemCategoryType), itemCategory.SelectedValue);
                itemTotal += Convert.ToDouble(itemDetails.Amount.value) * itemDetails.Quantity.Value;
                //(Optional) Item sales tax.
                //    Note: You must set the currencyID attribute to one of
                //    the 3-character currency codes for any of the supported PayPal currencies.
                //    Character length and limitations: Value is a positive number which cannot exceed $10,000 USD in any currency.
                //    It includes no currency symbol. It must have 2 decimal places, the decimal separator must be a period (.),
                //    and the optional thousands separator must be a comma (,).
                if (salesTax.Value != string.Empty)
                {
                    itemDetails.Tax = new BasicAmountType(currency, salesTax.Value);
                    orderTotal += Convert.ToDouble(salesTax.Value);
                }
                //(Optional) Item description.
                // Character length and limitations: 127 single-byte characters
                // This field is introduced in version 53.0.
                if (itemDescription.Value != string.Empty)
                {
                    itemDetails.Description = itemDescription.Value;
                }
                paymentDetails.PaymentDetailsItem.Add(itemDetails);
            }

            orderTotal += itemTotal;
            paymentDetails.ItemTotal = new BasicAmountType(currency, itemTotal.ToString());
            paymentDetails.OrderTotal = new BasicAmountType(currency, orderTotal.ToString());

            //(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.
            //Character length and limitations: 2,048 single-byte alphanumeric characters
            paymentDetails.NotifyURL = ipnNotificationUrl.Value.Trim();

            // Set Billing agreement (for Reference transactions & Recurring payments)
            if (billingAgreementText.Value != string.Empty)
            {
                 //(Required) Type of billing agreement. For recurring payments,
                 //this field must be set to RecurringPayments.
                 //In this case, you can specify up to ten billing agreements.
                 //Other defined values are not valid.
                 //Type of billing agreement for reference transactions.
                 //You must have permission from PayPal to use this field.
                 //This field must be set to one of the following values:
                 //   1. MerchantInitiatedBilling - PayPal creates a billing agreement
                 //      for each transaction associated with buyer.You must specify
                 //      version 54.0 or higher to use this option.
                 //   2. MerchantInitiatedBillingSingleAgreement - PayPal creates a
                 //      single billing agreement for all transactions associated with buyer.
                 //      Use this value unless you need per-transaction billing agreements.
                 //      You must specify version 58.0 or higher to use this option.
                BillingCodeType billingCodeType = (BillingCodeType)
                    Enum.Parse(typeof(BillingCodeType), billingType.SelectedValue);
                BillingAgreementDetailsType baType = new BillingAgreementDetailsType(billingCodeType);
                baType.BillingAgreementDescription = billingAgreementText.Value;
                ecDetails.BillingAgreementDetails.Add(baType);
            }

            //(Optional) Locale of pages displayed by PayPal during Express Checkout.
            if (localeCode.SelectedIndex != 0)
            {
                ecDetails.LocaleCode = localeCode.SelectedValue;
            }

            // (Optional) Name of the Custom Payment Page Style for payment pages associated with this button or link. It corresponds to the HTML variable page_style for customizing payment pages. It is the same name as the Page Style Name you chose to add or edit the page style in your PayPal Account profile.
            if (pageStyle.Value != string.Empty)
            {
                ecDetails.PageStyle = pageStyle.Value;
            }
            // (Optional) URL for the image you want to appear at the top left of the payment page. The image has a maximum size of 750 pixels wide by 90 pixels high. PayPal recommends that you provide an image that is stored on a secure (https) server. If you do not specify an image, the business name displays.
            if (cppheaderimage.Value != string.Empty)
            {
                ecDetails.cppHeaderImage = cppheaderimage.Value;
            }
            // (Optional) Sets the border color around the header of the payment page. The border is a 2-pixel perimeter around the header space, which is 750 pixels wide by 90 pixels high. By default, the color is black.
            if (cppheaderbordercolor.Value != string.Empty)
            {
                ecDetails.cppHeaderBorderColor = cppheaderbordercolor.Value;
            }
            // (Optional) Sets the background color for the header of the payment page. By default, the color is white.
            if (cppheaderbackcolor.Value != string.Empty)
            {
                ecDetails.cppHeaderBackColor = cppheaderbackcolor.Value;
            }
            // (Optional) Sets the background color for the payment page. By default, the color is white.
            if (cpppayflowcolor.Value != string.Empty)
            {
                ecDetails.cppPayflowColor = cpppayflowcolor.Value;
            }
            // (Optional) A label that overrides the business name in the PayPal account on the PayPal hosted checkout pages.
            if (brandName.Value != string.Empty)
            {
                ecDetails.BrandName = brandName.Value;
            }

            request.SetExpressCheckoutRequestDetails = ecDetails;
        }
        private void populateRequestObject(UpdateRecurringPaymentsProfileRequestType request)
        {
            CurrencyCodeType currency = (CurrencyCodeType)
                Enum.Parse(typeof(CurrencyCodeType), "USD");
            // Set EC-Token or Credit card requestDetails
            UpdateRecurringPaymentsProfileRequestDetailsType profileDetails = new UpdateRecurringPaymentsProfileRequestDetailsType();
            request.UpdateRecurringPaymentsProfileRequestDetails = profileDetails;

            profileDetails.ProfileID = profileId.Value;
            if (note.Value != "")
            {
                profileDetails.Note = note.Value;
            }
            // Populate Recurring Payments Profile Details
            if (subscriberName.Value != "")
            {
                profileDetails.SubscriberName = subscriberName.Value;
            }
            if (shippingName.Value != "" && shippingStreet1.Value != "" && shippingCity.Value != ""
                && shippingState.Value != "" && shippingPostalCode.Value != "" && shippingCountry.Value != "")
            {
                AddressType shippingAddr = new AddressType();
                shippingAddr.Name = shippingName.Value;
                shippingAddr.Street1 = shippingStreet1.Value;
                shippingAddr.CityName = shippingCity.Value;
                shippingAddr.StateOrProvince = shippingCity.Value;
                shippingAddr.CountryName = shippingCountry.Value;
                shippingAddr.PostalCode = shippingPostalCode.Value;

                if (shippingStreet2.Value != "")
                {
                    shippingAddr.Street2 = shippingStreet2.Value;
                }
                if (shippingPhone.Value != "")
                {
                    shippingAddr.Phone = shippingPhone.Value;
                }
                profileDetails.SubscriberShippingAddress = shippingAddr;
            }
            if (additionalBillingCycles.Value != "")
            {
                profileDetails.AdditionalBillingCycles = Int32.Parse(additionalBillingCycles.Value);
            }
            if (amount.Value != "")
            {
                profileDetails.Amount = new BasicAmountType(currency, amount.Value);
            }
            if (outstandingBalance.Value != "")
            {
                profileDetails.OutstandingBalance =
                        new BasicAmountType(currency, outstandingBalance.Value);
            }
            if (maxFailedPayments.Value != "")
            {
                profileDetails.MaxFailedPayments = Int32.Parse(maxFailedPayments.Value);
            }
            if (autoBillOutstandingAmount.SelectedIndex != 0)
            {
                profileDetails.AutoBillOutstandingAmount = (AutoBillType)
                    Enum.Parse(typeof(AutoBillType), autoBillOutstandingAmount.SelectedValue);
            }
            if(billingStartDate.Text != ""){
                profileDetails.BillingStartDate = billingStartDate.Text;
            }
            if (creditCardNumber.Value != "" && cvv.Value != "")
            {
                CreditCardDetailsType cc = new CreditCardDetailsType();
                cc.CreditCardNumber = creditCardNumber.Value;
                cc.CVV2 = cvv.Value;
                cc.ExpMonth = Int32.Parse(expMonth.SelectedValue);
                cc.ExpYear = Int32.Parse(expYear.SelectedValue);
                profileDetails.CreditCard = cc;
            }

            // Populate trial payment details
            if (trialBillingAmount.Value != "" && trialBillingFrequency.Value != ""
                    && trialBillingCycles.Value != "")
            {
                BillingPeriodDetailsType_Update trialPeriod = new BillingPeriodDetailsType_Update();
                trialPeriod.BillingPeriod = (BillingPeriodType)
                    Enum.Parse(typeof(BillingPeriodType), trialBillingPeriod.SelectedValue);
                trialPeriod.BillingFrequency = Int32.Parse(trialBillingFrequency.Value);
                trialPeriod.Amount = new BasicAmountType(currency, trialBillingAmount.Value);

                trialPeriod.TotalBillingCycles = Int32.Parse(trialBillingCycles.Value);
                if (trialShippingAmount.Value != "")
                {
                    trialPeriod.ShippingAmount = new BasicAmountType(currency, trialShippingAmount.Value);
                }
                if (trialTaxAmount.Value != "")
                {
                    trialPeriod.TaxAmount = new BasicAmountType(currency, trialTaxAmount.Value);
                }
                profileDetails.TrialPeriod = trialPeriod;
            }
            // Populate regular payment details
            if (billingAmount.Value != "" && billingFrequency.Value != ""
                    && totalBillingCycles.Value != "")
            {
                BillingPeriodDetailsType_Update paymentPeriod = new BillingPeriodDetailsType_Update();
                paymentPeriod.BillingPeriod = (BillingPeriodType)
                    Enum.Parse(typeof(BillingPeriodType), billingPeriod.SelectedValue);
                paymentPeriod.BillingFrequency = Int32.Parse(billingFrequency.Value);
                paymentPeriod.Amount = new BasicAmountType(currency, billingAmount.Value);

                paymentPeriod.TotalBillingCycles = Int32.Parse(totalBillingCycles.Value);
                if (trialShippingAmount.Value != "")
                {
                    paymentPeriod.ShippingAmount = new BasicAmountType(currency, shippingAmount.Value);
                }
                if (trialTaxAmount.Value != "")
                {
                    paymentPeriod.TaxAmount = new BasicAmountType(currency, taxAmount.Value);
                }
                profileDetails.PaymentPeriod = paymentPeriod;
            }
        }
        private void populateRequest(CreateRecurringPaymentsProfileRequestType request)
        {
            CurrencyCodeType currency = (CurrencyCodeType)
                Enum.Parse(typeof(CurrencyCodeType), "USD");

            // Set EC-Token or Credit card requestDetails
            CreateRecurringPaymentsProfileRequestDetailsType profileDetails = new CreateRecurringPaymentsProfileRequestDetailsType();
            request.CreateRecurringPaymentsProfileRequestDetails = profileDetails;
            // A timestamped token, the value of which was returned in the response to the first call to SetExpressCheckout. You can also use the token returned in the SetCustomerBillingAgreement response. Either this token or a credit card number is required. If you include both token and credit card number, the token is used and credit card number is ignored Call CreateRecurringPaymentsProfile once for each billing agreement included in SetExpressCheckout request and use the same token for each call. Each CreateRecurringPaymentsProfile request creates a single recurring payments profile.
            // Note: Tokens expire after approximately 3 hours.
            if(token.Value != string.Empty)
            {
                profileDetails.Token = token.Value;
            }
            // Credit card information for recurring payments using direct payments. Either a token or a credit card number is required. If you include both token and credit card number, the token is used and credit card number is ignored.
            else if (creditCardNumber.Value != string.Empty && cvv.Value != string.Empty)
            {
                CreditCardDetailsType cc = new CreditCardDetailsType();
                // (Required) Credit card number.
                cc.CreditCardNumber = creditCardNumber.Value;
                // 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.
                cc.CVV2 = cvv.Value;
                // (Required) Credit card expiration month.
                cc.ExpMonth = Convert.ToInt32(expMonth.SelectedValue);
                // (Required) Credit card expiration year.
                cc.ExpYear = Convert.ToInt32(expYear.SelectedValue);
                profileDetails.CreditCard = cc;
            }

            // Populate Recurring Payments Profile Details
            RecurringPaymentsProfileDetailsType rpProfileDetails =
                new RecurringPaymentsProfileDetailsType(billingStartDate.Text);
            profileDetails.RecurringPaymentsProfileDetails = rpProfileDetails;
            // (Optional) Full name of the person receiving the product or service paid for by the recurring payment. If not present, the name in the buyer's PayPal account is used.
            if(subscriberName.Value != string.Empty)
            {
                rpProfileDetails.SubscriberName = subscriberName.Value;
            }

            // (Optional) The subscriber's shipping address associated with this profile, if applicable. If not specified, the ship-to address from buyer's PayPal account is used.
            if(shippingName.Value != string.Empty && shippingStreet1.Value != string.Empty && shippingCity.Value != string.Empty
                && shippingState.Value != string.Empty && shippingPostalCode.Value != string.Empty && shippingCountry.Value != string.Empty)
            {
                AddressType shippingAddr = new AddressType();
                // Person's name associated with this shipping address. It is required if using a shipping address.
                shippingAddr.Name = shippingName.Value;
                // First street address. It is required if using a shipping address.
                shippingAddr.Street1 = shippingStreet1.Value;
                // Name of city. It is required if using a shipping address.
                shippingAddr.CityName = shippingCity.Value;
                // State or province. It is required if using a shipping address.
                shippingAddr.StateOrProvince = shippingState.Value;
                // Country code. It is required if using a shipping address.
                shippingAddr.CountryName = shippingCountry.Value;
                // U.S. ZIP code or other country-specific postal code. It is required if using a U.S. shipping address; may be required for other countries.
                shippingAddr.PostalCode = shippingPostalCode.Value;

                // (Optional) Second street address.
                if(shippingStreet2.Value != string.Empty)
                {
                    shippingAddr.Street2 = shippingStreet2.Value;
                }
                // (Optional) Phone number.
                if(shippingPhone.Value != string.Empty)
                {
                    shippingAddr.Phone = shippingPhone.Value;
                }
                rpProfileDetails.SubscriberShippingAddress = shippingAddr;
            }

            // (Required) Describes the recurring payments schedule, including the regular payment period, whether there is a trial period, and the number of payments that can fail before a profile is suspended.
            ScheduleDetailsType scheduleDetails = new ScheduleDetailsType();
            // (Required) Description of the recurring payment.
            // Note: You must ensure that this field matches the corresponding billing agreement description included in the SetExpressCheckout request.
            if(profileDescription.Value != string.Empty)
            {
                scheduleDetails.Description = profileDescription.Value;
            }
            // (Optional) Number of scheduled payments that can fail before the profile is automatically suspended. An IPN message is sent to the merchant when the specified number of failed payments is reached.
            if(maxFailedPayments.Value != string.Empty)
            {
                scheduleDetails.MaxFailedPayments = Convert.ToInt32(maxFailedPayments.Value);
            }
            // (Optional) Indicates whether you would like PayPal to automatically bill the outstanding balance amount in the next billing cycle. The outstanding balance is the total amount of any previously failed scheduled payments that have yet to be successfully paid. It is one of the following values:
            // * NoAutoBill – PayPal does not automatically bill the outstanding balance.
            // * AddToNextBilling – PayPal automatically bills the outstanding balance.
            if(autoBillOutstandingAmount.SelectedIndex != 0)
            {
                scheduleDetails.AutoBillOutstandingAmount = (AutoBillType)
                    Enum.Parse(typeof(AutoBillType), autoBillOutstandingAmount.SelectedValue);
            }
            // (Optional) Information about activating a profile, such as whether there is an initial non-recurring payment amount immediately due upon profile creation and how to override a pending profile PayPal suspends when the initial payment amount fails.
            if(initialAmount.Value != string.Empty)
            {
                // (Optional) Initial non-recurring payment amount due immediately upon profile creation. Use an initial amount for enrolment or set-up fees.
                // Note: All amounts included in the request must have the same currency.
                ActivationDetailsType activationDetails =
                    new ActivationDetailsType(new BasicAmountType(currency, initialAmount.Value));
                // (Optional) Action you can specify when a payment fails. It is one of the following values:
                // * ContinueOnFailure – By default, PayPal suspends the pending profile in the event that the initial payment amount fails. You can override this default behavior by setting this field to ContinueOnFailure. Then, if the initial payment amount fails, PayPal adds the failed payment amount to the outstanding balance for this recurring payment profile.
                //   When you specify ContinueOnFailure, a success code is returned to you in the CreateRecurringPaymentsProfile response and the recurring payments profile is activated for scheduled billing immediately. You should check your IPN messages or PayPal account for updates of the payment status.
                // * CancelOnFailure – If this field is not set or you set it to CancelOnFailure, PayPal creates the recurring payment profile, but places it into a pending status until the initial payment completes. If the initial payment clears, PayPal notifies you by IPN that the pending profile has been activated. If the payment fails, PayPal notifies you by IPN that the pending profile has been canceled.
                if(failedInitialAmountAction.SelectedIndex != 0)
                {
                    activationDetails.FailedInitialAmountAction = (FailedPaymentActionType)
                        Enum.Parse(typeof(FailedPaymentActionType), failedInitialAmountAction.SelectedValue);
                }
                scheduleDetails.ActivationDetails = activationDetails;
            }
            // (Optional) Trial period for this schedule.
            if(trialBillingAmount.Value != string.Empty && trialBillingFrequency.Value != string.Empty
                    && trialBillingCycles.Value != string.Empty)
            {
                // Number of billing periods that make up one billing cycle;
                // required if you specify an optional trial period.
                // The combination of billing frequency and billing period must be
                // less than or equal to one year. For example, if the billing cycle is Month,
                // the maximum value for billing frequency is 12. Similarly,
                // if the billing cycle is Week, the maximum value for billing frequency is 52.
                // Note:
                // If the billing period is SemiMonth, the billing frequency must be 1.
                int frequency = Convert.ToInt32(trialBillingFrequency.Value);

                //Billing amount for each billing cycle during this payment period;
                //required if you specify an optional trial period.
                //This amount does not include shipping and tax amounts.
                //Note:
                //All amounts in the CreateRecurringPaymentsProfile request must have
                //the same currency.
                //Character length and limitations:
                //Value is a positive number which cannot exceed $10,000 USD in any currency.
                //It includes no currency symbol.
                //It must have 2 decimal places, the decimal separator must be a period (.),
                //and the optional thousands separator must be a comma (,).
                BasicAmountType paymentAmount = new BasicAmountType(currency, trialBillingAmount.Value);

                //Unit for billing during this subscription period;
                //required if you specify an optional trial period.
                //It is one of the following values: [Day, Week, SemiMonth, Month, Year]
                //For SemiMonth, billing is done on the 1st and 15th of each month.
                //Note:
                //The combination of BillingPeriod and BillingFrequency cannot exceed one year.
                BillingPeriodType period = (BillingPeriodType)
                    Enum.Parse(typeof(BillingPeriodType), trialBillingPeriod.SelectedValue);

                //Number of billing periods that make up one billing cycle;
                //required if you specify an optional trial period.
                //The combination of billing frequency and billing period must be
                //less than or equal to one year. For example, if the billing cycle is Month,
                //the maximum value for billing frequency is 12. Similarly,
                //if the billing cycle is Week, the maximum value for billing frequency is 52.
                //Note:
                //If the billing period is SemiMonth, the billing frequency must be 1.
                int numCycles = Convert.ToInt32(trialBillingCycles.Value);

                BillingPeriodDetailsType trialPeriod = new BillingPeriodDetailsType(period, frequency, paymentAmount);
                trialPeriod.TotalBillingCycles = numCycles;
                //(Optional) Shipping amount for each billing cycle during this payment period.
                //Note:
                //All amounts in the request must have the same currency.
                if(trialShippingAmount.Value != string.Empty)
                {
                    trialPeriod.ShippingAmount = new BasicAmountType(currency, trialShippingAmount.Value);
                }
                //(Optional) Tax amount for each billing cycle during this payment period.
                //Note:
                //All amounts in the request must have the same currency.
                //Character length and limitations:
                //Value is a positive number which cannot exceed $10,000 USD in any currency.
                //It includes no currency symbol. It must have 2 decimal places,
                //the decimal separator must be a period (.), and the optional
                //thousands separator must be a comma (,).
                if(trialTaxAmount.Value != string.Empty)
                {
                    trialPeriod.TaxAmount = new BasicAmountType(currency, trialTaxAmount.Value);
                }

                scheduleDetails.TrialPeriod = trialPeriod;
            }
            // (Required) Regular payment period for this schedule.
            if(billingAmount.Value != string.Empty && billingFrequency.Value != string.Empty
                    && totalBillingCycles.Value != string.Empty)
            {
                // Number of billing periods that make up one billing cycle;
                // required if you specify an optional trial period.
                // The combination of billing frequency and billing period must be
                // less than or equal to one year. For example, if the billing cycle is Month,
                // the maximum value for billing frequency is 12. Similarly,
                // if the billing cycle is Week, the maximum value for billing frequency is 52.
                // Note:
                // If the billing period is SemiMonth, the billing frequency must be 1.
                int frequency = Convert.ToInt32(billingFrequency.Value);
                //Billing amount for each billing cycle during this payment period;
                //required if you specify an optional trial period.
                //This amount does not include shipping and tax amounts.
                //Note:
                //All amounts in the CreateRecurringPaymentsProfile request must have
                //the same currency.
                //Character length and limitations:
                //Value is a positive number which cannot exceed $10,000 USD in any currency.
                //It includes no currency symbol.
                //It must have 2 decimal places, the decimal separator must be a period (.),
                //and the optional thousands separator must be a comma (,).
                BasicAmountType paymentAmount = new BasicAmountType(currency, billingAmount.Value);
                BillingPeriodType period = (BillingPeriodType)
                    Enum.Parse(typeof(BillingPeriodType), billingPeriod.SelectedValue);
                //Number of billing periods that make up one billing cycle;
                //required if you specify an optional trial period.
                //The combination of billing frequency and billing period must be
                //less than or equal to one year. For example, if the billing cycle is Month,
                //the maximum value for billing frequency is 12. Similarly,
                //if the billing cycle is Week, the maximum value for billing frequency is 52.
                //Note:
                //If the billing period is SemiMonth, the billing frequency must be 1.
                int numCycles = Convert.ToInt32(totalBillingCycles.Value);

                //Unit for billing during this subscription period;
                //required if you specify an optional trial period.
                //It is one of the following values: [Day, Week, SemiMonth, Month, Year]
                //For SemiMonth, billing is done on the 1st and 15th of each month.
                //Note:
                //The combination of BillingPeriod and BillingFrequency cannot exceed one year.
                BillingPeriodDetailsType paymentPeriod = new BillingPeriodDetailsType(period, frequency, paymentAmount);
                paymentPeriod.TotalBillingCycles = numCycles;
                //(Optional) Shipping amount for each billing cycle during this payment period.
                //Note:
                //All amounts in the request must have the same currency.
                if(trialShippingAmount.Value != string.Empty)
                {
                    paymentPeriod.ShippingAmount = new BasicAmountType(currency, shippingAmount.Value);
                }

                //(Optional) Tax amount for each billing cycle during this payment period.
                //Note:
                //All amounts in the request must have the same currency.
                //Character length and limitations:
                //Value is a positive number which cannot exceed $10,000 USD in any currency.
                //It includes no currency symbol. It must have 2 decimal places,
                //the decimal separator must be a period (.), and the optional
                //thousands separator must be a comma (,).
                if(trialTaxAmount.Value != string.Empty)
                {
                    paymentPeriod.TaxAmount = new BasicAmountType(currency, taxAmount.Value);
                }
                scheduleDetails.PaymentPeriod = paymentPeriod;
            }
            profileDetails.ScheduleDetails = scheduleDetails;
        }
Пример #12
0
		// # SetExpressCheckout API Operation
		// The SetExpressCheckout API operation initiates an Express Checkout transaction. 
		public SetExpressCheckoutResponseType SetExpressCheckoutAPIOperation()
		{
			// Create the SetExpressCheckoutResponseType object
			SetExpressCheckoutResponseType responseSetExpressCheckoutResponseType = new SetExpressCheckoutResponseType();

			try
			{
				// # SetExpressCheckoutReq
				SetExpressCheckoutRequestDetailsType setExpressCheckoutRequestDetails = new SetExpressCheckoutRequestDetailsType();

				// URL to which the buyer's browser is returned after choosing to pay
				// with PayPal. For digital goods, you must add JavaScript to this page
				// to close the in-context experience.
				// `Note:
				// PayPal recommends that the value be the final review page on which
				// the buyer confirms the order and payment or billing agreement.`
				setExpressCheckoutRequestDetails.ReturnURL = "http://localhost/return";

				// URL to which the buyer is returned if the buyer does not approve the
				// use of PayPal to pay you. For digital goods, you must add JavaScript
				// to this page to close the in-context experience.
				// `Note:
				// PayPal recommends that the value be the original page on which the
				// buyer chose to pay with PayPal or establish a billing agreement.`
				setExpressCheckoutRequestDetails.CancelURL = "http://localhost/cancel";

				// # Payment Information
				// list of information about the payment
				List<PaymentDetailsType> paymentDetailsList = new List<PaymentDetailsType>();

				// information about the first payment
				PaymentDetailsType paymentDetails1 = new PaymentDetailsType();

				// 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 orderTotal1 = new BasicAmountType(CurrencyCodeType.USD, "2.00");
				paymentDetails1.OrderTotal = orderTotal1;

				// How you want to obtain payment. When implementing parallel payments,
				// this field is required and must be set to `Order`. When implementing
				// digital goods, this field is required and must be set to `Sale`. If the
				// transaction does not include a one-time purchase, this field is
				// ignored. It is one of the following values:
				//
				// * `Sale` - This is a final sale for which you are requesting payment
				// (default).
				// * `Authorization` - This payment is a basic authorization subject to
				// settlement with PayPal Authorization and Capture.
				// * `Order` - This payment is an order authorization subject to
				// settlement with PayPal Authorization and Capture.
				// `Note:
				// You cannot set this field to Sale in SetExpressCheckout request and
				// then change the value to Authorization or Order in the
				// DoExpressCheckoutPayment request. If you set the field to
				// Authorization or Order in SetExpressCheckout, you may set the field
				// to Sale.`
				paymentDetails1.PaymentAction = PaymentActionCodeType.ORDER;

				// Unique identifier for the merchant. For parallel payments, this field
				// is required and must contain the Payer Id or the email address of the
				// merchant.
				SellerDetailsType sellerDetails1 = new SellerDetailsType();
				sellerDetails1.PayPalAccountID = "*****@*****.**";
				paymentDetails1.SellerDetails = sellerDetails1;

				// A unique identifier of the specific payment request, which is
				// required for parallel payments.
				paymentDetails1.PaymentRequestID = "PaymentRequest1";

				// `Address` to which the order is shipped, which takes mandatory params:
				//
				// * `Street Name`
				// * `City`
				// * `State`
				// * `Country`
				// * `Postal Code`
				AddressType shipToAddress1 = new AddressType();
				shipToAddress1.Street1 = "Ape Way";
				shipToAddress1.CityName = "Austin";
				shipToAddress1.StateOrProvince = "TX";
				shipToAddress1.Country = CountryCodeType.US;
				shipToAddress1.PostalCode = "78750";

				paymentDetails1.ShipToAddress = shipToAddress1;

				// 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        
				paymentDetails1.NotifyURL = "http://IPNhost";

				// information about the second payment
				PaymentDetailsType paymentDetails2 = new PaymentDetailsType();
				// 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 orderTotal2 = new BasicAmountType(CurrencyCodeType.USD, "4.00");
				paymentDetails2.OrderTotal = orderTotal2;

				// How you want to obtain payment. When implementing parallel payments,
				// this field is required and must be set to `Order`. When implementing
				// digital goods, this field is required and must be set to `Sale`. If the
				// transaction does not include a one-time purchase, this field is
				// ignored. It is one of the following values:
				//
				// * `Sale` - This is a final sale for which you are requesting payment
				// (default).
				// * `Authorization` - This payment is a basic authorization subject to
				// settlement with PayPal Authorization and Capture.
				// * `Order` - This payment is an order authorization subject to
				// settlement with PayPal Authorization and Capture.
				// `Note:
				// You cannot set this field to Sale in SetExpressCheckout request and
				// then change the value to Authorization or Order in the
				// DoExpressCheckoutPayment request. If you set the field to
				// Authorization or Order in SetExpressCheckout, you may set the field
				// to Sale.`
				paymentDetails2.PaymentAction = PaymentActionCodeType.ORDER;

				// Unique identifier for the merchant. For parallel payments, this field
				// is required and must contain the Payer Id or the email address of the
				// merchant.
				SellerDetailsType sellerDetails2 = new SellerDetailsType();
				sellerDetails2.PayPalAccountID = "*****@*****.**";
				paymentDetails2.SellerDetails = sellerDetails2;

				// A unique identifier of the specific payment request, which is
				// required for parallel payments.
				paymentDetails2.PaymentRequestID = "PaymentRequest2";

				// 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        
				paymentDetails2.NotifyURL = "http://IPNhost";

				// `Address` to which the order is shipped, which takes mandatory params:
				//
				// * `Street Name`
				// * `City`
				// * `State`
				// * `Country`
				// * `Postal Code`
				AddressType shipToAddress2 = new AddressType();
				shipToAddress2.Street1 = "Ape Way";
				shipToAddress2.CityName = "Austin";
				shipToAddress2.StateOrProvince = "TX";
				shipToAddress2.Country = CountryCodeType.US;
				shipToAddress2.PostalCode = "78750";
				paymentDetails2.ShipToAddress = shipToAddress2;

				paymentDetailsList.Add(paymentDetails1);
				paymentDetailsList.Add(paymentDetails2);

				setExpressCheckoutRequestDetails.PaymentDetails = paymentDetailsList;

				SetExpressCheckoutReq setExpressCheckout = new SetExpressCheckoutReq();
				SetExpressCheckoutRequestType setExpressCheckoutRequest = new SetExpressCheckoutRequestType(setExpressCheckoutRequestDetails);

				setExpressCheckout.SetExpressCheckoutRequest = setExpressCheckoutRequest;

				var config = new Dictionary<string, string>
					{
						{"mode", "sandbox"},
						{"account1.apiUsername", "konstantin_merchant_api1.scandiaconsulting.com"},
						{"account1.apiPassword", "1398157263"},
						{"account1.apiSignature", "AFcWxV21C7fd0v3bYYYRCpSSRl31AlRjlcug7qV.VXWV14E1KtmQPsPL"}
					};

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

				// # API call            
				// Invoke the SetExpressCheckout method in service wrapper object
				responseSetExpressCheckoutResponseType = service.SetExpressCheckout(setExpressCheckout);

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

					// # Success values
					if (responseSetExpressCheckoutResponseType.Ack.ToString().Trim().ToUpper().Equals("SUCCESS"))
					{
						// # Redirecting to PayPal for authorization
						// Once you get the "Success" response, needs to authorise the
						// transaction by making buyer to login into PayPal. For that,
						// need to construct redirect url using EC token from response.
						// For example,
						// `redirectURL="https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token="+setExpressCheckoutResponse.Token;`

						// Express Checkout Token
						Console.WriteLine("Express Checkout Token : " + responseSetExpressCheckoutResponseType.Token + "\n");
					}
					// # Error Values
					else
					{
						List<ErrorType> errorMessages = responseSetExpressCheckoutResponseType.Errors;
						foreach (ErrorType error in errorMessages)
						{
							Console.WriteLine("API Error Message : " + error.LongMessage + "\n");
						}
					}
				}

			}
			// # Exception log    
			catch (System.Exception ex)
			{
				// Log the exception message       
				Console.WriteLine("Error Message : " + ex.Message);
			}
			return responseSetExpressCheckoutResponseType;
		}
        private void populateRequestObject(UpdateRecurringPaymentsProfileRequestType request)
        {
            CurrencyCodeType currency = (CurrencyCodeType)
                Enum.Parse(typeof(CurrencyCodeType), "USD");
            // Set EC-Token or Credit card requestDetails
            UpdateRecurringPaymentsProfileRequestDetailsType profileDetails = new UpdateRecurringPaymentsProfileRequestDetailsType();
            request.UpdateRecurringPaymentsProfileRequestDetails = profileDetails;

            // (Required) Recurring payments profile ID returned in the CreateRecurringPaymentsProfile response.
            profileDetails.ProfileID = profileId.Value;
            // (Optional) The reason for the update to the recurring payments profile. This message is included in the email notification to the buyer for the recurring payments profile update. This note can also be seen by both you and the buyer on the Status History page of the PayPal account.
            if (note.Value != string.Empty)
            {
                profileDetails.Note = note.Value;
            }
            // Populate Recurring Payments Profile Details
            // (Optional) Full name of the person receiving the product or service paid for by the recurring payment. If not present, the name in the buyer's PayPal account is used.
            if (subscriberName.Value != string.Empty)
            {
                profileDetails.SubscriberName = subscriberName.Value;
            }
            // (Optional) The subscriber's shipping address associated with this profile, if applicable. If you do not specify it, the ship-to address from buyer's PayPal account is used.
            // Note: Shipping Address is optional, but if you update any of the address fields, you must enter all of them. For example, if you want to update the subscriber's street address, you must specify all of the fields listed in ShipTo: AddressType, not just the field for the street address.
            if (shippingName.Value != string.Empty && shippingStreet1.Value != string.Empty && shippingCity.Value != string.Empty
                && shippingState.Value != string.Empty && shippingPostalCode.Value != string.Empty && shippingCountry.Value != string.Empty)
            {
                AddressType shippingAddr = new AddressType();
                // Person's name associated with this shipping address. It is required if using a shipping address.
                shippingAddr.Name = shippingName.Value;
                // First street address. It is required if using a shipping address.
                shippingAddr.Street1 = shippingStreet1.Value;
                // Name of city. It is required if using a shipping address.
                shippingAddr.CityName = shippingCity.Value;
                // State or province. It is required if using a shipping address.
                shippingAddr.StateOrProvince = shippingState.Value;
                // Country code. It is required if using a shipping address.
                shippingAddr.CountryName = shippingCountry.Value;
                // U.S. ZIP code or other country-specific postal code. It is required if using a U.S. shipping address; may be required for other countries.
                shippingAddr.PostalCode = shippingPostalCode.Value;

                // (Optional) Second street address.
                if (shippingStreet2.Value != string.Empty)
                {
                    shippingAddr.Street2 = shippingStreet2.Value;
                }
                // (Optional) Phone number.
                if (shippingPhone.Value != string.Empty)
                {
                    shippingAddr.Phone = shippingPhone.Value;
                }
                profileDetails.SubscriberShippingAddress = shippingAddr;
            }
            // (Optional) The number of additional billing cycles to add to this profile.
            if (additionalBillingCycles.Value != string.Empty)
            {
                profileDetails.AdditionalBillingCycles = Convert.ToInt32(additionalBillingCycles.Value);
            }
            // (Optional) Billing amount for each cycle in the subscription period, not including shipping and tax amounts.
            // Note: For recurring payments with Express Checkout, the payment amount can be increased by no more than 20% every 180 days (starting when the profile is created).
            if (amount.Value != string.Empty)
            {
                profileDetails.Amount = new BasicAmountType(currency, amount.Value);
            }
            // (Optional) The current past due or outstanding amount for this profile. You can only decrease the outstanding amount. It cannot be increased.
            if (outstandingBalance.Value != string.Empty)
            {
                profileDetails.OutstandingBalance =
                        new BasicAmountType(currency, outstandingBalance.Value);
            }
            // (Optional) The number of failed payments allowed before the profile is automatically suspended. The specified value cannot be less than the current number of failed payments for this profile.
            if (maxFailedPayments.Value != string.Empty)
            {
                profileDetails.MaxFailedPayments = Convert.ToInt32(maxFailedPayments.Value);
            }
            // (Optional) This field indicates whether you would like PayPal to automatically bill the outstanding balance amount in the next billing cycle. It is one of the following values:
            // * NoAutoBill – PayPal does not automatically bill the outstanding balance.
            // * AddToNextBilling – PayPal automatically bills the outstanding balance
            if (autoBillOutstandingAmount.SelectedIndex != 0)
            {
                profileDetails.AutoBillOutstandingAmount = (AutoBillType)
                    Enum.Parse(typeof(AutoBillType), autoBillOutstandingAmount.SelectedValue);
            }
            // (Optional) The date when billing for this profile begins.
            // Note: The profile may take up to 24 hours for activation.
            if(billingStartDate.Text != string.Empty){
                profileDetails.BillingStartDate = billingStartDate.Text;
            }
            // (Optional) Credit card information for this profile, if applicable. Credit card billing address is optional, but if you update any of the address fields, you must enter all of them. For example, if you want to update the street address, you must specify all of the address fields listed in CreditCardDetailsType, not just the field for the street address.
            // Note: Only enter credit card details for recurring payments with direct payments.
            if (creditCardNumber.Value != string.Empty && cvv.Value != string.Empty)
            {
                CreditCardDetailsType cc = new CreditCardDetailsType();
                // (Required) Credit card number.
                cc.CreditCardNumber = creditCardNumber.Value;
                // 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.
                cc.CVV2 = cvv.Value;
                // (Required) Credit card expiration month.
                cc.ExpMonth = Convert.ToInt32(expMonth.SelectedValue);
                // (Required) Credit card expiration year.
                cc.ExpYear = Convert.ToInt32(expYear.SelectedValue);
                profileDetails.CreditCard = cc;
            }

            // (Optional) The trial period for this schedule.
            if (trialBillingAmount.Value != string.Empty && trialBillingFrequency.Value != string.Empty
                    && trialBillingCycles.Value != string.Empty)
            {
                BillingPeriodDetailsType_Update trialPeriod = new BillingPeriodDetailsType_Update();
                //Unit for billing during this subscription period;
                //required if you specify an optional trial period.
                //It is one of the following values: [Day, Week, SemiMonth, Month, Year]
                //For SemiMonth, billing is done on the 1st and 15th of each month.
                //Note:
                //The combination of BillingPeriod and BillingFrequency cannot exceed one year.
                trialPeriod.BillingPeriod = (BillingPeriodType)
                    Enum.Parse(typeof(BillingPeriodType), trialBillingPeriod.SelectedValue);
                // Number of billing periods that make up one billing cycle;
                // required if you specify an optional trial period.
                // The combination of billing frequency and billing period must be
                // less than or equal to one year. For example, if the billing cycle is Month,
                // the maximum value for billing frequency is 12. Similarly,
                // if the billing cycle is Week, the maximum value for billing frequency is 52.
                // Note:
                // If the billing period is SemiMonth, the billing frequency must be 1.
                trialPeriod.BillingFrequency = Convert.ToInt32(trialBillingFrequency.Value);
                //Billing amount for each billing cycle during this payment period;
                //required if you specify an optional trial period.
                //This amount does not include shipping and tax amounts.
                //Note:
                //All amounts in the CreateRecurringPaymentsProfile request must have
                //the same currency.
                //Character length and limitations:
                //Value is a positive number which cannot exceed $10,000 USD in any currency.
                //It includes no currency symbol.
                //It must have 2 decimal places, the decimal separator must be a period (.),
                //and the optional thousands separator must be a comma (,).
                trialPeriod.Amount = new BasicAmountType(currency, trialBillingAmount.Value);

                trialPeriod.TotalBillingCycles = Convert.ToInt32(trialBillingCycles.Value);
                //(Optional) Shipping amount for each billing cycle during this payment period.
                //Note:
                //All amounts in the request must have the same currency.
                if (trialShippingAmount.Value != string.Empty)
                {
                    trialPeriod.ShippingAmount = new BasicAmountType(currency, trialShippingAmount.Value);
                }
                //(Optional) Tax amount for each billing cycle during this payment period.
                //Note:
                //All amounts in the request must have the same currency.
                //Character length and limitations:
                //Value is a positive number which cannot exceed $10,000 USD in any currency.
                //It includes no currency symbol. It must have 2 decimal places,
                //the decimal separator must be a period (.), and the optional
                //thousands separator must be a comma (,).
                if (trialTaxAmount.Value != string.Empty)
                {
                    trialPeriod.TaxAmount = new BasicAmountType(currency, trialTaxAmount.Value);
                }
                profileDetails.TrialPeriod = trialPeriod;
            }
            // (Optional) The regular payment period for this schedule.
            if (billingAmount.Value != string.Empty && billingFrequency.Value != string.Empty
                    && totalBillingCycles.Value != string.Empty)
            {
                BillingPeriodDetailsType_Update paymentPeriod = new BillingPeriodDetailsType_Update();
                //Unit for billing during this subscription period;
                //required if you specify an optional trial period.
                //It is one of the following values: [Day, Week, SemiMonth, Month, Year]
                //For SemiMonth, billing is done on the 1st and 15th of each month.
                //Note:
                //The combination of BillingPeriod and BillingFrequency cannot exceed one year.
                paymentPeriod.BillingPeriod = (BillingPeriodType)
                    Enum.Parse(typeof(BillingPeriodType), billingPeriod.SelectedValue);
                // Number of billing periods that make up one billing cycle;
                // required if you specify an optional trial period.
                // The combination of billing frequency and billing period must be
                // less than or equal to one year. For example, if the billing cycle is Month,
                // the maximum value for billing frequency is 12. Similarly,
                // if the billing cycle is Week, the maximum value for billing frequency is 52.
                // Note:
                // If the billing period is SemiMonth, the billing frequency must be 1.
                paymentPeriod.BillingFrequency = Convert.ToInt32(billingFrequency.Value);
                //Billing amount for each billing cycle during this payment period;
                //required if you specify an optional trial period.
                //This amount does not include shipping and tax amounts.
                //Note:
                //All amounts in the CreateRecurringPaymentsProfile request must have
                //the same currency.
                //Character length and limitations:
                //Value is a positive number which cannot exceed $10,000 USD in any currency.
                //It includes no currency symbol.
                //It must have 2 decimal places, the decimal separator must be a period (.),
                //and the optional thousands separator must be a comma (,).
                paymentPeriod.Amount = new BasicAmountType(currency, billingAmount.Value);

                paymentPeriod.TotalBillingCycles = Convert.ToInt32(totalBillingCycles.Value);
                //(Optional) Shipping amount for each billing cycle during this payment period.
                //Note:
                //All amounts in the request must have the same currency.
                if (trialShippingAmount.Value != string.Empty)
                {
                    paymentPeriod.ShippingAmount = new BasicAmountType(currency, shippingAmount.Value);
                }
                //(Optional) Tax amount for each billing cycle during this payment period.
                //Note:
                //All amounts in the request must have the same currency.
                //Character length and limitations:
                //Value is a positive number which cannot exceed $10,000 USD in any currency.
                //It includes no currency symbol. It must have 2 decimal places,
                //the decimal separator must be a period (.), and the optional
                //thousands separator must be a comma (,).
                if (trialTaxAmount.Value != string.Empty)
                {
                    paymentPeriod.TaxAmount = new BasicAmountType(currency, taxAmount.Value);
                }
                profileDetails.PaymentPeriod = paymentPeriod;
            }
        }
Пример #14
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);
        }
        private void PopulatePaymentDetails(SetExpressCheckoutRequestDetailsType ecDetails)
        {
            var paymentInfo = new PaymentDetailsType();
            var total = 0.0;
            var currency = CurrencyCodeType.GBP;
            var address = new AddressType
            {
                Name = Checkout.BillingInfo.FirstName + " " + Checkout.BillingInfo.SurName,
                Street1 = Checkout.BillingInfo.FirmName + " " + Checkout.BillingInfo.BuildingName + " " + Checkout.BillingInfo.StreetName,
                CityName = Checkout.BillingInfo.City,
                StateOrProvince = Checkout.BillingInfo.County,
                PostalCode = Checkout.BillingInfo.PostCode
            };
            paymentInfo.ShipToAddress = address;

            foreach (var item in Cart)
            {
                var itemInformation = new PaymentDetailsItemType();
                itemInformation.Name = string.Format("{0}", item.Name);
                itemInformation.Quantity = item.Quantity;
                itemInformation.Amount = new BasicAmountType(currency, item.UnitPriceInStr);
                total += item.TotalPrice;
                paymentInfo.PaymentDetailsItem.Add(itemInformation);
            }

            var tax = total*20/100;
            paymentInfo.ItemTotal = new BasicAmountType(currency, total.ToString());
            paymentInfo.OrderTotal = new BasicAmountType(currency, (total + tax).ToString());
            paymentInfo.TaxTotal = new BasicAmountType(currency, (total * 20/100).ToString());
            ecDetails.PaymentDetails.Add(paymentInfo);
        }
Пример #16
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 });
                }
            }
        }