コード例 #1
0
		/// <summary>
		/// Processes the Authorize and AuthorizeAndCapture transactions
		/// </summary>
		/// <param name="invoice">The <see cref="IInvoice"/> to be paid</param>
		/// <param name="payment">The <see cref="IPayment"/> record</param>
		/// <param name="args"></param>
		/// <returns>The <see cref="IPaymentResult"/></returns>
		public IPaymentResult ProcessPayment(IInvoice invoice, IPayment payment, ProcessorArgumentCollection args)
		{
			var setExpressCheckoutRequestDetails = new SetExpressCheckoutRequestDetailsType
			{
				ReturnURL = String.Format("{0}/App_Plugins/Merchello.PayPal/PayPalExpressCheckout.html?InvoiceKey={1}&PaymentKey={2}&PaymentMethodKey={3}", GetWebsiteUrl(), invoice.Key, payment.Key, payment.PaymentMethodKey),
				CancelURL = "http://localhost/cancel",
				PaymentDetails = new List<PaymentDetailsType> { GetPaymentDetails(invoice) }
			};


			var setExpressCheckout = new SetExpressCheckoutReq();
			var setExpressCheckoutRequest = new SetExpressCheckoutRequestType(setExpressCheckoutRequestDetails);
			setExpressCheckout.SetExpressCheckoutRequest = setExpressCheckoutRequest;
			var config = new Dictionary<string, string>
					{
						{"mode", "sandbox"},
						{"account1.apiUsername", _settings.ApiUsername},
						{"account1.apiPassword", _settings.ApiPassword},
						{"account1.apiSignature", _settings.ApiSignature}
					};
			var service = new PayPalAPIInterfaceServiceService(config);
			var responseSetExpressCheckoutResponseType = service.SetExpressCheckout(setExpressCheckout);

			// If this were using a service we might want to store some of the transaction data in the ExtendedData for record
			payment.ExtendedData.SetValue("RedirectUrl", "https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=" + responseSetExpressCheckoutResponseType.Token);

			return new PaymentResult(Attempt<IPayment>.Succeed(payment), invoice, false);
		}
コード例 #2
0
        public ActionResult AuthorizeAgreement()
        {
            var service = new PayPalAPIInterfaceServiceService();

            var request = new SetExpressCheckoutReq()
            {
                SetExpressCheckoutRequest = new SetExpressCheckoutRequestType
                {
                    SetExpressCheckoutRequestDetails = new SetExpressCheckoutRequestDetailsType()
                    {
                        BillingAgreementDetails = new List<BillingAgreementDetailsType>()
                        {
                            new BillingAgreementDetailsType(BillingCodeType.MERCHANTINITIATEDBILLINGSINGLEAGREEMENT)
                            {
                                BillingAgreementDescription = "All your money are belong to us.",
                            }
                        },
                        ReturnURL = Utilities.ToAbsoluteUrl(HttpContext, Url.Action("AgreementConfirmed")),
                        CancelURL = Utilities.ToAbsoluteUrl(HttpContext, Url.Action("AgreementCanceled")),
                        BuyerEmail = "*****@*****.**",
                        BrandName = "Super Legitimate Website"
                    }
                }
            };

            var response = service.SetExpressCheckout(request);

            var url = String.Format("https://www.sandbox.paypal.com/webscr&cmd=_express-checkout&token={0}", response.Token);

            return Redirect(url);
        }
コード例 #3
0
 public string SetExpressCheckout(User user, Product product, string referrer = "", int quantity = 1, string billingAgreementText = "")
 {
     var request = new SetExpressCheckoutRequestType();
     PopulateSetExpressCheckoutRequestObject(request, user, product, referrer, quantity, billingAgreementText);
     var wrapper = new SetExpressCheckoutReq {SetExpressCheckoutRequest = request};
     var setEcResponse = _payPalApiService.SetExpressCheckout(wrapper, GetApiUserName());
     return setEcResponse.Token;
 }
