コード例 #1
0
ファイル: PaypalAPI.cs プロジェクト: mikeshane/MerchantTribe
        public SetExpressCheckoutResponseType SetExpressCheckout(string paymentAmount, string returnURL, string cancelURL, PaymentActionCodeType paymentAction, CurrencyCodeType currencyCodeType, string invoiceId)
        {
            // Create the request object
            SetExpressCheckoutRequestType pp_request = new SetExpressCheckoutRequestType();

            // Create the request details object
            pp_request.SetExpressCheckoutRequestDetails = new SetExpressCheckoutRequestDetailsType();
            pp_request.SetExpressCheckoutRequestDetails.PaymentAction          = paymentAction;
            pp_request.SetExpressCheckoutRequestDetails.PaymentActionSpecified = true;
            pp_request.SetExpressCheckoutRequestDetails.InvoiceID  = invoiceId;
            pp_request.SetExpressCheckoutRequestDetails.OrderTotal = new BasicAmountType();

            pp_request.SetExpressCheckoutRequestDetails.OrderTotal.currencyID = currencyCodeType;
            pp_request.SetExpressCheckoutRequestDetails.OrderTotal.Value      = paymentAmount;

            pp_request.SetExpressCheckoutRequestDetails.CancelURL = cancelURL;
            pp_request.SetExpressCheckoutRequestDetails.ReturnURL = returnURL;

            return((SetExpressCheckoutResponseType)caller.Call("SetExpressCheckout", pp_request));
        }
コード例 #2
0
        private void PopulateSetCheckoutRequestObject(SetExpressCheckoutRequestType request)
        {
            var requestedDetails = new SetExpressCheckoutRequestDetailsType();

            requestedDetails.SolutionType    = SolutionTypeType.SOLE;
            requestedDetails.NoShipping      = "1";
            requestedDetails.BuyerEmail      = Checkout.BillingInfo.Email;
            requestedDetails.AddressOverride = "0";
            requestedDetails.BillingAddress  = 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
            };
            requestedDetails.BrandName = "Bluecoat Software";
            PopulatePaymentDetails(requestedDetails);
            requestedDetails.ReturnURL = CheckoutReturnUrl; requestedDetails.CancelURL = CancelUrl; request.SetExpressCheckoutRequestDetails = requestedDetails;
        }
コード例 #3
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);
        }
コード例 #4
0
ファイル: PaypalAPI.cs プロジェクト: mikeshane/MerchantTribe
        public SetExpressCheckoutResponseType SetExpressCheckout(string paymentAmount, string returnURL, string cancelURL, PaymentActionCodeType paymentAction, CurrencyCodeType currencyCodeType, String name, String countryISOCode, String street1, String street2, String city, String region, String postalCode, String phone, string invoiceId)
        {
            // Create the request object
            SetExpressCheckoutRequestType pp_request = new SetExpressCheckoutRequestType();

            // Create the request details object
            pp_request.SetExpressCheckoutRequestDetails = new SetExpressCheckoutRequestDetailsType();
            pp_request.SetExpressCheckoutRequestDetails.PaymentAction          = paymentAction;
            pp_request.SetExpressCheckoutRequestDetails.PaymentActionSpecified = true;

            pp_request.SetExpressCheckoutRequestDetails.AddressOverride = "1";
            pp_request.SetExpressCheckoutRequestDetails.InvoiceID       = invoiceId;

            pp_request.SetExpressCheckoutRequestDetails.OrderTotal = new BasicAmountType();

            pp_request.SetExpressCheckoutRequestDetails.OrderTotal.currencyID = currencyCodeType;
            pp_request.SetExpressCheckoutRequestDetails.OrderTotal.Value      = paymentAmount;

            pp_request.SetExpressCheckoutRequestDetails.CancelURL = cancelURL;
            pp_request.SetExpressCheckoutRequestDetails.ReturnURL = returnURL;

            pp_request.SetExpressCheckoutRequestDetails.Address = new AddressType();
            pp_request.SetExpressCheckoutRequestDetails.Address.AddressStatusSpecified = false;
            pp_request.SetExpressCheckoutRequestDetails.Address.AddressOwnerSpecified  = false;

            pp_request.SetExpressCheckoutRequestDetails.Address.Street1          = street1;
            pp_request.SetExpressCheckoutRequestDetails.Address.Street2          = street2;
            pp_request.SetExpressCheckoutRequestDetails.Address.CityName         = city;
            pp_request.SetExpressCheckoutRequestDetails.Address.StateOrProvince  = region;
            pp_request.SetExpressCheckoutRequestDetails.Address.PostalCode       = postalCode;
            pp_request.SetExpressCheckoutRequestDetails.Address.CountrySpecified = true;
            pp_request.SetExpressCheckoutRequestDetails.Address.Country          = GetCountryCode(countryISOCode);
            pp_request.SetExpressCheckoutRequestDetails.Address.Phone            = phone;
            pp_request.SetExpressCheckoutRequestDetails.Address.Name             = name;
            return((SetExpressCheckoutResponseType)caller.Call("SetExpressCheckout", pp_request));
        }
