PaymentDetailsItemType Information about a Payment Item.
Esempio n. 1
0
        public string SetupPayment()
        {
            PaymentDetailsType paymentDetail = new PaymentDetailsType();
            CurrencyCodeType currency = (CurrencyCodeType)EnumUtils.GetValue("USD", typeof(CurrencyCodeType));
            PaymentDetailsItemType paymentItem = new PaymentDetailsItemType();
            paymentItem.Name = PaypalComment;
            paymentItem.Amount = new BasicAmountType(currency, this.TotalPrice);
            int itemQuantity = 1;
            paymentItem.Quantity = itemQuantity;
            List<PaymentDetailsItemType> paymentItems = new List<PaymentDetailsItemType>();
            paymentItems.Add(paymentItem);
            paymentDetail.PaymentDetailsItem = paymentItems;

            paymentDetail.PaymentAction = (PaymentActionCodeType)EnumUtils.GetValue("Sale", typeof(PaymentActionCodeType));
            paymentDetail.OrderTotal = new BasicAmountType((CurrencyCodeType)EnumUtils.GetValue("USD", typeof(CurrencyCodeType)), this.TotalPrice);
            List<PaymentDetailsType> paymentDetails = new List<PaymentDetailsType>();
            paymentDetails.Add(paymentDetail);

            SetExpressCheckoutRequestDetailsType ecDetails = new SetExpressCheckoutRequestDetailsType();
            ecDetails.ReturnURL = this.returnUrl;
            ecDetails.CancelURL = this.cancelUrl;
            ecDetails.PaymentDetails = paymentDetails;

            SetExpressCheckoutRequestType request = new SetExpressCheckoutRequestType();
            request.Version = "104.0";
            request.SetExpressCheckoutRequestDetails = ecDetails;

            SetExpressCheckoutReq wrapper = new SetExpressCheckoutReq();
            wrapper.SetExpressCheckoutRequest = request;
            Dictionary<string, string> sdkConfig = new Dictionary<string, string>();
            sdkConfig.Add("mode", appMode);
            sdkConfig.Add("account1.apiUsername", username);
            sdkConfig.Add("account1.apiPassword", password);
            sdkConfig.Add("account1.apiSignature", signature);
            PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(sdkConfig);
            SetExpressCheckoutResponseType setECResponse = service.SetExpressCheckout(wrapper);

            string url = paymentUrl + setECResponse.Token;

            return url;
        }
        private void populateRequestObject(DoReferenceTransactionRequestType request)
        {
            DoReferenceTransactionRequestDetailsType referenceTransactionDetails = new DoReferenceTransactionRequestDetailsType();
            request.DoReferenceTransactionRequestDetails = referenceTransactionDetails;
            // (Required) A transaction ID from a previous purchase, such as a credit card charge using the DoDirectPayment API, or a billing agreement ID.
            referenceTransactionDetails.ReferenceID = referenceId.Value;
            // (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.
            referenceTransactionDetails.PaymentAction = (PaymentActionCodeType)
                Enum.Parse(typeof(PaymentActionCodeType), paymentAction.SelectedValue);

            // Populate payment requestDetails.
            PaymentDetailsType paymentDetails = new PaymentDetailsType();
            referenceTransactionDetails.PaymentDetails = paymentDetails;
            // (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. 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.
            // Note: You must set the currencyID attribute to one of the 3-character currency codes for any of the supported PayPal currencies.
            double orderTotal = 0.0;
            // (Optional) Sum of cost of 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.
            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.
            if (shippingTotal.Value != string.Empty)
            {
                paymentDetails.ShippingTotal = new BasicAmountType(currency, shippingTotal.Value);
                orderTotal += Convert.ToDouble(shippingTotal.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.
            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.
            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.
            if (orderDescription.Value != string.Empty)
            {
                paymentDetails.OrderDescription = orderDescription.Value;
            }

            // Each payment can include requestDetails about multiple payment items
            // This example shows just one payment item
            if (itemName.Value != null && itemAmount.Value != null && itemQuantity.Value != null)
            {
                PaymentDetailsItemType itemDetails = new PaymentDetailsItemType();
                // Item name. This field is required when you pass a value for ItemCategory.
                itemDetails.Name = itemName.Value;
                // Cost of item. This field is required when you pass a value for ItemCategory.
                itemDetails.Amount = new BasicAmountType(currency, itemAmount.Value);
                // Item quantity. This field is required when you pass a value forItemCategory.
                itemDetails.Quantity = Convert.ToInt32(itemQuantity.Value);
                // Indicates whether the item is digital or physical. For digital goods, this field is required and you must set it to Digital to get the best rates. It is one of the following values:
                // * Digital
                // * Physical
                // This field is introduced in version 69.0.
                itemDetails.ItemCategory = (ItemCategoryType)
                    Enum.Parse(typeof(ItemCategoryType), itemCategory.SelectedValue);
                itemTotal += Convert.ToDouble(itemDetails.Amount.value) * itemDetails.Quantity.Value;
                //if (salesTax.Value != string.Empty)
                //{
                //    itemDetails.Tax = new BasicAmountType(currency, salesTax.Value);
                //    orderTotal += Convert.ToDouble(salesTax.Value);
                //}
                // (Optional) Item description.
                // This field is available since 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.
            paymentDetails.NotifyURL = ipnNotificationUrl.Value.Trim();
        }
Esempio n. 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;
        }
Esempio n. 4
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;
		}
        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;
        }