コード例 #4
0
 public void SetQuickCheckOut()
 {
     var request = new SetExpressCheckoutRequestType();
     PopulateSetCheckoutRequestObject(request);
     var wrapper = new SetExpressCheckoutReq();
     wrapper.SetExpressCheckoutRequest = request;
     var service = new PayPalAPIInterfaceServiceService();
     var response = service.SetExpressCheckout(wrapper);
     if (response.Ack.Equals(AckCodeType.FAILURE) || (response.Errors != null && response.Errors.Count > 0))
     {
         throw new InvalidOperationException(string.Join("\n", response.Errors.Select(x=>x.LongMessage)));
     }
     var paypalRedirectUrl = string.Format(ConfigurationManager.AppSettings["PayPalRedirectUrl"] + "_express-checkout&token={0}", response.Token);
     WebResponse.Redirect(paypalRedirectUrl);
 }
コード例 #5
0
        protected void Submit_Click(object sender, EventArgs e)
        {
            // Create request object
            SetExpressCheckoutRequestType request = new SetExpressCheckoutRequestType();
            populateRequestObject(request);

            // Invoke the API
            SetExpressCheckoutReq wrapper = new SetExpressCheckoutReq();
            wrapper.SetExpressCheckoutRequest = request;
            PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService();
            SetExpressCheckoutResponseType setECResponse = service.SetExpressCheckout(wrapper);

            // Check for API return status
            HttpContext CurrContext = HttpContext.Current;
            CurrContext.Items.Add("paymentDetails", request.SetExpressCheckoutRequestDetails.PaymentDetails);
            setKeyResponseObjects(service, setECResponse);
        }
コード例 #6
0
ファイル: ReviewOrderViewModel.cs プロジェクト: jtbradley/BRR
        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;
        }
 /// <summary> 
 /// 
 /// </summary>
 ///<param name="setExpressCheckoutReq"></param>
 public SetExpressCheckoutResponseType SetExpressCheckout(SetExpressCheckoutReq setExpressCheckoutReq)
 {
     return SetExpressCheckout(setExpressCheckoutReq,(string) null);
 }
コード例 #8
0
 /**
   *AUTO_GENERATED
  	  */
 public SetExpressCheckoutResponseType SetExpressCheckout(SetExpressCheckoutReq setExpressCheckoutReq, string apiUserName)
 {
     IAPICallPreHandler apiCallPreHandler = null;
      		string portName = "PayPalAPIAA";
     setStandardParams(setExpressCheckoutReq.SetExpressCheckoutRequest);
     DefaultSOAPAPICallHandler defaultHandler = new DefaultSOAPAPICallHandler(setExpressCheckoutReq.ToXMLString(null, "SetExpressCheckoutReq"), null, null);
     apiCallPreHandler = new MerchantAPICallPreHandler(defaultHandler, apiUserName, getAccessToken(), getAccessTokenSecret());
     ((MerchantAPICallPreHandler) apiCallPreHandler).SDKName = SDKName;
     ((MerchantAPICallPreHandler) apiCallPreHandler).SDKVersion = SDKVersion;
     ((MerchantAPICallPreHandler) apiCallPreHandler).PortName = portName;
     string response = Call(apiCallPreHandler);
     XmlDocument xmlDocument = new XmlDocument();
     xmlDocument.LoadXml(response);
     XmlNode xmlNode = xmlDocument.SelectSingleNode("*[local-name()='Envelope']/*[local-name()='Body']/*[local-name()='SetExpressCheckoutResponse']");
     return new SetExpressCheckoutResponseType(xmlNode);
 }