コード例 #5
0
        public string GenerateOrder(List <ItemPayPal> items)
        {
            // Create request object
            SetExpressCheckoutRequestType request = new SetExpressCheckoutRequestType();

            SetExpressCheckoutRequestDetailsType ecDetails = new SetExpressCheckoutRequestDetailsType();



            /* 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.MXN;


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

            paymentDetails.OrderDescription = "";

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

            paymentDetails.ButtonSource = "PTSH";

            foreach (ItemPayPal item in items)
            {
                PaymentDetailsItemType details = new PaymentDetailsItemType()
                {
                    Name     = item.Name,
                    Amount   = new BasicAmountType(currency, ((decimal)item.Price).ToString()),
                    Quantity = item.Quantity
                };

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

                itemTotal += Convert.ToDouble(details.Amount.value) * details.Quantity.Value;

                //(Optional) Item description.
                // Character length and limitations: 127 single-byte characters
                // This field is introduced in version 53.0.

                details.Description = item.Description;

                paymentDetails.PaymentDetailsItem.Add(details);
            }

            orderTotal += itemTotal;
            paymentDetails.ItemTotal  = new BasicAmountType(currency, itemTotal.ToString());
            paymentDetails.OrderTotal = new BasicAmountType(currency, orderTotal.ToString());
            paymentDetails.Custom     = "9998";
            paymentDetails.InvoiceID  = null;

            ecDetails.ReturnURL          = AppSettings.PayPalCallbackOk;
            ecDetails.CancelURL          = AppSettings.PayPalCallbackFail;
            ecDetails.NoShipping         = "1";
            ecDetails.AllowNote          = "0";
            ecDetails.cppCartBorderColor = "0b5ba1";

            // (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.
            ecDetails.cppHeaderImage = "";

            request.SetExpressCheckoutRequestDetails = ecDetails;

            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////


            // Invoke the API
            SetExpressCheckoutReq wrapper = new SetExpressCheckoutReq();

            wrapper.SetExpressCheckoutRequest = request;

            System.Net.ServicePointManager.Expect100Continue = false;

            // 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]

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

            //wrapper.SetExpressCheckoutRequest.Version = "84.0";
            // # API call
            // Invoke the SetExpressCheckout method in service wrapper object
            SetExpressCheckoutResponseType setECResponse = service.SetExpressCheckout(wrapper);

            // Check for API return status

            if (setECResponse.Ack.Equals(AckCodeType.FAILURE) || (setECResponse.Errors != null && setECResponse.Errors.Any()))
            {
                return(string.Empty);
            }
            return(setECResponse.Token);
        }
コード例 #6
0
        /// <summary>
        /// Performs the setup for an express checkout.
        /// </summary>
        /// <param name="invoice">
        /// The <see cref="IInvoice"/>.
        /// </param>
        /// <param name="payment">
        /// The <see cref="IPayment"/>
        /// </param>
        /// <param name="returnUrl">
        /// The return URL.
        /// </param>
        /// <param name="cancelUrl">
        /// The cancel URL.
        /// </param>
        /// <returns>
        /// The <see cref="ExpressCheckoutResponse"/>.
        /// </returns>
        protected virtual PayPalExpressTransactionRecord SetExpressCheckout(IInvoice invoice, IPayment payment, string returnUrl, string cancelUrl)
        {
            var record = new PayPalExpressTransactionRecord
                             {
                                 Success = true,
                                 Data = { Authorized = false, CurrencyCode = invoice.CurrencyCode }
                             };

            var factory = new PayPalPaymentDetailsTypeFactory(new PayPalFactorySettings { WebsiteUrl = _websiteUrl });
            var paymentDetailsType = factory.Build(invoice, PaymentActionCodeType.ORDER);

            // The API requires this be in a list
            var paymentDetailsList = new List<PaymentDetailsType>() { paymentDetailsType };

            // ExpressCheckout details
            var ecDetails = new SetExpressCheckoutRequestDetailsType()
                    {
                        ReturnURL = returnUrl,
                        CancelURL = cancelUrl,
                        PaymentDetails = paymentDetailsList,
                        AddressOverride = "0"
                    };

            // Trigger the event to allow for overriding ecDetails
            var ecdOverride = new PayPalExpressCheckoutRequestDetailsOverride(invoice, payment, ecDetails);
            SettingCheckoutRequestDetails.RaiseEvent(new ObjectEventArgs<PayPalExpressCheckoutRequestDetailsOverride>(ecdOverride), this);

            // The ExpressCheckoutRequest
            var request = new SetExpressCheckoutRequestType
                    {
                        Version = Version,
                        SetExpressCheckoutRequestDetails = ecdOverride.ExpressCheckoutDetails
                    };

            // Crete the wrapper for Express Checkout
            var wrapper = new SetExpressCheckoutReq
                              {
                                  SetExpressCheckoutRequest = request
                              };

            try
            {
                var service = GetPayPalService();
                var response = service.SetExpressCheckout(wrapper);

                record.SetExpressCheckout = _responseFactory.Build(response, response.Token);
                if (record.SetExpressCheckout.Success())
                {
                    record.Data.Token = response.Token;
                    record.SetExpressCheckout.RedirectUrl = GetRedirectUrl(response.Token);
                }
                else
                {
                    foreach (var et in record.SetExpressCheckout.ErrorTypes)
                    {
                        var code = et.ErrorCode;
                        var sm = et.ShortMessage;
                        var lm = et.LongMessage;
                        MultiLogHelper.Warn<PayPalExpressCheckoutService>(string.Format("{0} {1} {2}", code, lm, sm));
                    }

                    record.Success = false;
                }
            }
            catch (Exception ex)
            {
                record.Success = false;
                record.SetExpressCheckout = _responseFactory.Build(ex);
            }

            return record;
        }
コード例 #7
0
ファイル: Default.aspx.cs プロジェクト: blendev/Trumans
        protected void btnPPCont_Click(object sender, EventArgs e)
        {
            try
            {
                var Surcharge   = Math.Round((Convert.ToDouble(amount.Value) * 3) / 100, 2);
                var orderAmount = (Convert.ToDouble(amount.Value) + Surcharge).ToString();

                Dictionary <string, string> PPPayment = new Dictionary <string, string>();
                PPPayment.Add("AccNum", accountNum.Value);
                // PPPayment.Add("Amount", amount.Value);

                PPPayment.Add("Amount", orderAmount);

                Session["PPPaymentDetails"] = PPPayment;
                CustomSecurityHeaderType _credentials = new CustomSecurityHeaderType
                {
                    Credentials = new UserIdPasswordType()
                    {
                        Username  = System.Configuration.ConfigurationManager.AppSettings["UserName"].ToString(),
                        Password  = System.Configuration.ConfigurationManager.AppSettings["Password"].ToString(),
                        Signature = System.Configuration.ConfigurationManager.AppSettings["Signature"].ToString(),
                    }
                };


                var expressCheckoutRequestDetails = new SetExpressCheckoutRequestDetailsType();
                // expressCheckoutRequestDetails.ReturnURL = "http://payment.trumans.blendev.com/PayPalPayment.aspx";
                //expressCheckoutRequestDetails.CancelURL = "http://payment.trumans.blendev.com/PayPalCancel.aspx";
                expressCheckoutRequestDetails.CancelURL  = System.Configuration.ConfigurationManager.AppSettings["CancelURL"].ToString();
                expressCheckoutRequestDetails.ReturnURL  = System.Configuration.ConfigurationManager.AppSettings["SuccessURL"].ToString();
                expressCheckoutRequestDetails.NoShipping = "1";
                var paymentDetailsArray = new PaymentDetailsType[1];
                paymentDetailsArray[0] = new PaymentDetailsType
                {
                    PaymentAction = PaymentActionCodeType.Sale,
                    OrderTotal    = new BasicAmountType
                    {
                        currencyID = CurrencyCodeType.AUD,
                        Value      = orderAmount.ToString(),
                    }
                };

                BasicAmountType OTotal = new BasicAmountType();
                OTotal.Value      = orderAmount.ToString();
                OTotal.currencyID = CurrencyCodeType.AUD;
                expressCheckoutRequestDetails.OrderTotal = OTotal;

                var ExpressCheck = new SetExpressCheckoutRequestType
                {
                    SetExpressCheckoutRequestDetails = expressCheckoutRequestDetails,
                    Version = "98",
                };

                SetExpressCheckoutReq obj = new SetExpressCheckoutReq();
                obj.SetExpressCheckoutRequest = ExpressCheck;

                PayPalAPI.PayPalAPIAAInterfaceClient objPayPalAPI = new PayPalAPIAAInterfaceClient();

                var setExpressCheckoutResponse = objPayPalAPI.SetExpressCheckout(ref _credentials, obj);
                if (setExpressCheckoutResponse.Ack == AckCodeType.Success)
                {
                    Response.Redirect("https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=" + setExpressCheckoutResponse.Token, false);
                    Session["Token"] = setExpressCheckoutResponse.Token;
                }
                else
                {
                    StreamWriter File2 = File.AppendText(HttpContext.Current.Server.MapPath("~/Logs/file.txt"));
                    File2.WriteLine("Error : " + setExpressCheckoutResponse.Errors[0].LongMessage);
                    File2.Close();


                    string script = "<script type=\"text/javascript\">alert('Unexpected Error Occured , Please try Later!!');</script>";
                    ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", script);
                }
            }
            catch (Exception ex)
            {
                StreamWriter File2 = File.AppendText(HttpContext.Current.Server.MapPath("~/Logs/file.txt"));
                File2.WriteLine("Error : " + ex.Message);
                File2.Close();


                string script = "<script type=\"text/javascript\">alert('Unexpected Error Occured , Please try Later!!');</script>";
                ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", script);
            }
        }
コード例 #8
0
ファイル: PaypalAPI.cs プロジェクト: appliedi/MerchantTribe
        public SetExpressCheckoutResponseType SetExpressCheckout(string paymentAmount, string returnURL, string cancelURL, PaymentActionCodeType paymentAction, CurrencyCodeType currencyCodeType, String name, String countryISOCode, String street1, String street2, String city, String region, String postalCode, String phone, string invoiceId)
        {
            // Create the request object
            SetExpressCheckoutRequestType pp_request = new SetExpressCheckoutRequestType();

            // Create the request details object
            pp_request.SetExpressCheckoutRequestDetails = new SetExpressCheckoutRequestDetailsType();
            pp_request.SetExpressCheckoutRequestDetails.PaymentAction = paymentAction;
            pp_request.SetExpressCheckoutRequestDetails.PaymentActionSpecified = true;

            pp_request.SetExpressCheckoutRequestDetails.AddressOverride = "1";
            pp_request.SetExpressCheckoutRequestDetails.InvoiceID = invoiceId;

            pp_request.SetExpressCheckoutRequestDetails.OrderTotal = new BasicAmountType();

            pp_request.SetExpressCheckoutRequestDetails.OrderTotal.currencyID = currencyCodeType;
            pp_request.SetExpressCheckoutRequestDetails.OrderTotal.Value = paymentAmount;

            pp_request.SetExpressCheckoutRequestDetails.CancelURL = cancelURL;
            pp_request.SetExpressCheckoutRequestDetails.ReturnURL = returnURL;
            
            pp_request.SetExpressCheckoutRequestDetails.Address = new AddressType();            
            pp_request.SetExpressCheckoutRequestDetails.Address.AddressStatusSpecified = false;
            pp_request.SetExpressCheckoutRequestDetails.Address.AddressOwnerSpecified = false;

            pp_request.SetExpressCheckoutRequestDetails.Address.Street1 = street1;
            pp_request.SetExpressCheckoutRequestDetails.Address.Street2 = street2;
            pp_request.SetExpressCheckoutRequestDetails.Address.CityName = city;
            pp_request.SetExpressCheckoutRequestDetails.Address.StateOrProvince = region;
            pp_request.SetExpressCheckoutRequestDetails.Address.PostalCode = postalCode;
            pp_request.SetExpressCheckoutRequestDetails.Address.CountrySpecified = true;
            pp_request.SetExpressCheckoutRequestDetails.Address.Country = GetCountryCode(countryISOCode);                        
            pp_request.SetExpressCheckoutRequestDetails.Address.Phone = phone;
            pp_request.SetExpressCheckoutRequestDetails.Address.Name = name;                        
            return (SetExpressCheckoutResponseType)caller.Call("SetExpressCheckout", pp_request);
        }
コード例 #9
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;
             *          //}
             * */
        }