Esempio n. 6
0
        private void PopulateSetExpressCheckoutRequestObject(SetExpressCheckoutRequestType request, User user, Product product, string referrer,  int quantity, string billingAgreementText = "")
        {
            const string zero = "0.00";
            var orderTotal = 0.0;
            var itemTotal = 0.0;

            // Each payment can include requestDetails about multiple items
            // This example shows just one payment item
            if (quantity < 1) throw new Exception("Insufficient quantity");
            var itemDetails = new PaymentDetailsItemType {
                Name = product.Name,
                Amount = new BasicAmountType(MSKatushaCurrencyCode, product.Amount), 
                Quantity = quantity, 
                //ItemCategory = ItemCategoryType.PHYSICAL,
                Tax = new BasicAmountType(MSKatushaCurrencyCode, product.Tax), 
                Description = product.Description,
            };
            itemTotal += (Double.Parse(itemDetails.Amount.value) * quantity);

            orderTotal += Double.Parse(itemDetails.Tax.value);
            orderTotal += itemTotal;

            var paymentDetails = new PaymentDetailsType {
                ShippingTotal = new BasicAmountType(MSKatushaCurrencyCode, zero), 
                OrderDescription = MSKatushaorderDescription, 
                PaymentAction = PaymentActionCodeType.SALE,
                ItemTotal = new BasicAmountType(MSKatushaCurrencyCode, itemTotal.ToString(CultureInfo.InvariantCulture)),
                Custom = product.FriendlyName + "|" +(referrer ?? ""),
            };
            orderTotal += Double.Parse(paymentDetails.ShippingTotal.value);
            paymentDetails.OrderTotal = new BasicAmountType(MSKatushaCurrencyCode, orderTotal.ToString(CultureInfo.InvariantCulture));
            paymentDetails.PaymentDetailsItem.Add(itemDetails);


            var ecDetails = new SetExpressCheckoutRequestDetailsType {
                ReturnURL = _settings.ReturnUrl, 
                CancelURL = _settings.CancelUrl, 
                BuyerEmail = user.Email, 
                AddressOverride = "0", 
                NoShipping = "1", 
                SolutionType = SolutionTypeType.SOLE, 
                BuyerDetails = new BuyerDetailsType {BuyerId = user.Guid.ToString(), BuyerRegistrationDate = user.CreationDate.ToString("s"), BuyerUserName = user.UserName},
                cppHeaderImage = MSKatushaImageUrl,
                BrandName = MSKatushaBrandName
                //PageStyle = pageStyle.Value,
                //cppHeaderBorderColor = cppheaderbordercolor.Value,
                //cppHeaderBackColor = cppheaderbackcolor.Value,
                //cppPayflowColor = cpppayflowcolor.Value,
            };
            ecDetails.PaymentDetails.Add(paymentDetails);

            if (!String.IsNullOrWhiteSpace(billingAgreementText)) {
                var baType = new BillingAgreementDetailsType(BillingCodeType.MERCHANTINITIATEDBILLINGSINGLEAGREEMENT) { BillingAgreementDescription = billingAgreementText };
                ecDetails.BillingAgreementDetails.Add(baType);
            }
            request.SetExpressCheckoutRequestDetails = ecDetails;

            /*
                        //if (insuranceTotal.Value != "" && !double.Parse(insuranceTotal.Value).Equals(0.0)) {
                        //    paymentDetails.InsuranceTotal = new BasicAmountType(MSKatushaCurrencyCode, zero);
                        //    paymentDetails.InsuranceOptionOffered = "true";
                        //    orderTotal += Double.Parse(insuranceTotal.Value);
                        //}
                        //if (handlingTotal.Value != "") {
                        //    paymentDetails.HandlingTotal = new BasicAmountType(MSKatushaCurrencyCode, handlingTotal.Value);
                        //    orderTotal += Double.Parse(handlingTotal.Value);
                        //}
                        //if (taxTotal.Value != "") {
                        //    paymentDetails.TaxTotal = new BasicAmountType(MSKatushaCurrencyCode, taxTotal.Value);
                        //    orderTotal += Double.Parse(taxTotal.Value);
                        //}
                        //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;
                        //    ecDetails.PaymentDetails[0].ShipToAddress = shipAddress;
                        //}
             * */
        }