コード例 #9
0
		/// <summary>
		/// Processes the Authorize and AuthorizeAndCapture transactions
		/// </summary>
		/// <param name="invoice">The <see cref="IInvoice"/> to be paid</param>
		/// <param name="payment">The <see cref="IPayment"/> record</param>
		/// <param name="args"></param>
		/// <returns>The <see cref="IPaymentResult"/></returns>
		public IPaymentResult InitializePayment(IInvoice invoice, IPayment payment, ProcessorArgumentCollection args) {

			var setExpressCheckoutRequestDetails = new SetExpressCheckoutRequestDetailsType();

			Func<string, string> adjustUrl = (url) => {
				if (!url.StartsWith("http")) url = GetWebsiteUrl() + (url[0] == '/' ? "" : "/") + url;
				url = url.Replace("{invoiceKey}", invoice.Key.ToString(), StringComparison.InvariantCultureIgnoreCase);
				url = url.Replace("{paymentKey}", payment.Key.ToString(), StringComparison.InvariantCultureIgnoreCase);
				url = url.Replace("{paymentMethodKey}", payment.PaymentMethodKey.ToString(), StringComparison.InvariantCultureIgnoreCase);
				return url;
			};
			
			// Save ReturnUrl and CancelUrl in ExtendedData.
			// They will be usefull in PayPalApiController.

			var returnUrl = args.GetReturnUrl();
			if (returnUrl.IsEmpty()) returnUrl = _settings.ReturnUrl;
			if (returnUrl.IsEmpty()) returnUrl = "/";
			returnUrl = adjustUrl(returnUrl);
			payment.ExtendedData.SetValue(Constants.ExtendedDataKeys.ReturnUrl, returnUrl);

			var cancelUrl = args.GetCancelUrl();
			if (cancelUrl.IsEmpty()) cancelUrl = _settings.CancelUrl;
			if (cancelUrl.IsEmpty()) cancelUrl = "/";
			cancelUrl = adjustUrl(cancelUrl);
			payment.ExtendedData.SetValue(Constants.ExtendedDataKeys.CancelUrl, cancelUrl);

			// Set ReturnUrl and CancelUrl of PayPal request to PayPalApiController.
			setExpressCheckoutRequestDetails.ReturnURL = adjustUrl("/umbraco/MerchelloPayPal/PayPalApi/SuccessPayment?InvoiceKey={invoiceKey}&PaymentKey={paymentKey}");
			setExpressCheckoutRequestDetails.CancelURL = adjustUrl("/umbraco/MerchelloPayPal/PayPalApi/AbortPayment?InvoiceKey={invoiceKey}&PaymentKey={paymentKey}");

			//setExpressCheckoutRequestDetails.OrderDescription = "#" + invoice.InvoiceNumber;
			setExpressCheckoutRequestDetails.PaymentDetails = new List<PaymentDetailsType> { CreatePayPalPaymentDetails(invoice, args) };

			var setExpressCheckout = new SetExpressCheckoutReq() {
				SetExpressCheckoutRequest = new SetExpressCheckoutRequestType(setExpressCheckoutRequestDetails)
			};

			try {
				var response = GetPayPalService().SetExpressCheckout(setExpressCheckout);
				if (response.Ack != AckCodeType.SUCCESS && response.Ack != AckCodeType.SUCCESSWITHWARNING) {
					return new PaymentResult(Attempt<IPayment>.Fail(payment, CreateErrorResult(response.Errors)), invoice, false);
				}

				var redirectUrl = string.Format("https://www.{0}paypal.com/cgi-bin/webscr?cmd=_express-checkout&token={1}", (_settings.LiveMode ? "" : "sandbox."), response.Token);
				payment.ExtendedData.SetValue("RedirectUrl", redirectUrl);
				return new PaymentResult(Attempt<IPayment>.Succeed(payment), invoice, true);

			} catch (Exception ex) {
				return new PaymentResult(Attempt<IPayment>.Fail(payment, ex), invoice, true);
			}

		}
コード例 #10
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);
        }
コード例 #11
0
		private SetExpressCheckoutReq CreatePaypalRequest(CustomerOrder order, Store store, PaymentIn payment)
		{
			var retVal = new SetExpressCheckoutReq();

			var request = new SetExpressCheckoutRequestType();

			var ecDetails = new SetExpressCheckoutRequestDetailsType
			{
				CallbackTimeout = "3",
				ReturnURL = string.Format("{0}/{1}?cancel=false&orderId={2}", store.Url, PaypalPaymentRedirectRelativePath, order.Id),
				CancelURL = string.Format("{0}/{1}?cancel=true&orderId={2}", store.Url, PaypalPaymentRedirectRelativePath, order.Id)
			};

			if (PaypalPaymentModeStoreSetting.Equals("BankCard"))
			{
				ecDetails.SolutionType = SolutionTypeType.SOLE;
				ecDetails.LandingPage = LandingPageType.BILLING;
			}
			else
			{
				ecDetails.SolutionType = SolutionTypeType.MARK;
				ecDetails.LandingPage = LandingPageType.LOGIN;
			}

			var currency = (CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), order.Currency.ToString());

			var billingAddress = order.Addresses.FirstOrDefault(s => s.AddressType == VirtoCommerce.Domain.Order.Model.AddressType.Billing);

			if (billingAddress != null)
				ecDetails.BuyerEmail = billingAddress.Email;
			else
				billingAddress = order.Addresses.FirstOrDefault();

			if (billingAddress != null && !string.IsNullOrEmpty(billingAddress.Email))
				ecDetails.BuyerEmail = billingAddress.Email;

			ecDetails.PaymentDetails.Add(GetPaypalPaymentDetail(currency, PaymentActionCodeType.SALE, payment));

			request.SetExpressCheckoutRequestDetails = ecDetails;

			retVal.SetExpressCheckoutRequest = request;

			return retVal;
		}