コード例 #10
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)));
        }
コード例 #11
0
ファイル: Gateway.cs プロジェクト: ColoradoWebGuy/RockPlugins
        private SetExpressCheckoutRequestType populateRequestObject(FinancialGateway financialGateway, PaymentInfo paymentInfo, List <GatewayAccountItem> selectedAccounts)
        {
            SetExpressCheckoutRequestType        request   = new SetExpressCheckoutRequestType();
            SetExpressCheckoutRequestDetailsType ecDetails = new SetExpressCheckoutRequestDetailsType();
            String host      = GlobalAttributesCache.Value("PublicApplicationRoot");
            int    lastSlash = host.LastIndexOf('/');

            host = (lastSlash > -1) ? host.Substring(0, lastSlash) : host;
            if (financialGateway.GetAttributeValue("ReturnPage") != string.Empty)
            {
                PageReference pageReference = new PageReference(financialGateway.GetAttributeValue("ReturnPage"));
                ecDetails.ReturnURL = host + pageReference.BuildUrl();
            }
            if (financialGateway.GetAttributeValue("CancelPage") != string.Empty)
            {
                PageReference pageReference = new PageReference(financialGateway.GetAttributeValue("CancelPage"));
                ecDetails.CancelURL = host + pageReference.BuildUrl();
            }

            /*
             * // (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 = paymentInfo.Email;

            /* 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 = Convert.ToDouble(paymentInfo.Amount);
            CurrencyCodeType currency  = CurrencyCodeType.USD;

            //(Optional) Description of items the buyer is purchasing.
            paymentDetails.OrderDescription = "Contribution";

            // We do a authorization then complete the sale in the "Charge" phase
            paymentDetails.PaymentAction = PaymentActionCodeType.AUTHORIZATION;
            foreach (GatewayAccountItem item in selectedAccounts)
            {
                if (item.Amount > 0)
                {
                    PaymentDetailsItemType itemDetails = new PaymentDetailsItemType();

                    itemDetails.Name        = item.Name;
                    itemDetails.Amount      = new BasicAmountType(currency, item.Amount.ToString());
                    itemDetails.Quantity    = 1;
                    itemDetails.Description = item.PublicName;
                    itemDetails.Number      = item.Id.ToString();
                    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();

            //(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 (financialGateway.GetAttributeValue("PayPalLogoImage") != string.Empty)
            {
                ecDetails.cppHeaderImage = financialGateway.GetAttributeValue("PayPalLogoImage");
            }

            /*// (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 (financialGateway.GetAttributeValue("PayPalBrandName") != string.Empty)
            {
                ecDetails.BrandName = financialGateway.GetAttributeValue("PayPalBrandName");
            }

            request.SetExpressCheckoutRequestDetails = ecDetails;

            return(request);
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        HttpContext CurrContext = HttpContext.Current;

        // Create the SetExpressCheckoutResponseType object
        SetExpressCheckoutResponseType responseSetExpressCheckoutResponseType = new SetExpressCheckoutResponseType();

        try
        {
            // Check if the EC methos is shorcut or mark
            string ecMethod = "";
            if (Request.QueryString["ExpressCheckoutMethod"] != null)
            {
                ecMethod = Request.QueryString["ExpressCheckoutMethod"];
            }
            else if ((string)(Session["ExpressCheckoutMethod"]) != null)
            {
                ecMethod = (string)(Session["ExpressCheckoutMethod"]);
            }
            string item_name     = "";
            string item_id       = "";
            string item_desc     = "";
            string item_quantity = "";
            string item_amount   = "";
            //string tax_amount = "";
            //string shipping_amount = "";
            //string handling_amount = "";
            //string shipping_discount_amount = "";
            //string insurance_amount = "";
            string total_amount  = "";
            string currency_code = "";
            string payment_type  = "";
            string roundedtotal  = "";
            string roundeditmamt = "";

            // From Marck EC Page
            //string shipping_rate = "";
            string first_name  = "";
            string last_name   = "";
            string street1     = "";
            string street2     = "";
            string city        = "";
            string state       = "";
            string postal_code = "";
            string country     = "";
            string phone       = "";
            //Double new_total_rate = 0.00;
            AddressType shipToAddress = new AddressType();
            if (ecMethod != null && ecMethod == "ShorcutExpressCheckout")
            {
                // Get parameters from index page (shorcut express checkout)
                item_name     = Request.Form["item_name"];
                item_id       = Request.Form["item_id"];
                item_desc     = Request.Form["item_desc"];
                item_quantity = Request.Form["item_quantity"];
                item_amount   = Request.Form["item_amount"];

                total_amount            = Request.Form["total_amount"];
                currency_code           = Request.Form["currency_code_type"];
                payment_type            = Request.Form["payment_type"];
                Session["Total_Amount"] = total_amount;

                roundeditmamt = (Math.Round(double.Parse(item_amount), 2)).ToString();
                roundedtotal  = (Math.Round(double.Parse(total_amount), 2)).ToString();
            }
            else if (ecMethod != null && ecMethod == "MarkExpressCheckout")
            {
                // Get parameters from mark ec page
                //shipping_rate = Request.Form["shipping_method"].ToString();

                item_name     = Request.Form["item_name"];
                item_id       = Request.Form["item_id"];
                item_desc     = Request.Form["item_desc"];
                item_quantity = Request.Form["item_quantity"];
                item_amount   = Request.Form["item_amount"];
                //tax_amount = Request.Form["tax_amount"];
                //shipping_amount = Request.Form["shipping_amount"];
                //handling_amount = Request.Form["handling_amount"];
                //shipping_discount_amount = Request.Form["shipping_discount_amount"];
                //insurance_amount = Request.Form["insurance_amount"];
                total_amount  = Request.Form["total_amount"];
                currency_code = Request.Form["currency_code"];
                payment_type  = Request.Form["payment_type"];

                first_name  = Request.Form["FIRST_NAME"];
                last_name   = Request.Form["LAST_NAME"];
                street1     = Request.Form["STREET_1"];
                street2     = Request.Form["STREET_2"];
                city        = Request.Form["CITY"];
                state       = Request.Form["STATE"];
                postal_code = Request.Form["POSTAL_CODE"];
                country     = Request.Form["COUNTRY"];
                phone       = Request.Form["PHONE"];

                roundeditmamt = (Math.Round(double.Parse(item_amount), 2)).ToString();
                roundedtotal  = (Math.Round(double.Parse(total_amount), 2)).ToString();

                // Set the details of new shipping address
                //shipToAddress.Name = first_name + " " + last_name;
                //shipToAddress.Street1 = street1;
                //if (!street2.Equals(""))
                //{
                //    shipToAddress.Street2 = street2;
                //}
                //shipToAddress.CityName = city;
                //shipToAddress.StateOrProvince = state;
                //string countrycode = country;
                //CountryCodeType countryCodeType = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), countrycode, true);
                //shipToAddress.Country = countryCodeType;
                //shipToAddress.PostalCode = postal_code;
                //if (!phone.Equals(""))
                //{
                //    shipToAddress.Phone = phone;
                //}

                //Double total_rate = Convert.ToDouble(total_amount);
                //Double old_shipping_rate = Convert.ToDouble(shipping_amount);
                //Double new_shipping_rate = Convert.ToDouble(shipping_rate);

                // Calculate new order total based on shipping method selected
                //new_total_rate = total_rate - old_shipping_rate + new_shipping_rate;
                //Session["Total_Amount"] = new_total_rate.ToString();
                //total_amount = new_total_rate.ToString();
                //shipping_amount = new_shipping_rate.ToString();
            }

            Session["SellerEmail"] = SellerEmail;
            CurrencyCodeType currencyCode_Type = (CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), currency_code, true);
            Session["currency_code_type"] = currencyCode_Type;
            PaymentActionCodeType payment_ActionCode_Type = (PaymentActionCodeType)Enum.Parse(typeof(PaymentActionCodeType), payment_type, true);
            Session["payment_action_type"] = payment_ActionCode_Type;
            // SetExpressCheckoutRequestDetailsType object
            SetExpressCheckoutRequestDetailsType setExpressCheckoutRequestDetails = new SetExpressCheckoutRequestDetailsType();
            // (Required) URL to which the buyer's browser is returned after choosing to pay with PayPal.
            setExpressCheckoutRequestDetails.ReturnURL = ReturnUrl;
            //(Required) URL to which the buyer is returned if the buyer does not approve the use of PayPal to pay you
            setExpressCheckoutRequestDetails.CancelURL = CancelUrl;
            // A URL to your logo image. Use a valid graphics format, such as .gif, .jpg, or .png
            setExpressCheckoutRequestDetails.cppLogoImage = LogoUrl;
            // To display the border in your principal identifying color, set the "cppCartBorderColor" parameter to the 6-digit hexadecimal value of that color
            // setExpressCheckoutRequestDetails.cppCartBorderColor = "0000CD";

            //Item details
            PaymentDetailsItemType itemDetails = new PaymentDetailsItemType();
            itemDetails.Name        = item_name;
            itemDetails.Amount      = new BasicAmountType(currencyCode_Type, roundeditmamt);
            itemDetails.Quantity    = Convert.ToInt32(item_quantity);
            itemDetails.Description = item_desc;
            itemDetails.Number      = item_id;

            //Add more items if necessary by using the class 'PaymentDetailsItemType'

            // Payment Information
            List <PaymentDetailsType> paymentDetailsList = new List <PaymentDetailsType>();

            PaymentDetailsType paymentDetails = new PaymentDetailsType();
            paymentDetails.PaymentAction = payment_ActionCode_Type;
            paymentDetails.ItemTotal     = new BasicAmountType(currencyCode_Type, roundeditmamt);//item amount
            //paymentDetails.TaxTotal = new BasicAmountType(currencyCode_Type, tax_amount); //tax amount;
            //paymentDetails.ShippingTotal = new BasicAmountType(currencyCode_Type, shipping_amount); //shipping amount
            //paymentDetails.HandlingTotal = new BasicAmountType(currencyCode_Type, handling_amount); //handling amount
            //paymentDetails.ShippingDiscount = new BasicAmountType(currencyCode_Type, shipping_discount_amount); //shipping discount
            //paymentDetails.InsuranceTotal = new BasicAmountType(currencyCode_Type, insurance_amount); //insurance amount
            paymentDetails.OrderTotal = new BasicAmountType(currencyCode_Type, roundedtotal); // order total amount

            paymentDetails.PaymentDetailsItem.Add(itemDetails);

            // Unique identifier for the merchant.
            SellerDetailsType sellerDetails = new SellerDetailsType();
            sellerDetails.PayPalAccountID = SellerEmail;
            paymentDetails.SellerDetails  = sellerDetails;

            if (ecMethod != null && ecMethod == "MarkExpressCheckout")
            {
                paymentDetails.ShipToAddress = shipToAddress;
            }
            paymentDetailsList.Add(paymentDetails);
            setExpressCheckoutRequestDetails.PaymentDetails = paymentDetailsList;

            // Collect Shipping details if MARK express checkout

            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.Debug(acknowledgement + "\n");
                System.Diagnostics.Debug.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.
                    // Express Checkout Token
                    string EcToken = responseSetExpressCheckoutResponseType.Token;
                    //logger.Info("Express Checkout Token : " + EcToken + "\n");
                    System.Diagnostics.Debug.WriteLine("Express Checkout Token : " + EcToken + "\n");
                    // Store the express checkout token in session to be used in GetExpressCheckoutDetails & DoExpressCheckout API operations
                    Session["EcToken"] = EcToken;
                    Response.Redirect(RedirectUrl + HttpUtility.UrlEncode(EcToken), false);
                    Context.ApplicationInstance.CompleteRequest();
                }
                // # Error Values
                else
                {
                    List <ErrorType> errorMessages = responseSetExpressCheckoutResponseType.Errors;
                    string           errorMessage  = "";
                    foreach (ErrorType error in errorMessages)
                    {
                        //logger.Debug("API Error Message : " + error.LongMessage);
                        System.Diagnostics.Debug.WriteLine("API Error Message : " + error.LongMessage + "\n");
                        errorMessage = errorMessage + error.LongMessage;
                    }
                    //Redirect to error page in case of any API errors
                    CurrContext.Items.Add("APIErrorMessage", errorMessage);
                    Server.Transfer("~/Response.aspx");
                }
            }
        }
        catch (System.Exception ex)
        {
            // Log the exception message
            //logger.Debug("Error Message : " + ex.Message);
            System.Diagnostics.Debug.WriteLine("Error Message : " + ex.Message);
        }
    }