Esempio n. 7
0
		private PaymentDetailsType GetPaymentDetails(IInvoice invoice)
		{
			decimal itemTotal = 0;
			decimal taxTotal = 0;
			decimal shippingTotal = 0;
			var paymentDetailItems = new List<PaymentDetailsItemType>();
			foreach (var item in invoice.Items)
			{
				switch (item.LineItemType)
				{
					case LineItemType.Tax:
						taxTotal = item.TotalPrice;
						break;
					case LineItemType.Shipping:
						shippingTotal = item.TotalPrice;
						break;
					case LineItemType.Product:
						var paymentItem = new PaymentDetailsItemType
						{
							Name = item.Name,
							ItemURL = GetWebsiteUrl() + "/all-products/" + item.Sku,
							Amount = new BasicAmountType(CurrencyCodeType.USD, item.Price.ToString("0.00")),
							Quantity = item.Quantity,
						};
						paymentDetailItems.Add(paymentItem);
						itemTotal += item.TotalPrice;
						break;
					default:
						throw new Exception("Unsupported item with type: " + item.LineItemType);
				}
			}

			var paymentDetails = new PaymentDetailsType
			{
				PaymentDetailsItem = paymentDetailItems,
				ItemTotal = new BasicAmountType(CurrencyCodeType.USD, itemTotal.ToString("0.00")),
				TaxTotal = new BasicAmountType(CurrencyCodeType.USD, taxTotal.ToString("0.00")),
				ShippingTotal = new BasicAmountType(CurrencyCodeType.USD, shippingTotal.ToString("0.00")),
				OrderTotal = new BasicAmountType(CurrencyCodeType.USD, (itemTotal + taxTotal + shippingTotal).ToString("0.00")),
				PaymentAction = PaymentActionCodeType.ORDER,
				SellerDetails = new SellerDetailsType { PayPalAccountID = _settings.AccountId },
				PaymentRequestID = "PaymentRequest",
				//ShipToAddress = shipToAddress,
				NotifyURL = "http://IPNhost"
			};

			return paymentDetails;
		}
        private void populateRequestObject(DoReferenceTransactionRequestType request)
        {
            DoReferenceTransactionRequestDetailsType referenceTransactionDetails = new DoReferenceTransactionRequestDetailsType();
            request.DoReferenceTransactionRequestDetails = referenceTransactionDetails;
            referenceTransactionDetails.ReferenceID = referenceId.Value;
            referenceTransactionDetails.PaymentAction = (PaymentActionCodeType)
                Enum.Parse(typeof(PaymentActionCodeType), paymentAction.SelectedValue);

            // Populate payment requestDetails.
            PaymentDetailsType paymentDetails = new PaymentDetailsType();
            referenceTransactionDetails.PaymentDetails = 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 != "")
            {
                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);

            // Each payment can include requestDetails about multiple payment 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());
        }
        /// <summary>
        /// Handles Set Express Checkout For Recurring Payments
        /// </summary>
        /// <param name="contextHttp"></param>
        private void SetExpressCheckoutForRecurringPayments(HttpContext contextHttp)
        {
            NameValueCollection parameters = contextHttp.Request.Params;

            // 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);

            SetExpressCheckoutRequestType setExpressCheckoutReq = new SetExpressCheckoutRequestType();
            SetExpressCheckoutRequestDetailsType details = new SetExpressCheckoutRequestDetailsType();

            string requestUrl = ConfigurationManager.AppSettings["HOSTING_ENDPOINT"].ToString();

            // (Required) 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.
            UriBuilder uriBuilder = new UriBuilder(requestUrl);
            uriBuilder.Path = contextHttp.Request.ApplicationPath
                + (contextHttp.Request.ApplicationPath.EndsWith("/") ? string.Empty : "/")
                + "UseCaseSamples/SetExpressCheckoutForRecurringPayments.aspx";
            string returnUrl = uriBuilder.Uri.ToString();

            // (Required) 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.
            uriBuilder = new UriBuilder(requestUrl);
            uriBuilder.Path = contextHttp.Request.ApplicationPath
                + (contextHttp.Request.ApplicationPath.EndsWith("/") ? string.Empty : "/")
                + "UseCaseSamples/SetExpressCheckoutForRecurringPayments.aspx";
            string cancelUrl = uriBuilder.Uri.ToString();

            // (Required) 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.
            // Character length and limitations: 2048 single-byte characters
            details.ReturnURL = returnUrl + "?currencyCodeType=" + parameters["currencyCode"];
            details.CancelURL = cancelUrl;

            // (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.
            // Character length and limitations: 127 single-byte alphanumeric characters
            details.BuyerEmail = parameters["buyerMail"];

            decimal itemTotal = 0.0M;
            decimal orderTotal = 0.0M;

            // Cost of item. This field is required when you pass a value for ItemCategory.
            string amountItems = parameters["itemAmount"];

            // Item quantity. This field is required when you pass a value for ItemCategory.
            // For digital goods (ItemCategory=Digital), this field is required.
            // Character length and limitations: Any positive integer
            string qtyItems = parameters["itemQuantity"];

            // Item name. This field is required when you pass a value for ItemCategory.
            // Character length and limitations: 127 single-byte characters
            string names = parameters["itemName"];

            List<PaymentDetailsItemType> lineItems = new List<PaymentDetailsItemType>();
            PaymentDetailsItemType item = new PaymentDetailsItemType();
            BasicAmountType amt = new BasicAmountType();

            // PayPal uses 3-character ISO-4217 codes for specifying currencies in fields and variables.
            amt.currencyID = (CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), parameters["currencyCode"]);
            amt.value = amountItems;
            item.Quantity = Convert.ToInt32(qtyItems);
            item.Name = names;
            item.Amount = amt;

            // 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
            item.ItemCategory = (ItemCategoryType)Enum.Parse(typeof(ItemCategoryType), parameters["itemCategory"]);

            // (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 (parameters["salesTax"] != string.Empty)
            {
                item.Tax = new BasicAmountType((CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), parameters["currencyCode"]), parameters["salesTax"]);
            }

            itemTotal += Convert.ToDecimal(qtyItems) * Convert.ToDecimal(amountItems);
            orderTotal += itemTotal;

            List<PaymentDetailsType> payDetails = new List<PaymentDetailsType>();
            PaymentDetailsType paydtl = new PaymentDetailsType();

            // 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.
            paydtl.PaymentAction = (PaymentActionCodeType)Enum.Parse(typeof(PaymentActionCodeType), parameters["paymentType"]);

            // (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 (parameters["shippingTotal"] != string.Empty)
            {
                BasicAmountType shippingTotal = new BasicAmountType();
                shippingTotal.value = parameters["shippingTotal"];
                shippingTotal.currencyID = (CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), parameters["currencyCode"]);
                orderTotal += Convert.ToDecimal(parameters["shippingTotal"]);
                paydtl.ShippingTotal = shippingTotal;
            }

            // (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 (parameters["insuranceTotal"] != string.Empty)
            {
                paydtl.InsuranceTotal = new BasicAmountType((CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), parameters["currencyCode"]), parameters["insuranceTotal"]);
                paydtl.InsuranceOptionOffered = "true";
                orderTotal += Convert.ToDecimal(parameters["insuranceTotal"]);
            }

            // (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 (parameters["handlingTotal"] != string.Empty)
            {
                paydtl.HandlingTotal = new BasicAmountType((CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), parameters["currencyCode"]), parameters["handlingTotal"]);
                orderTotal += Convert.ToDecimal(parameters["handlingTotal"]);
            }

            // (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 (parameters["taxTotal"] != string.Empty)
            {
                paydtl.TaxTotal = new BasicAmountType((CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), parameters["currencyCode"]), parameters["taxTotal"]);
                orderTotal += Convert.ToDecimal(parameters["taxTotal"]);
            }

            // (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 (parameters["orderDescription"] != string.Empty)
            {
                paydtl.OrderDescription = parameters["orderDescription"];
            }

            BasicAmountType itemsTotal = new BasicAmountType();
            itemsTotal.value = Convert.ToString(itemTotal);

            // PayPal uses 3-character ISO-4217 codes for specifying currencies in fields and variables.
            itemsTotal.currencyID = (CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), parameters["currencyCode"]);

            paydtl.OrderTotal = new BasicAmountType((CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), parameters["currencyCode"]), Convert.ToString(orderTotal));
            paydtl.PaymentDetailsItem = lineItems;

            paydtl.ItemTotal = itemsTotal;

            // (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
            paydtl.NotifyURL = parameters["notifyURL"];

            payDetails.Add(paydtl);
            details.PaymentDetails = payDetails;

            if (parameters["billingAgreementText"] != 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.
                BillingAgreementDetailsType billingAgreement = new BillingAgreementDetailsType((BillingCodeType)Enum.Parse(typeof(BillingCodeType), parameters["billingType"]));

                // Description of goods or services associated with the billing agreement.
                // This field is required for each recurring payment billing agreement.
                // PayPal recommends that the description contain a brief summary of
                // the billing agreement terms and conditions. For example,
                // buyer is billed at "9.99 per month for 2 years".
                // Character length and limitations: 127 single-byte alphanumeric characters
                billingAgreement.BillingAgreementDescription = parameters["billingAgreementText"];
                List<BillingAgreementDetailsType> billList = new List<BillingAgreementDetailsType>();
                billList.Add(billingAgreement);
                details.BillingAgreementDetails = billList;
            }

            setExpressCheckoutReq.SetExpressCheckoutRequestDetails = details;
            SetExpressCheckoutReq expressCheckoutReq = new SetExpressCheckoutReq();
            expressCheckoutReq.SetExpressCheckoutRequest = setExpressCheckoutReq;

            SetExpressCheckoutResponseType response = null;
            try
            {
                response = service.SetExpressCheckout(expressCheckoutReq);
            }
            catch (System.Exception ex)
            {
                contextHttp.Response.Write(ex.Message);
                return;
            }

            Dictionary<string, string> responseValues = new Dictionary<string, string>();
            string redirectUrl = null;

            if (!response.Ack.ToString().Trim().ToUpper().Equals(AckCode.FAILURE.ToString()) && !response.Ack.ToString().Trim().ToUpper().Equals(AckCode.FAILUREWITHWARNING.ToString()))
            {
                redirectUrl = ConfigurationManager.AppSettings["PAYPAL_REDIRECT_URL"].ToString() + "_express-checkout&token=" + response.Token;
            }

            responseValues.Add("Acknowledgement", response.Ack.ToString().Trim().ToUpper());

            Display(contextHttp, "SetExpressCheckoutForRecurringPayments", "SetExpressCheckout", responseValues, service.getLastRequest(), service.getLastResponse(), response.Errors, redirectUrl);
        }
        /// <summary>
        /// Handles DoExpressCheckout
        /// </summary>
        /// <param name="contextHttp"></param>
        private void DoExpressCheckout(HttpContext contextHttp)
        {
            NameValueCollection parameters = contextHttp.Request.Params;

            // 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();

            // Creating service wrapper object to make an API call by loading configuration map.
            PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(configurationMap);

            DoExpressCheckoutPaymentRequestType doCheckoutPaymentRequestType = new DoExpressCheckoutPaymentRequestType();
            DoExpressCheckoutPaymentRequestDetailsType details = new DoExpressCheckoutPaymentRequestDetailsType();

            // A timestamped token by which you identify to PayPal that you are processing
            // this payment with Express Checkout. The token expires after three hours.
            // If you set the token in the SetExpressCheckout request, the value of the token
            // in the response is identical to the value in the request.
            // Character length and limitations: 20 single-byte characters
            details.Token = parameters["token"];

            // Unique PayPal Customer Account identification number.
            // Character length and limitations: 13 single-byte alphanumeric characters
            details.PayerID = parameters["payerID"];

            // (Optional) How you want to obtain payment. 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
            // this 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.
            // Character length and limitations: Up to 13 single-byte alphabetic characters
            // This field is deprecated. Use PaymentAction in PaymentDetailsType instead.
            details.PaymentAction = (PaymentActionCodeType)Enum.Parse(typeof(PaymentActionCodeType), parameters["paymentType"]);

            decimal itemTotalAmt = 0.0M;
            decimal orderTotalAmt = 0.0M;
            String amt = parameters["amt"];
            String quantity = parameters["itemQuantity"];
            itemTotalAmt = Convert.ToDecimal(amt) * Convert.ToDecimal(quantity);
            orderTotalAmt += itemTotalAmt;

            PaymentDetailsType paymentDetails = new PaymentDetailsType();
            BasicAmountType orderTotal = new BasicAmountType();
            orderTotal.value = Convert.ToString(orderTotalAmt);

            //PayPal uses 3-character ISO-4217 codes for specifying currencies in fields and variables.
            orderTotal.currencyID = (CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), parameters["currencyCode"]);

            // (Required) The total cost of the transaction to the buyer.
            // If shipping cost (not applicable to digital goods) 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.
            // For digital goods, the following must be true:
            // total cost > 0
            // total cost <= total cost passed in the call to SetExpressCheckout
            // Note:
            // You must set the currencyID attribute to one of the 3-character currency codes
            // for any of the supported PayPal currencies.
            // When multiple payments are passed in one transaction, all of the payments must
            // have the same currency code.
            // 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 (,).
            paymentDetails.OrderTotal = orderTotal;

            BasicAmountType itemTotal = new BasicAmountType();
            itemTotal.value = Convert.ToString(itemTotalAmt);

            //PayPal uses 3-character ISO-4217 codes for specifying currencies in fields and variables.
            itemTotal.currencyID = (CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), parameters["currencyCode"]);

            // Sum of cost of all items in this order. For digital goods, this field is
            // required. PayPal recommends that you pass the same value in the call to
            // DoExpressCheckoutPayment that you passed in the call to SetExpressCheckout.
            // 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 (,).
            // paymentDetails.ItemTotal = itemTotal;
            List<PaymentDetailsItemType> paymentItems = new List<PaymentDetailsItemType>();
            PaymentDetailsItemType paymentItem = new PaymentDetailsItemType();

            // Item name. This field is required when you pass a value for ItemCategory.
            // Character length and limitations: 127 single-byte characters
            // This field is introduced in version 53.0.
            paymentItem.Name = parameters["itemName"];

            // Item quantity. This field is required when you pass a value for ItemCategory.
            // For digital goods (ItemCategory=Digital), this field is required.
            // Character length and limitations: Any positive integer
            // This field is introduced in version 53.0.
            paymentItem.Quantity = Convert.ToInt32(parameters["itemQuantity"]);
            BasicAmountType amount = new BasicAmountType();

            // Cost of item. This field is required when you pass a value for ItemCategory.
            // 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 (,).
            // This field is introduced in version 53.0.
            amount.value = parameters["amt"];

            // PayPal uses 3-character ISO-4217 codes for specifying currencies in fields and variables.
            amount.currencyID = (CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), parameters["currencyCode"]);
            paymentItem.Amount = amount;
            paymentItems.Add(paymentItem);
            paymentDetails.PaymentDetailsItem = paymentItems;

            // (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 = parameters["notifyURL"];

            List<PaymentDetailsType> payDetailType = new List<PaymentDetailsType>();
            payDetailType.Add(paymentDetails);

            // When implementing parallel payments, you can create up to 10 sets of payment
            // details type parameter fields, each representing one payment you are hosting
            // on your marketplace.
            details.PaymentDetails = payDetailType;

            doCheckoutPaymentRequestType.DoExpressCheckoutPaymentRequestDetails = details;
            DoExpressCheckoutPaymentReq doExpressCheckoutPaymentReq = new DoExpressCheckoutPaymentReq();
            doExpressCheckoutPaymentReq.DoExpressCheckoutPaymentRequest = doCheckoutPaymentRequestType;
            DoExpressCheckoutPaymentResponseType response = null;
            try
            {
                response = service.DoExpressCheckoutPayment(doExpressCheckoutPaymentReq);
            }
            catch (System.Exception ex)
            {
                contextHttp.Response.Write(ex.StackTrace);
                return;
            }

            Dictionary<string, string> responseValues = new Dictionary<string, string>();
            string redirectUrl = null;

            if (!response.Ack.ToString().Trim().ToUpper().Equals(AckCode.FAILURE.ToString()) && !response.Ack.ToString().Trim().ToUpper().Equals(AckCode.FAILUREWITHWARNING.ToString()))
            {
                responseValues.Add("Acknowledgement", response.Ack.ToString().Trim().ToUpper());
                responseValues.Add("PaymentType", parameters["paymentType"]);
                responseValues.Add("TransactionId", response.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].TransactionID);
            }
            else
            {
                responseValues.Add("Acknowledgement", response.Ack.ToString().Trim().ToUpper());
            }

            Display(contextHttp, "DoExpressCheckout", "DoExpressCheckout", responseValues, service.getLastRequest(), service.getLastResponse(), response.Errors, redirectUrl);
        }
        private ActionResult Processing_PayPal(int claim, PaymentMode payment)
        {
            if (payment == null)
            {
                throw new System.ArgumentNullException("payment");
            }
            PaymentBeforeProcessingResult beforePaymentResult = BookingProvider.BeforePaymentProcessing(UrlLanguage.CurrentLanguage, payment.paymentparam);
            if (beforePaymentResult == null)
            {
                throw new System.Exception("cannot get payment details");
            }
            if (!beforePaymentResult.success)
            {
                throw new System.Exception("payment details fail");
            }
            System.Collections.Generic.List<PaymentDetailsType> paymentDetails = new System.Collections.Generic.List<PaymentDetailsType>();
            PaymentDetailsType paymentDetail = new PaymentDetailsType();
            paymentDetail.AllowedPaymentMethod = new AllowedPaymentMethodType?(AllowedPaymentMethodType.ANYFUNDINGSOURCE);
            CurrencyCodeType currency = (CurrencyCodeType)EnumUtils.GetValue(payment.payrest.currency, typeof(CurrencyCodeType));
            PaymentDetailsItemType paymentItem = new PaymentDetailsItemType();
            paymentItem.Name = string.Format(PaymentStrings.ResourceManager.Get("PaymentForOrderFormat"), claim);
            paymentItem.Amount = new BasicAmountType(new CurrencyCodeType?(currency), payment.payrest.total.ToString("#.00", System.Globalization.NumberFormatInfo.InvariantInfo));
            paymentItem.Quantity = new int?(1);
            paymentItem.ItemCategory = new ItemCategoryType?(ItemCategoryType.PHYSICAL);
            paymentItem.Description = string.Format("Booking #{0}", claim);
            paymentDetail.PaymentDetailsItem = new System.Collections.Generic.List<PaymentDetailsItemType>
            {
                paymentItem
            };
            paymentDetail.PaymentAction = new PaymentActionCodeType?(PaymentActionCodeType.SALE);
            paymentDetail.OrderTotal = new BasicAmountType(paymentItem.Amount.currencyID, paymentItem.Amount.value);
            paymentDetails.Add(paymentDetail);
            SetExpressCheckoutRequestDetailsType ecDetails = new SetExpressCheckoutRequestDetailsType();
            ecDetails.ReturnURL = new Uri(base.Request.BaseServerAddress(), base.Url.Action("processingresult", new
            {
                id = "paypal",
                success = true
            })).ToString();
            ecDetails.CancelURL = new Uri(base.Request.BaseServerAddress(), base.Url.Action("processingresult", new
            {
                id = "paypal",
                success = false
            })).ToString();
            ecDetails.NoShipping = "1";
            ecDetails.AllowNote = "0";
            ecDetails.SolutionType = new SolutionTypeType?(SolutionTypeType.SOLE);
            ecDetails.SurveyEnable = "0";
            ecDetails.PaymentDetails = paymentDetails;
            ecDetails.InvoiceID = beforePaymentResult.invoiceNumber;
            SetExpressCheckoutRequestType request = new SetExpressCheckoutRequestType();
            request.Version = "104.0";
            request.SetExpressCheckoutRequestDetails = ecDetails;
            SetExpressCheckoutReq wrapper = new SetExpressCheckoutReq();
            wrapper.SetExpressCheckoutRequest = request;
            System.Collections.Generic.Dictionary<string, string> config = PaymentController.PayPal_CreateConfig();
            PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(config);
            SetExpressCheckoutResponseType setECResponse = service.SetExpressCheckout(wrapper);
            System.Collections.Generic.KeyValuePair<string, string> sandboxConfig = config.FirstOrDefault((System.Collections.Generic.KeyValuePair<string, string> m) => m.Key == "mode");
            string sandboxServer = (sandboxConfig.Key != null && sandboxConfig.Value == "sandbox") ? ".sandbox" : "";

            return base.View("PaymentSystems\\PayPal", new ProcessingContext
            {
                Reservation = BookingProvider.GetReservationState(UrlLanguage.CurrentLanguage, claim),
                PaymentMode = payment,
                BeforePaymentResult = beforePaymentResult,
                RedirectUrl = string.Format("https://www{0}.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token={1}", sandboxServer, base.Server.UrlEncode(setECResponse.Token))
            });

              //  return new RedirectResult(string.Format("https://www{0}.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token={1}", sandboxServer, base.Server.UrlEncode(setECResponse.Token)));
        }
        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);
        }