コード例 #12
0
 public SetExpressCheckoutResponseType SetExpressCheckout(SetExpressCheckoutReq SetExpressCheckoutReq)
 {
     return SetExpressCheckout(SetExpressCheckoutReq, null);
 }
コード例 #13
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;

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

            // # 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();
                logger.Info(acknowledgement + "\n");
                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
                    logger.Info("Express Checkout Token : " + responseSetExpressCheckoutResponseType.Token + "\n");
                    Console.WriteLine("Express Checkout Token : " + responseSetExpressCheckoutResponseType.Token + "\n");
                }
                // # Error Values
                else
                {
                    List<ErrorType> errorMessages = responseSetExpressCheckoutResponseType.Errors;
                    foreach (ErrorType error in errorMessages)
                    {
                        logger.Debug("API Error Message : " + error.LongMessage);
                        Console.WriteLine("API Error Message : " + error.LongMessage + "\n");
                    }
                }
            }

        }
        // # Exception log    
        catch (System.Exception ex)
        {
            // Log the exception message       
            logger.Debug("Error Message : " + ex.Message);
            Console.WriteLine("Error Message : " + ex.Message);
        }
        return responseSetExpressCheckoutResponseType;
    }
コード例 #14
0
        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)));
        }
コード例 #15
0
        /// <summary>
        /// Handles ParallelPayment
        /// </summary>
        /// <param name="contextHttp"></param>
        private void ParallelPayment(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/DoExpressCheckoutForParallelPayment.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/DoExpressCheckout.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"];

            SellerDetailsType seller1 = new SellerDetailsType();
            seller1.PayPalAccountID = parameters["receiverEmail_0"];
            PaymentDetailsType paymentDetails1 = new PaymentDetailsType();
            paymentDetails1.SellerDetails = seller1;
            paymentDetails1.PaymentRequestID = parameters["paymentRequestID_0"];
            BasicAmountType orderTotal1 = new BasicAmountType();
            orderTotal1.currencyID = (CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), parameters["currencyCode"]);
            orderTotal1.value = parameters["orderTotal"];
            paymentDetails1.OrderTotal = orderTotal1;

            SellerDetailsType seller2 = new SellerDetailsType();
            seller2.PayPalAccountID = parameters["receiverEmail_1"];
            PaymentDetailsType paymentDetails2 = new PaymentDetailsType();
            paymentDetails2.SellerDetails = seller2;
            paymentDetails2.PaymentRequestID = parameters["paymentRequestID_1"];
            BasicAmountType orderTotal2 = new BasicAmountType();
            orderTotal2.currencyID = (CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), parameters["currencyCode"]);
            orderTotal2.value = parameters["orderTotal"];
            paymentDetails2.OrderTotal = orderTotal2;

            List<PaymentDetailsType> payDetails = new List<PaymentDetailsType>();
            payDetails.Add(paymentDetails1);
            payDetails.Add(paymentDetails2);

            details.PaymentDetails = payDetails;
            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, "ParallelPayment", "SetExpressCheckout", responseValues, service.getLastRequest(), service.getLastResponse(), response.Errors, redirectUrl);
        }
コード例 #16
0
        /// <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);
        }