コード例 #13
0
        protected SetExpressCheckoutResponseType ECSetExpressCheckoutCode(string paymentAmount, string returnURL, string cancelURL,
            PaymentActionCodeType paymentAction, CurrencyCodeType currencyCodeType)
        {
            CallerServices caller = CreateCaller();

            var pp_request = new SetExpressCheckoutRequestType()
            {
                Version = "51.0",
                SetExpressCheckoutRequestDetails = new SetExpressCheckoutRequestDetailsType()
                {
                    PaymentAction = paymentAction,
                    PaymentActionSpecified = true,
                    OrderTotal = new BasicAmountType()
                    {
                        currencyID = currencyCodeType,
                        Value = paymentAmount
                    },
                    CancelURL = cancelURL,
                    ReturnURL = returnURL,
                }
            };

            return (SetExpressCheckoutResponseType)caller.Call("SetExpressCheckout", pp_request);
        }
コード例 #14
0
        public ExpressCheckoutResult SetExpressCheckout()
        {
            HttpContext context = HttpContext.Current;
            User        user    = Token.Instance.User;
            Basket      basket  = user.Basket;

            //MAKE SURE BASKET IS PROPERLY PACKAGED FOR CHECKOUT
            basket.Package();

            //GET EXISTING SESSION IF IT IS PRESENT
            ExpressCheckoutSession existingSession = ExpressCheckoutSession.Current;

            if (existingSession != null)
            {
                WebTrace.Write("Existing session token: " + existingSession.Token);
            }

            //CREATE THE EXPRESS CHECKOUT REQUEST OBJECT
            SetExpressCheckoutRequestType expressCheckoutRequest = new SetExpressCheckoutRequestType();

            expressCheckoutRequest.SetExpressCheckoutRequestDetails = new SetExpressCheckoutRequestDetailsType();
            if (existingSession != null)
            {
                expressCheckoutRequest.SetExpressCheckoutRequestDetails.Token = existingSession.Token;
            }
            expressCheckoutRequest.Version = "1.0";

            //GET THE CURRENCY FOR THE TRANSACTION
            string           baseCurrencyCode = Token.Instance.Store.BaseCurrency.ISOCode;
            CurrencyCodeType baseCurrency     = PayPalProvider.GetPayPalCurrencyType(baseCurrencyCode);
            //BUILD THE REQUEST DETAILS
            SetExpressCheckoutRequestDetailsType expressCheckoutDetails = expressCheckoutRequest.SetExpressCheckoutRequestDetails;
            LSDecimal basketTotal = basket.Items.TotalPrice();

            WebTrace.Write("Basket Total: " + basketTotal.ToString());
            expressCheckoutDetails.OrderTotal            = new BasicAmountType();
            expressCheckoutDetails.OrderTotal.currencyID = baseCurrency;
            expressCheckoutDetails.OrderTotal.Value      = string.Format("{0:##,##0.00}", basketTotal);
            expressCheckoutDetails.MaxAmount             = new BasicAmountType();
            expressCheckoutDetails.MaxAmount.currencyID  = baseCurrency;
            expressCheckoutDetails.MaxAmount.Value       = string.Format("{0:##,##0.00}", basketTotal + 50);

            //SET THE URLS
            string storeUrl = GetStoreUrl();

            expressCheckoutDetails.ReturnURL = storeUrl + "/PayPalExpressCheckout.aspx?Action=GET";
            expressCheckoutDetails.CancelURL = storeUrl + "/PayPalExpressCheckout.aspx?Action=CANCEL";

            //SET THE CUSTOM VALUE TO THE USER ID FOR MATCHING DURING GET
            expressCheckoutDetails.Custom = "UID" + basket.UserId.ToString();

            //SET THE CUSTOMER ADDRESS
            Address     billingAddress = user.PrimaryAddress;
            AddressType address        = new AddressType();

            address.Name       = billingAddress.FirstName + " " + billingAddress.LastName;
            address.Street1    = billingAddress.Address1;
            address.Street2    = billingAddress.Address2;
            address.CityName   = billingAddress.City;
            address.PostalCode = billingAddress.PostalCode;
            if (billingAddress.Country != null)
            {
                address.Country = PayPalProvider.GetPayPalCountry(billingAddress.CountryCode);
            }
            else
            {
                address.Country = CountryCodeType.US;
            }
            address.CountrySpecified          = true;
            expressCheckoutDetails.BuyerEmail = billingAddress.Email;
            expressCheckoutDetails.Address    = address;

            //SET THE PAYMENT ACTION
            expressCheckoutDetails.PaymentAction          = this.UseAuthCapture ? PaymentActionCodeType.Sale : PaymentActionCodeType.Authorization;
            expressCheckoutDetails.PaymentActionSpecified = true;

            //EXECUTE REQUEST
            SetExpressCheckoutResponseType expressCheckoutResponse;

            context.Trace.Write("DO SOAP CALL");
            expressCheckoutResponse = (SetExpressCheckoutResponseType)SoapCall("SetExpressCheckout", expressCheckoutRequest);
            context.Trace.Write("CHECK SOAP RESULT");
            if (expressCheckoutResponse == null)
            {
                ErrorType[] customErrorList = new ErrorType[1];
                ErrorType   customError     = new ErrorType();
                customError.ErrorCode    = "NORESP";
                customError.ShortMessage = "No Response From Server";
                customError.LongMessage  = "The PayPal service is unavailable at this time.";
                customErrorList[0]       = customError;
                return(new ExpressCheckoutResult(0, string.Empty, customErrorList));
            }

            //IF ERRORS ARE IN RESPONSE, RETURN THEM AND EXIT PROCESS
            if (expressCheckoutResponse.Errors != null)
            {
                return(new ExpressCheckoutResult(0, string.Empty, expressCheckoutResponse.Errors));
            }

            //NO ERRORS FOUND, PUT PAYPAL DETAILS INTO SESSION
            context.Trace.Write("Store PayPal Token In Session");
            ExpressCheckoutSession newSession = new ExpressCheckoutSession();

            newSession.Token           = expressCheckoutResponse.Token;
            newSession.TokenExpiration = DateTime.UtcNow.AddHours(3);
            newSession.Save();

            context.Trace.Write("Saved PayPal Token:" + newSession.Token);
            context.Trace.Write("Token Expiration:" + newSession.TokenExpiration.ToLongDateString());

            //RETURN TO CALLER INCLUDING REDIRECTION URL
            string redirectUrl = "https://www" + (this.UseSandbox ? ".sandbox" : string.Empty) + ".paypal.com/webscr?cmd=_express-checkout&token=" + expressCheckoutResponse.Token;

            return(new ExpressCheckoutResult(0, redirectUrl, null));
        }
コード例 #15
0
        private void PopulateRequestObject(SetExpressCheckoutRequestType request, string email, string orderDescription, string billingAgreementText, string LogoURL, string brandName, double itemTotalAmount, string PlanName, double planAmount, string planDescription)
        {
            SetExpressCheckoutRequestDetailsType ecDetails = new SetExpressCheckoutRequestDetailsType();

            ecDetails.ReturnURL = System.Configuration.ConfigurationManager.AppSettings["ReturnUrl"];
            ecDetails.CancelURL = System.Configuration.ConfigurationManager.AppSettings["CancelURL"];

            ecDetails.BuyerEmail = email;
            //Optional get from merchant account ecDetails.ReqConfirmShipping=value;
            //Optional get from paypal  ecDetails.AddressOverride
            //optional ecDetails.NoShipping
            ecDetails.SolutionType = (SolutionTypeType)Enum.Parse(typeof(SolutionTypeType), "SOLE");
            //ecDetails.LandingPage = (LandingPageType)Enum.Parse(typeof(LandingPageType), "BILLING");

            //Adding payment details
            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), "USD");

            // 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), "SALE");

            // Each payment can include requestDetails about multiple items
            // This example shows just one payment item
            var itemName     = PlanName;
            var itemQuantity = 1;

            if (itemName != null && planAmount != null && itemQuantity != null)
            {
                PaymentDetailsItemType itemDetails = new PaymentDetailsItemType();
                itemDetails.Name = itemName;
                //itemDetails.Amount = new BasicAmountType(currency, planAmount.ToString()); // Comment by nitendra
                itemDetails.Amount = new BasicAmountType(currency, String.Format("{0:0.00}", planAmount)); // Added by nitendra
                // planAmount
                itemDetails.Quantity = Convert.ToInt32(itemQuantity);
                // 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), "DIGITAL");
                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 (planDescription != string.Empty)
                {
                    itemDetails.Description = planDescription;
                }
                paymentDetails.PaymentDetailsItem.Add(itemDetails);
            }

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

            // Added by nitendra
            orderTotal += itemTotal;
            paymentDetails.ItemTotal  = new BasicAmountType(currency, String.Format("{0:0.00}", itemTotal));
            paymentDetails.OrderTotal = new BasicAmountType(currency, String.Format("{0:0.00}", orderTotal));


            if (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.
                BillingCodeType billingCodeType = (BillingCodeType)
                                                  Enum.Parse(typeof(BillingCodeType), "MERCHANTINITIATEDBILLING");
                BillingAgreementDetailsType baType = new BillingAgreementDetailsType(billingCodeType);
                baType.BillingAgreementDescription = billingAgreementText;
                ecDetails.BillingAgreementDetails.Add(baType);
            }

            //Logo for Website
            // (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 (LogoURL != string.Empty)
            {
                ecDetails.cppHeaderImage = LogoURL;
            }

            // (Optional) A label that overrides the business name in the PayPal account on the PayPal hosted checkout pages.
            if (brandName != string.Empty)
            {
                ecDetails.BrandName = brandName;
            }
            request.SetExpressCheckoutRequestDetails = ecDetails;
        }
コード例 #16
0
        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;
        }
コード例 #17
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;
        }
コード例 #18
0
        /// <summary>
        /// Performs the setup for an express checkout.
        /// </summary>
        /// <param name="invoice">
        /// The <see cref="IInvoice"/>.
        /// </param>
        /// <param name="payment">
        /// The <see cref="IPayment"/>
        /// </param>
        /// <param name="returnUrl">
        /// The return URL.
        /// </param>
        /// <param name="cancelUrl">
        /// The cancel URL.
        /// </param>
        /// <returns>
        /// The <see cref="ExpressCheckoutResponse"/>.
        /// </returns>
        protected virtual PayPalExpressTransactionRecord SetExpressCheckout(IInvoice invoice, IPayment payment, string returnUrl, string cancelUrl)
        {
            var record = new PayPalExpressTransactionRecord
                             {
                                 Success = true,
                                 Data = { Authorized = false, CurrencyCode = invoice.CurrencyCode }
                             };

            var factory = new PayPalPaymentDetailsTypeFactory(new PayPalFactorySettings { WebsiteUrl = _websiteUrl });
            var paymentDetailsType = factory.Build(invoice, PaymentActionCodeType.ORDER);

            // The API requires this be in a list
            var paymentDetailsList = new List<PaymentDetailsType>() { paymentDetailsType };

            // ExpressCheckout details
            //// We do not want the customer to be able to reset their shipping address at PayPal
            //// due to the fact that it could affect shipping charges and in some cases tax rates.
            //// This is the AddressOverride = "0" - NOT WORKING!
            var ecDetails = new SetExpressCheckoutRequestDetailsType()
                    {
                        ReturnURL = returnUrl,
                        CancelURL = cancelUrl,
                        PaymentDetails = paymentDetailsList,
                        AddressOverride = "0"
                    };

            // Trigger the event to allow for overriding ecDetails
            var ecdOverride = new PayPalExpressCheckoutRequestDetailsOverride(invoice, payment, ecDetails);
            SettingCheckoutRequestDetails.RaiseEvent(new ObjectEventArgs<PayPalExpressCheckoutRequestDetailsOverride>(ecdOverride), this);

            // The ExpressCheckoutRequest
            var request = new SetExpressCheckoutRequestType
                    {
                        Version = Version,
                        SetExpressCheckoutRequestDetails = ecdOverride.ExpressCheckoutDetails
                    };

            // Crete the wrapper for Express Checkout
            var wrapper = new SetExpressCheckoutReq
                              {
                                  SetExpressCheckoutRequest = request
                              };

            try
            {
                var service = GetPayPalService();
                var response = service.SetExpressCheckout(wrapper);
                record.SetExpressCheckout = _responseFactory.Build(response, response.Token);
                record.Data.Token = response.Token;
                record.SetExpressCheckout.RedirectUrl = GetRedirectUrl(response.Token);
            }
            catch (Exception ex)
            {
                record.Success = false;
                record.SetExpressCheckout = _responseFactory.Build(ex);
            }

            return record;
        }