コード例 #17
0
 /**
   *AUTO_GENERATED
  	  */
 public SetExpressCheckoutResponseType SetExpressCheckout(SetExpressCheckoutReq setExpressCheckoutReq, string apiUserName)
 {
     setStandardParams(setExpressCheckoutReq.SetExpressCheckoutRequest);
     string response = Call("SetExpressCheckout", setExpressCheckoutReq.ToXMLString(), apiUserName);
     XmlDocument xmlDocument = new XmlDocument();
     xmlDocument.LoadXml(response);
     XmlNode xmlNode = xmlDocument.SelectSingleNode("*[local-name()='Envelope']/*[local-name()='Body']/*[local-name()='SetExpressCheckoutResponse']");
     return new SetExpressCheckoutResponseType(xmlNode);
 }
        /// <summary>
        /// 
        /// </summary>
        ///<param name="setExpressCheckoutReq"></param>
        ///<param name="credential">An explicit ICredential object that you want to authenticate this call against</param> 
        public SetExpressCheckoutResponseType SetExpressCheckout(SetExpressCheckoutReq setExpressCheckoutReq, ICredential credential)
        {
            setStandardParams(setExpressCheckoutReq.SetExpressCheckoutRequest);
            DefaultSOAPAPICallHandler defaultHandler = new DefaultSOAPAPICallHandler(this.config, setExpressCheckoutReq.ToXMLString(null, "SetExpressCheckoutReq"), null, null);
            IAPICallPreHandler apiCallPreHandler = new MerchantAPICallPreHandler(this.config, defaultHandler, credential);
            ((MerchantAPICallPreHandler) apiCallPreHandler).SDKName = SDKName;
            ((MerchantAPICallPreHandler) apiCallPreHandler).SDKVersion = SDKVersion;
            ((MerchantAPICallPreHandler) apiCallPreHandler).PortName = "PayPalAPIAA";

            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.LoadXml(Call(apiCallPreHandler));
            return new SetExpressCheckoutResponseType(
                xmlDocument.SelectSingleNode("*[local-name()='Envelope']/*[local-name()='Body']/*[local-name()='SetExpressCheckoutResponse']")
            );
        }
コード例 #19
0
        protected void Submit_Click(object sender, EventArgs e)
        {
            // Create request object
            SetExpressCheckoutRequestType request = new SetExpressCheckoutRequestType();
            populateRequestObject(request);

            // Invoke the API
            SetExpressCheckoutReq wrapper = new SetExpressCheckoutReq();
            wrapper.SetExpressCheckoutRequest = 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 SetExpressCheckout method in service wrapper object
            SetExpressCheckoutResponseType setECResponse = service.SetExpressCheckout(wrapper);

            // Check for API return status
            HttpContext CurrContext = HttpContext.Current;
            CurrContext.Items.Add("paymentDetails", request.SetExpressCheckoutRequestDetails.PaymentDetails);
            setKeyResponseObjects(service, setECResponse);
        }
コード例 #20
0
        // # SetExpressCheckout API Operation
        // The SetExpressCheckout API operation initiates an Express Checkout transaction.
        public SetExpressCheckoutResponseType SetExpressCheckout(string payment)
        {
            // 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 = System.Web.Configuration.WebConfigurationManager.AppSettings["HostingEndpoint"] + "/HirerWorkOrder/PaymentPost";

                // 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 = System.Web.Configuration.WebConfigurationManager.AppSettings["HostingEndpoint"] + "/HirerWorkOrder/PaymentCancel";

                // # 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, payment);
                paymentDetails1.OrderTotal = orderTotal1;
                paymentDetails1.OrderDescription = System.Web.Configuration.WebConfigurationManager.AppSettings["PaypalDescription"];

                // 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.SALE;

                // 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 = System.Web.Configuration.WebConfigurationManager.AppSettings["PayPalAccountID"];
                paymentDetails1.SellerDetails = sellerDetails1;

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

                paymentDetailsList.Add(paymentDetails1);

                setExpressCheckoutRequestDetails.PaymentDetails = paymentDetailsList;

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

                setExpressCheckout.SetExpressCheckoutRequest = setExpressCheckoutRequest;

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

                // # API call
                // Invoke the SetExpressCheckout method in service wrapper object
                responseSetExpressCheckoutResponseType = service.SetExpressCheckout(setExpressCheckout);
            }
            // # Exception log
            catch (System.Exception ex)
            {
                // Log the exception message
                levent.Level = LogLevel.Error;
                levent.Message = "Logon failed for PaypalExpressCheckout: " + ex.Message;
                log.Log(levent);
            }
            return responseSetExpressCheckoutResponseType;
        }
コード例 #21
0
        /**
         *
         */
        public SetExpressCheckoutResponseType SetExpressCheckout(SetExpressCheckoutReq SetExpressCheckoutReq, string apiUsername)
        {
            setStandardParams(SetExpressCheckoutReq.SetExpressCheckoutRequest);
            string resp = call("SetExpressCheckout", SetExpressCheckoutReq.toXMLString(), apiUsername);

            return new SetExpressCheckoutResponseType(resp);
        }