コード例 #19
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);
    }
コード例 #20
0
ファイル: PayPalService.cs プロジェクト: RemSoftDev/GeekWear
        public static PayPalResponceModel Pay(string email, CartViewModel cart, string expressCheckoutSuccessUrl, string paymentFailureUrl)
        {
            Dictionary <string, string>      config  = PayPal.Api.ConfigManager.Instance.GetProperties();
            PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(config);

            SetExpressCheckoutRequestType        setExpressCheckoutReqType = new SetExpressCheckoutRequestType();
            SetExpressCheckoutRequestDetailsType details    = new SetExpressCheckoutRequestDetailsType();
            List <PaymentDetailsType>            payDetails = new List <PaymentDetailsType>();
            PaymentDetailsType paydtl = new PaymentDetailsType();

            paydtl.PaymentAction = PaymentActionCodeType.ORDER;

            BasicAmountType shippingTotal = new BasicAmountType();

            shippingTotal.value      = cart.ShippingCost.ToString();
            shippingTotal.currencyID = CurrencyCodeType.USD;

            decimal itemsTotal = 0.0M;

            List <PaymentDetailsItemType> lineItems = new List <PaymentDetailsItemType>();

            foreach (var cartItem in cart.Items)
            {
                PaymentDetailsItemType item = new PaymentDetailsItemType();
                BasicAmountType        amt  = new BasicAmountType();
                amt.currencyID = CurrencyCodeType.USD;

                amt.value     = "50";
                item.Quantity = cartItem.Count;
                itemsTotal   += 50 * cartItem.Count;

                item.Name   = string.Format("{0} {1} Shirt", cartItem.Project.ShirtColor, cartItem.Project.SizeString);
                item.Amount = amt;

                lineItems.Add(item);
            }

            decimal orderTotal = itemsTotal + cart.ShippingCost;

            paydtl.OrderTotal         = new BasicAmountType(CurrencyCodeType.USD, Convert.ToString(orderTotal));
            paydtl.PaymentDetailsItem = lineItems;

            paydtl.ShippingTotal      = shippingTotal;
            paydtl.PaymentDetailsItem = lineItems;
            payDetails.Add(paydtl);

            details.BuyerEmail     = email;
            details.PaymentDetails = payDetails;
            details.ReturnURL      = expressCheckoutSuccessUrl;
            details.CancelURL      = paymentFailureUrl;

            setExpressCheckoutReqType.SetExpressCheckoutRequestDetails = details;
            SetExpressCheckoutReq expressCheckoutReq = new SetExpressCheckoutReq();

            expressCheckoutReq.SetExpressCheckoutRequest = setExpressCheckoutReqType;
            SetExpressCheckoutResponseType response = null;

            try
            {
                response = service.SetExpressCheckout(expressCheckoutReq);
            }
            catch (Exception ex)
            {
                return(new PayPalResponceModel
                {
                    Success = false,
                    ErrorMessage = ex.Message
                });
            }

            if (!response.Ack.ToString().Trim().ToUpper().Equals(AckCode.FAILURE.ToString()) && !response.Ack.ToString().Trim().ToUpper().Equals(AckCode.FAILUREWITHWARNING.ToString()))
            {
                var redirectUrl = string.Format("{0}_express-checkout&token={1}", config["paypalResultUrl"], response.Token);
                return(new PayPalResponceModel
                {
                    Success = true,
                    RedirectUrl = redirectUrl
                });
            }

            return(new PayPalResponceModel
            {
                Success = false,
                ErrorMessage = string.Join(". ", response.Errors.Select(x => x.LongMessage).ToList())
            });
        }
コード例 #21
0
ファイル: PaypalAPI.cs プロジェクト: appliedi/MerchantTribe
        public SetExpressCheckoutResponseType SetExpressCheckout(string paymentAmount, string returnURL, string cancelURL, PaymentActionCodeType paymentAction, CurrencyCodeType currencyCodeType, string invoiceId)
        {
            // Create the request object
            SetExpressCheckoutRequestType pp_request = new SetExpressCheckoutRequestType();

            // Create the request details object
            pp_request.SetExpressCheckoutRequestDetails = new SetExpressCheckoutRequestDetailsType();
            pp_request.SetExpressCheckoutRequestDetails.PaymentAction = paymentAction;
            pp_request.SetExpressCheckoutRequestDetails.PaymentActionSpecified = true;
            pp_request.SetExpressCheckoutRequestDetails.InvoiceID = invoiceId;
            pp_request.SetExpressCheckoutRequestDetails.OrderTotal = new BasicAmountType();

            pp_request.SetExpressCheckoutRequestDetails.OrderTotal.currencyID = currencyCodeType;
            pp_request.SetExpressCheckoutRequestDetails.OrderTotal.Value = paymentAmount;            

            pp_request.SetExpressCheckoutRequestDetails.CancelURL = cancelURL;
            pp_request.SetExpressCheckoutRequestDetails.ReturnURL = returnURL;

            return (SetExpressCheckoutResponseType)caller.Call("SetExpressCheckout", pp_request);
        }
コード例 #22
0
        public static string StartEC(ShoppingCart cart, bool boolBypassOrderReview, IDictionary <string, string> checkoutOptions)
        {
            var payPalRefund   = new PayPalAPISoapBinding();
            var payPalBinding  = new PayPalAPIAASoapBinding();
            var redirectUrl    = new StringBuilder();
            var ecOrderTotal   = new BasicAmountType();
            var request        = new SetExpressCheckoutReq();
            var requestType    = new SetExpressCheckoutRequestType();
            var requestDetails = new SetExpressCheckoutRequestDetailsType();
            var response       = new SetExpressCheckoutResponseType();
            var result         = string.Empty;
            var urlHelper      = DependencyResolver.Current.GetService <UrlHelper>();

            //Express checkout
            GetPaypalRequirements(out payPalRefund, out payPalBinding);

            ecOrderTotal.Value = Localization.CurrencyStringForGatewayWithoutExchangeRate(cart.Total(true));

            if (cart.HasRecurringComponents() && AppLogic.AppConfigBool("Recurring.UseGatewayInternalBilling"))
            {
                //Have to send extra details on the SetExpressCheckoutReq or the token will be invalid for creating a recurring profile later
                var recurringAgreement     = new BillingAgreementDetailsType();
                var recurringAgreementList = new List <BillingAgreementDetailsType>();

                recurringAgreement.BillingType = BillingCodeType.RecurringPayments;
                recurringAgreement.BillingAgreementDescription = "Recurring order created on " + System.DateTime.Now.ToShortDateString() + " from " + AppLogic.AppConfig("StoreName");
                recurringAgreementList.Add(recurringAgreement);
                requestDetails.BillingAgreementDetails = recurringAgreementList.ToArray();
            }

            request.SetExpressCheckoutRequest            = requestType;
            requestType.SetExpressCheckoutRequestDetails = requestDetails;

            ecOrderTotal.currencyID   = (CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), AppLogic.AppConfig("Localization.StoreCurrency"), true);
            requestDetails.OrderTotal = ecOrderTotal;

            if (AppLogic.AppConfigBool("PayPal.RequireConfirmedAddress"))
            {
                requestDetails.ReqConfirmShipping = "1";
            }
            else
            {
                requestDetails.ReqConfirmShipping = "0";
            }

            requestDetails.ReturnURL = string.Format("{0}{1}",
                                                     AppLogic.GetStoreHTTPLocation(
                                                         useSsl: true,
                                                         includeScriptLocation: true,
                                                         noVirtualNoSlash: true),
                                                     urlHelper.Action(
                                                         actionName: ActionNames.PayPalExpressReturn,
                                                         controllerName: ControllerNames.PayPalExpress));
            if (boolBypassOrderReview)
            {
                requestDetails.ReturnURL = string.Format("{0}?BypassOrderReview=true", requestDetails.ReturnURL);
            }

            requestDetails.CancelURL = string.Format("{0}{1}",
                                                     AppLogic.GetStoreHTTPLocation(
                                                         useSsl: true,
                                                         includeScriptLocation: true,
                                                         noVirtualNoSlash: true),
                                                     urlHelper.Action(
                                                         actionName: ActionNames.Index,
                                                         controllerName: ControllerNames.Checkout));
            requestDetails.LocaleCode    = AppLogic.AppConfig("PayPal.DefaultLocaleCode");
            requestDetails.PaymentAction = PaymentActionCodeType.Authorization;

            if (AppLogic.TransactionModeIsAuthCapture() || AppLogic.AppConfigBool("PayPal.ForceCapture") || PayPalController.GetAppropriateExpressType() == ExpressAPIType.PayPalAcceleratedBording)
            {
                requestDetails.PaymentAction = PaymentActionCodeType.Sale;
            }

            requestDetails.SolutionType           = SolutionTypeType.Sole;
            requestDetails.PaymentActionSpecified = true;
            requestType.Version = API_VER;

            if (!string.IsNullOrWhiteSpace(AppLogic.AppConfig("PayPal.Express.PageStyle")))
            {
                requestDetails.PageStyle = AppLogic.AppConfig("PayPal.Express.PageStyle").Trim();
            }

            if (!string.IsNullOrWhiteSpace(AppLogic.AppConfig("PayPal.Express.HeaderImage")))
            {
                requestDetails.cppheaderimage = AppLogic.AppConfig("PayPal.Express.HeaderImage").Trim();
            }

            if (!string.IsNullOrWhiteSpace(AppLogic.AppConfig("PayPal.Express.HeaderBackColor")))
            {
                requestDetails.cppheaderbackcolor = AppLogic.AppConfig("PayPal.Express.HeaderBackColor").Trim();
            }

            if (!string.IsNullOrWhiteSpace(AppLogic.AppConfig("PayPal.Express.HeaderBorderColor")))
            {
                requestDetails.cppheaderbordercolor = AppLogic.AppConfig("PayPal.Express.HeaderBorderColor").Trim();
            }

            if (!string.IsNullOrWhiteSpace(AppLogic.AppConfig("PayPal.Express.PayFlowColor")))
            {
                requestDetails.cpppayflowcolor = AppLogic.AppConfig("PayPal.Express.PayFlowColor").Trim();
            }

            if (checkoutOptions != null && checkoutOptions.ContainsKey("UserSelectedFundingSource") && checkoutOptions["UserSelectedFundingSource"] == "BML")
            {
                var fundingSourceDetails = new FundingSourceDetailsType();

                fundingSourceDetails.AllowPushFunding                   = "0";
                fundingSourceDetails.UserSelectedFundingSource          = UserSelectedFundingSourceType.BML;
                fundingSourceDetails.UserSelectedFundingSourceSpecified = true;
                requestDetails.FundingSourceDetails = fundingSourceDetails;
            }

            try
            {
                response = payPalBinding.SetExpressCheckout(request);

                if (response.Ack.ToString().StartsWith("success", StringComparison.InvariantCultureIgnoreCase))
                {
                    result = AppLogic.ro_OK;
                }
                else
                {
                    if (response.Errors != null)
                    {
                        bool first = true;
                        for (int ix = 0; ix < response.Errors.Length; ix++)
                        {
                            if (!first)
                            {
                                result += ", ";
                            }
                            result += "Error: [" + response.Errors[ix].ErrorCode + "] " + response.Errors[ix].LongMessage;
                            first   = false;
                        }
                    }
                }
            }
            catch (Exception)
            {
                result = "Failed to start PayPal Express Checkout! Please try another payment method.";
            }

            if (result == AppLogic.ro_OK)
            {
                var useIntegratedCheckout = AppLogic.AppConfigBool("PayPal.Express.UseIntegratedCheckout");

                if (AppLogic.AppConfigBool("UseLiveTransactions") == true)
                {
                    redirectUrl.Append(useIntegratedCheckout
                                                ? AppLogic.AppConfig("PayPal.Express.IntegratedCheckout.LiveURL")
                                                : AppLogic.AppConfig("PayPal.Express.LiveURL"));
                }
                else
                {
                    redirectUrl.Append(useIntegratedCheckout
                                                ? AppLogic.AppConfig("PayPal.Express.IntegratedCheckout.SandboxURL")
                                                : AppLogic.AppConfig("PayPal.Express.SandboxURL"));
                }

                redirectUrl.Append(useIntegratedCheckout
                                        ? "?token="
                                        : "?cmd=_express-checkout&token=");

                redirectUrl.Append(response.Token);

                if (boolBypassOrderReview)
                {
                    redirectUrl.Append("&useraction=commit");
                }

                // Set active payment method to PayPalExpress
                DB.ExecuteSQL(string.Format("UPDATE Address SET PaymentMethodLastUsed={0} WHERE AddressID={1}",
                                            DB.SQuote(AppLogic.ro_PMPayPalExpress),
                                            cart.ThisCustomer.PrimaryBillingAddressID));

                SetECFaultRedirect(cart.ThisCustomer, redirectUrl.ToString());
            }
            else
            {
                var error = new ErrorMessage(HttpUtility.HtmlEncode(result));
                redirectUrl.Append(urlHelper.BuildCheckoutLink(error.MessageId));
            }

            return(redirectUrl.ToString());
        }
コード例 #23
0
        /// <summary>
        /// Performs the setup for an express checkout.
        /// </summary>
        /// <param name="invoice">
        /// The <see cref="IInvoice"/>.
        /// </param>
        /// <param name="payment">
        /// The <see cref="IPayment"/>
        /// </param>
        /// <param name="returnUrl">
        /// The return URL.
        /// </param>
        /// <param name="cancelUrl">
        /// The cancel URL.
        /// </param>
        /// <returns>
        /// The <see cref="ExpressCheckoutResponse"/>.
        /// </returns>
        protected virtual PayPalExpressTransactionRecord SetExpressCheckout(IInvoice invoice, IPayment payment, string returnUrl, string cancelUrl)
        {
            var record = new PayPalExpressTransactionRecord
            {
                Success = true,
                Data    = { Authorized = false, CurrencyCode = invoice.CurrencyCode }
            };

            var factory = new PayPalPaymentDetailsTypeFactory(new PayPalFactorySettings {
                WebsiteUrl = _websiteUrl
            });
            var paymentDetailsType = factory.Build(invoice, PaymentActionCodeType.ORDER);

            // The API requires this be in a list
            var paymentDetailsList = new List <PaymentDetailsType>()
            {
                paymentDetailsType
            };

            // ExpressCheckout details
            var ecDetails = new SetExpressCheckoutRequestDetailsType()
            {
                ReturnURL       = returnUrl,
                CancelURL       = cancelUrl,
                PaymentDetails  = paymentDetailsList,
                AddressOverride = "1"
            };

            // Trigger the event to allow for overriding ecDetails
            var ecdOverride = new PayPalExpressCheckoutRequestDetailsOverride(invoice, payment, ecDetails);

            SettingCheckoutRequestDetails.RaiseEvent(new ObjectEventArgs <PayPalExpressCheckoutRequestDetailsOverride>(ecdOverride), this);

            // The ExpressCheckoutRequest
            var request = new SetExpressCheckoutRequestType
            {
                Version = Version,
                SetExpressCheckoutRequestDetails = ecdOverride.ExpressCheckoutDetails
            };

            // Crete the wrapper for Express Checkout
            var wrapper = new SetExpressCheckoutReq
            {
                SetExpressCheckoutRequest = request
            };

            try
            {
                var service  = GetPayPalService();
                var response = service.SetExpressCheckout(wrapper);

                record.SetExpressCheckout = _responseFactory.Build(response, response.Token);
                if (record.SetExpressCheckout.Success())
                {
                    record.Data.Token = response.Token;
                    record.SetExpressCheckout.RedirectUrl = GetRedirectUrl(response.Token);
                }
                else
                {
                    foreach (var et in record.SetExpressCheckout.ErrorTypes)
                    {
                        var code = et.ErrorCode;
                        var sm   = et.ShortMessage;
                        var lm   = et.LongMessage;
                        MultiLogHelper.Warn <PayPalExpressCheckoutService>(string.Format("{0} {1} {2}", code, lm, sm));
                    }

                    record.Success = false;
                }
            }
            catch (Exception ex)
            {
                record.Success            = false;
                record.SetExpressCheckout = _responseFactory.Build(ex);
            }

            return(record);
        }
コード例 #24
0
ファイル: PaypalAPI.cs プロジェクト: wncoder/core
        public SetExpressCheckoutResponseType SetExpressCheckout(PaymentDetailsItemType[] itemsDetails,
                                                                 string itemsTotal, string taxTotal, string shippingTotal,
                                                                 string orderTotal, string returnURL, string cancelURL, PaymentActionCodeType paymentAction,
                                                                 CurrencyCodeType currencyCodeType, SolutionTypeType solutionType, string name,
                                                                 string countryISOCode, string street1, string street2, string city, string region, string postalCode,
                                                                 string phone, string invoiceId, bool isNonShipping)
        {
            // Create the request object
            var pp_request = new SetExpressCheckoutRequestType
            {
                SetExpressCheckoutRequestDetails = new SetExpressCheckoutRequestDetailsType
                {
                    CancelURL             = cancelURL,
                    ReturnURL             = returnURL,
                    AddressOverride       = "1",
                    NoShipping            = isNonShipping ? "1" : "0",
                    SolutionType          = solutionType,
                    SolutionTypeSpecified = true
                }
            };

            // Create the request details object

            //pp_request.SetExpressCheckoutRequestDetails.ReqBillingAddress = (isNonShipping ? "1" : "0");

            var paymentDetails = new PaymentDetailsType
            {
                InvoiceID              = invoiceId,
                PaymentAction          = paymentAction,
                PaymentActionSpecified = true,
                PaymentDetailsItem     = itemsDetails,
                ItemTotal              = new BasicAmountType
                {
                    currencyID = currencyCodeType,
                    Value      = itemsTotal
                },
                TaxTotal = new BasicAmountType
                {
                    currencyID = currencyCodeType,
                    Value      = taxTotal
                },
                ShippingTotal = new BasicAmountType
                {
                    currencyID = currencyCodeType,
                    Value      = shippingTotal
                },
                OrderTotal = new BasicAmountType
                {
                    currencyID = currencyCodeType,
                    Value      = orderTotal
                },
                ShipToAddress = new AddressType
                {
                    AddressStatusSpecified = false,
                    AddressOwnerSpecified  = false,
                    Street1          = street1,
                    Street2          = street2,
                    CityName         = city,
                    StateOrProvince  = region,
                    PostalCode       = postalCode,
                    CountrySpecified = true,
                    Country          = GetCountryCode(countryISOCode),
                    Phone            = phone,
                    Name             = name
                }
            };

            pp_request.SetExpressCheckoutRequestDetails.PaymentDetails = new[] { paymentDetails };

            return((SetExpressCheckoutResponseType)caller.Call("SetExpressCheckout", pp_request));
        }
コード例 #25
0
        public virtual async Task <PaymentRequestResult> RequestForPaymentUrl(string callbackUrl, TblInvoices invoice)
        {
            var settings = await _settingService.LoadSettingAsync <PayPalSettingsModel>();

            var currentCurrency = DependencyResolver.Current.GetService <IWorkContext>().CurrentCurrency;
            var amount          = invoice.ComputeInvoiceTotalAmount();


            var currencyCode = CurrencyCodeType.USD;

            if (currentCurrency.IsoCode.ToLower().Trim() == "eur")
            {
                currencyCode = CurrencyCodeType.EUR;
            }
            var buyerEmail  = "";
            var paymentDesc = string.Format(_localizationService.GetResource("Plugin.PaymentMethod.PayPal.InvoiceNumber"), invoice.Id.ToString("N").ToUpper());

            if (invoice.User != null)
            {
                buyerEmail = invoice.User.Email;
            }

            if (string.IsNullOrWhiteSpace(settings.APIUserName) ||
                string.IsNullOrWhiteSpace(settings.APIPassword) ||
                string.IsNullOrWhiteSpace(settings.APISignature))
            {
                return(new PaymentRequestResult()
                {
                    ErrorMessage = _localizationService.GetResource("Plugin.PaymentMethod.PayPal.InvalidConfig")
                });
            }

            var result = new PaymentRequestResult();
            await Task.Run(() =>
            {
                try
                {
                    var ecDetails = new SetExpressCheckoutRequestDetailsType()
                    {
                        ReturnURL          = AppendQueryStringToUrl(callbackUrl, "Status", "OK"),
                        CancelURL          = AppendQueryStringToUrl(callbackUrl, "Status", "NOK"),
                        LocaleCode         = "US",
                        BuyerEmail         = buyerEmail,
                        InvoiceID          = invoice.Id.ToString(),
                        OrderDescription   = paymentDesc,
                        ShippingMethod     = ShippingServiceCodeType.DOWNLOAD,
                        PaymentAction      = PaymentActionCodeType.SALE,
                        OrderTotal         = new BasicAmountType(currencyCode, amount.ToString()),
                        NoShipping         = "1", //PayPal does not display shipping address fields and removes shipping information from the transaction.
                        ReqConfirmShipping = "0", //do not require the buyer's shipping address be a confirmed address.
                        AddressOverride    = "0", //The PayPal pages should not display the shipping address.
                        cppHeaderImage     = settings.PayPalHeaderImageUrl,
                        BrandName          = settings.PayPalBrandName,
                    };

                    var request = new SetExpressCheckoutRequestType(ecDetails);
                    var wrapper = new SetExpressCheckoutReq {
                        SetExpressCheckoutRequest = request
                    };
                    var service = new PayPalAPIInterfaceServiceService(GetPayPalConfig());
                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                    var setEcResponse = service.SetExpressCheckout(wrapper);

                    if (setEcResponse.Ack == AckCodeType.SUCCESS)
                    {
                        result.RedirectUrl = settings.PaymentPageUrl + "_express-checkout&token=" +
                                             setEcResponse.Token;
                        result.Token     = setEcResponse.Token;
                        result.IsSuccess = true;
                    }
                    else
                    {
                        foreach (var error in setEcResponse.Errors)
                        {
                            result.ErrorMessage +=
                                $"[{error.SeverityCode}] {error.ErrorCode} : {error.LongMessage} </br>";
                        }
                    }
                }
                catch
                {
                    result.ErrorMessage = _localizationService.GetResource("Plugin.PaymentMethod.PayPal.ServiceUnavailable");
                }
            });

            return(result);
        }
コード例 #26
0
        /// <summary>
        /// Performs the setup for an express checkout.
        /// </summary>
        /// <param name="invoice">
        /// The <see cref="IInvoice"/>.
        /// </param>
        /// <param name="payment">
        /// The <see cref="IPayment"/>
        /// </param>
        /// <param name="returnUrl">
        /// The return URL.
        /// </param>
        /// <param name="cancelUrl">
        /// The cancel URL.
        /// </param>
        /// <returns>
        /// The <see cref="ExpressCheckoutResponse"/>.
        /// </returns>
        protected virtual PayPalExpressTransactionRecord SetExpressCheckout(IInvoice invoice, IPayment payment, string returnUrl, string cancelUrl)
        {
            var record = new PayPalExpressTransactionRecord
            {
                Success = true,
                Data    = { Authorized = false, CurrencyCode = invoice.CurrencyCode }
            };

            var factory = new PayPalPaymentDetailsTypeFactory(new PayPalFactorySettings {
                WebsiteUrl = _websiteUrl
            });
            var paymentDetailsType = factory.Build(invoice, PaymentActionCodeType.ORDER);

            // The API requires this be in a list
            var paymentDetailsList = new List <PaymentDetailsType>()
            {
                paymentDetailsType
            };

            // ExpressCheckout details
            //// We do not want the customer to be able to reset their shipping address at PayPal
            //// due to the fact that it could affect shipping charges and in some cases tax rates.
            //// This is the AddressOverride = "0" - NOT WORKING!
            var ecDetails = new SetExpressCheckoutRequestDetailsType()
            {
                ReturnURL       = returnUrl,
                CancelURL       = cancelUrl,
                PaymentDetails  = paymentDetailsList,
                AddressOverride = "0"
            };

            // Trigger the event to allow for overriding ecDetails
            var ecdOverride = new PayPalExpressCheckoutRequestDetailsOverride(invoice, payment, ecDetails);

            SettingCheckoutRequestDetails.RaiseEvent(new ObjectEventArgs <PayPalExpressCheckoutRequestDetailsOverride>(ecdOverride), this);

            // The ExpressCheckoutRequest
            var request = new SetExpressCheckoutRequestType
            {
                Version = Version,
                SetExpressCheckoutRequestDetails = ecdOverride.ExpressCheckoutDetails
            };

            // Crete the wrapper for Express Checkout
            var wrapper = new SetExpressCheckoutReq
            {
                SetExpressCheckoutRequest = request
            };

            try
            {
                var service  = GetPayPalService();
                var response = service.SetExpressCheckout(wrapper);
                record.SetExpressCheckout             = _responseFactory.Build(response, response.Token);
                record.Data.Token                     = response.Token;
                record.SetExpressCheckout.RedirectUrl = GetRedirectUrl(response.Token);
            }
            catch (Exception ex)
            {
                record.Success            = false;
                record.SetExpressCheckout = _responseFactory.Build(ex);
            }

            return(record);
        }