Beispiel #1
0
        /// <summary>
        /// Builds the <see cref="PaymentDetailsItemType"/>.
        /// </summary>
        /// <param name="invoice">
        /// The invoice.
        /// </param>
        /// <param name="actionCode">
        /// The <see cref="PaymentActionCodeType"/>.
        /// </param>
        /// <returns>
        /// The <see cref="PaymentDetailsType"/>.
        /// </returns>
        public PaymentDetailsType Build(IInvoice invoice, PaymentActionCodeType actionCode)
        {
            // Get the decimal configuration for the current currency
            var currencyCodeType   = PayPalApiHelper.GetPayPalCurrencyCode(invoice.CurrencyCode);
            var basicAmountFactory = new PayPalBasicAmountTypeFactory(currencyCodeType);

            // Get the tax total
            var itemTotal     = basicAmountFactory.Build(invoice.TotalItemPrice());
            var shippingTotal = basicAmountFactory.Build(invoice.TotalShipping());
            var taxTotal      = basicAmountFactory.Build(invoice.TotalTax());
            var invoiceTotal  = basicAmountFactory.Build(invoice.Total);

            var items = BuildPaymentDetailsItemTypes(invoice.ProductLineItems(), basicAmountFactory);

            var paymentDetails = new PaymentDetailsType
            {
                PaymentDetailsItem = items.ToList(),
                ItemTotal          = itemTotal,
                TaxTotal           = taxTotal,
                ShippingTotal      = shippingTotal,
                OrderTotal         = invoiceTotal,
                PaymentAction      = actionCode,
                InvoiceID          = invoice.PrefixedInvoiceNumber()
            };

            // ShipToAddress
            if (invoice.ShippingLineItems().Any())
            {
                var addressTypeFactory = new PayPalAddressTypeFactory();
                paymentDetails.ShipToAddress = addressTypeFactory.Build(invoice.GetShippingAddresses().FirstOrDefault());
            }

            return(paymentDetails);
        }
Beispiel #2
0
        public DoExpressCheckoutPaymentResponseType DoExpressCheckoutPayment(string token, string payerID,
                                                                             string paymentAmount, PaymentActionCodeType paymentAction, CurrencyCodeType currencyCodeType,
                                                                             string invoiceId)
        {
            // Create the request object
            var pp_request = new DoExpressCheckoutPaymentRequestType
            {
                DoExpressCheckoutPaymentRequestDetails = new DoExpressCheckoutPaymentRequestDetailsType
                {
                    Token   = token,
                    PayerID = payerID
                }
            };

            // Create the request details object

            var paymentDetails = new PaymentDetailsType
            {
                InvoiceID              = invoiceId,
                PaymentAction          = paymentAction,
                PaymentActionSpecified = true,
                OrderTotal             = new BasicAmountType
                {
                    currencyID = currencyCodeType,
                    Value      = paymentAmount
                }
            };

            paymentDetails.ButtonSource = "HotcakesCommerce_Cart_EC_US";

            pp_request.DoExpressCheckoutPaymentRequestDetails.PaymentDetails = new[] { paymentDetails };
            return((DoExpressCheckoutPaymentResponseType)caller.Call("DoExpressCheckoutPayment", pp_request));
        }
Beispiel #3
0
        private void PopulatePaymentDetails(SetExpressCheckoutRequestDetailsType ecDetails)
        {
            var paymentInfo = new PaymentDetailsType();
            var total       = 0.0;
            var currency    = CurrencyCodeType.GBP;
            var address     = new AddressType
            {
                Name            = Checkout.BillingInfo.FirstName + " " + Checkout.BillingInfo.SurName,
                Street1         = Checkout.BillingInfo.FirmName + " " + Checkout.BillingInfo.BuildingName + " " + Checkout.BillingInfo.StreetName,
                CityName        = Checkout.BillingInfo.City,
                StateOrProvince = Checkout.BillingInfo.County,
                PostalCode      = Checkout.BillingInfo.PostCode
            };

            paymentInfo.ShipToAddress = address;

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

            var tax = total * 20 / 100;

            paymentInfo.ItemTotal  = new BasicAmountType(currency, total.ToString());
            paymentInfo.OrderTotal = new BasicAmountType(currency, (total + tax).ToString());
            paymentInfo.TaxTotal   = new BasicAmountType(currency, (total * 20 / 100).ToString());
            ecDetails.PaymentDetails.Add(paymentInfo);
        }
        public DoExpressCheckoutPaymentReq GetDoExpressCheckoutPaymentRequest(ProcessPaymentRequest processPaymentRequest)
        {
            // populate payment details
            var currencyCodeType = _payPalCurrencyCodeParser.GetCurrencyCodeType(_workContext.WorkingCurrency);

            var paymentDetails = new PaymentDetailsType
            {
                OrderTotal   = processPaymentRequest.OrderTotal.GetBasicAmountType(currencyCodeType),
                Custom       = processPaymentRequest.OrderGuid.ToString(),
                ButtonSource = PayPalHelper.BnCode,
                InvoiceID    = processPaymentRequest.OrderGuid.ToString()
            };

            // build the request
            return(new DoExpressCheckoutPaymentReq
            {
                DoExpressCheckoutPaymentRequest = new DoExpressCheckoutPaymentRequestType
                {
                    Version = GetVersion(),
                    DoExpressCheckoutPaymentRequestDetails = new DoExpressCheckoutPaymentRequestDetailsType
                    {
                        Token = processPaymentRequest.CustomValues["PaypalToken"].ToString(),
                        PayerID = processPaymentRequest.CustomValues["PaypalPayerId"].ToString(),
                        PaymentAction = _payPalExpressCheckoutPaymentSettings.PaymentAction,
                        PaymentActionSpecified = true,
                        ButtonSource = PayPalHelper.BnCode,
                        PaymentDetails = new[] { paymentDetails }
                    }
                }
            });
        }
Beispiel #5
0
        public DoExpressCheckoutPaymentReq GetDoExpressCheckoutRequest(CartModel cart)
        {
            // populate payment details
            var paymentDetails = new PaymentDetailsType
            {
                OrderTotal         = cart.TotalToPay.GetAmountType(),
                ShippingTotal      = cart.ShippingTotal.GetAmountType(),
                ItemTotal          = _payPalOrderService.GetItemTotal(cart),
                TaxTotal           = cart.ItemTax.GetAmountType(),
                Custom             = cart.CartGuid.ToString(),
                ButtonSource       = "Thought_Cart_MrCMS",
                InvoiceID          = cart.CartGuid.ToString(),
                PaymentDetailsItem = _payPalOrderService.GetPaymentDetailsItems(cart)
            };

            // build the request
            return(new DoExpressCheckoutPaymentReq
            {
                DoExpressCheckoutPaymentRequest = new DoExpressCheckoutPaymentRequestType
                {
                    DoExpressCheckoutPaymentRequestDetails = new DoExpressCheckoutPaymentRequestDetailsType
                    {
                        Token = cart.PayPalExpressToken,
                        PayerID = cart.PayPalExpressPayerId,
                        PaymentAction = _payPalExpressCheckoutSettings.PaymentAction,
                        PaymentDetails = new List <PaymentDetailsType> {
                            paymentDetails
                        }
                    }
                }
            });
        }
Beispiel #6
0
        private void SetShippingAddress(GetExpressCheckoutDetailsResponseDetailsType details)
        {
            PaymentDetailsType paymentDetails = details.PaymentDetails.FirstOrDefault();

            if (paymentDetails != null)
            {
                _cartManager.SetShippingAddress(paymentDetails.ShipToAddress.GetAddress());
            }
        }
Beispiel #7
0
        private PaymentDetailsType GetPaypalPaymentDetail(string currency, PaymentActionCodeType paymentAction, PaymentIn payment)
        {
            var paymentDetails = new PaymentDetailsType {
                PaymentAction = paymentAction
            };

            paymentDetails.OrderTotal = new BasicAmountType(GetPaypalCurrency(currency), FormatMoney(payment.Sum));

            return(paymentDetails);
        }
        private PaymentDetailsType GetPaymentDetails(IInvoice invoice)
        {
            decimal itemTotal          = 0;
            decimal taxTotal           = 0;
            decimal shippingTotal      = 0;
            var     paymentDetailItems = new List <PaymentDetailsItemType>();

            foreach (var item in invoice.Items)
            {
                switch (item.LineItemType)
                {
                case LineItemType.Tax:
                    taxTotal = item.TotalPrice;
                    break;

                case LineItemType.Shipping:
                    shippingTotal = item.TotalPrice;
                    break;

                case LineItemType.Product:
                    var paymentItem = new PaymentDetailsItemType
                    {
                        Name     = item.Name,
                        ItemURL  = GetWebsiteUrl() + "/all-products/" + item.Sku,
                        Amount   = new BasicAmountType(CurrencyCodeType.USD, item.Price.ToString("0.00")),
                        Quantity = item.Quantity,
                    };
                    paymentDetailItems.Add(paymentItem);
                    itemTotal += item.TotalPrice;
                    break;

                default:
                    throw new Exception("Unsupported item with type: " + item.LineItemType);
                }
            }

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

            return(paymentDetails);
        }
        /// <summary>
        /// Do paypal express checkout
        /// </summary>
        /// <param name="Token">Paypal express checkout token</param>
        /// <param name="PayerID">Paypal payer identifier</param>
        /// <param name="OrderTotal">Order total</param>
        /// <param name="processPaymentResult">Process payment result</param>
        public void DoExpressCheckout(string Token, string PayerID, decimal OrderTotal, ProcessPaymentResult processPaymentResult)
        {
            InitSettings();
            TransactMode transactionMode = GetCurrentTransactionMode();

            DoExpressCheckoutPaymentReq         req     = new DoExpressCheckoutPaymentReq();
            DoExpressCheckoutPaymentRequestType request = new DoExpressCheckoutPaymentRequestType();

            req.DoExpressCheckoutPaymentRequest = request;
            request.Version = this.APIVersion;
            DoExpressCheckoutPaymentRequestDetailsType details = new DoExpressCheckoutPaymentRequestDetailsType();

            request.DoExpressCheckoutPaymentRequestDetails = details;
            PaymentDetailsType paymentDetails = new PaymentDetailsType();

            details.PaymentDetails = paymentDetails;
            if (transactionMode == TransactMode.Authorize)
            {
                details.PaymentAction = PaymentActionCodeType.Authorization;
            }
            else
            {
                details.PaymentAction = PaymentActionCodeType.Sale;
            }
            details.Token                        = Token;
            details.PayerID                      = PayerID;
            paymentDetails.OrderTotal            = new BasicAmountType();
            paymentDetails.OrderTotal.Value      = OrderTotal.ToString("N", new CultureInfo("en-us"));
            paymentDetails.OrderTotal.currencyID = PaypalHelper.GetPaypalCurrency(CurrencyManager.PrimaryStoreCurrency);
            paymentDetails.ButtonSource          = "nopCommerceCart";

            DoExpressCheckoutPaymentResponseType response = service2.DoExpressCheckoutPayment(req);
            string error;

            if (!PaypalHelper.CheckSuccess(response, out error))
            {
                throw new NopException(error);
            }

            processPaymentResult.AuthorizationTransactionID     = response.DoExpressCheckoutPaymentResponseDetails.PaymentInfo.TransactionID;
            processPaymentResult.AuthorizationTransactionResult = response.Ack.ToString();
            //processPaymentResult.AuthorizationDate = response.Timestamp;
            //processPaymentResult.AuthorizationDate = DateTime.Now;

            if (transactionMode == TransactMode.Authorize)
            {
                processPaymentResult.PaymentStatus = PaymentStatusEnum.Authorized;
            }
            else
            {
                processPaymentResult.PaymentStatus = PaymentStatusEnum.Paid;
            }
        }
        protected void btnPay_Click(object sender, EventArgs e)
        {
            if (radPaypal.Checked)
            {
                PayPalAPIAAInterfaceClient paypalAAInt = new PayPalAPIAAInterfaceClient();
                string hosting = ConfigurationManager.AppSettings["HostingPrefix"];

                CustomSecurityHeaderType type = new CustomSecurityHeaderType();
                type.Credentials = new UserIdPasswordType()
                {
                    Username  = ConfigurationManager.AppSettings["PP_APIUsername"],
                    Password  = ConfigurationManager.AppSettings["PP_APIPassword"],
                    Signature = ConfigurationManager.AppSettings["PP_APISignature"]
                };

                SetExpressCheckoutRequestDetailsType sdt = new SetExpressCheckoutRequestDetailsType();
                sdt.NoShipping = "1";
                PaymentDetailsType pdt = new PaymentDetailsType()
                {
                    OrderDescription = "Payment Details Sushant",
                    OrderTotal       = new BasicAmountType()
                    {
                        currencyID = CurrencyCodeType.USD,
                        Value      = "100.00"
                    }
                };

                sdt.PaymentDetails = new PaymentDetailsType[] { pdt };
                sdt.CancelURL      = hosting + "Default.aspx";
                sdt.ReturnURL      = hosting + "ExpressCheckoutSuccess.aspx";

                SetExpressCheckoutReq req = new SetExpressCheckoutReq()
                {
                    SetExpressCheckoutRequest = new SetExpressCheckoutRequestType()
                    {
                        SetExpressCheckoutRequestDetails = sdt,
                        Version = "60.0"
                    }
                };

                var resp = paypalAAInt.SetExpressCheckout(ref type, req);
                if (resp.Errors != null && resp.Errors.Length > 0)
                {
                    // errors occured
                    throw new Exception("Exception(s) occured when calling PayPal. First exception: " +
                                        resp.Errors[0].LongMessage);
                }

                Response.Redirect(string.Format("{0}?cmd=_express-checkout&token={1}",
                                                ConfigurationManager.AppSettings["PayPalSubmitUrl"], resp.Token));
            }
        }
        protected void btnPay_Click(object sender, EventArgs e)
        {
            if (radPaypal.Checked)
            {
                PayPalAPIAAInterfaceClient paypalAAInt = new PayPalAPIAAInterfaceClient();
                string hosting = ConfigurationManager.AppSettings["HostingPrefix"];

                CustomSecurityHeaderType type = new CustomSecurityHeaderType();
                type.Credentials = new UserIdPasswordType()
                {
                    Username = ConfigurationManager.AppSettings["PP_APIUsername"],
                    Password = ConfigurationManager.AppSettings["PP_APIPassword"],
                    Signature = ConfigurationManager.AppSettings["PP_APISignature"]
                };

                SetExpressCheckoutRequestDetailsType sdt = new SetExpressCheckoutRequestDetailsType();
                sdt.NoShipping = "1";
                PaymentDetailsType pdt = new PaymentDetailsType()
                {
                    OrderDescription = "Payment Details Sushant",
                    OrderTotal = new BasicAmountType()
                    {
                        currencyID = CurrencyCodeType.USD,
                        Value = "100.00"
                    }
                };

                sdt.PaymentDetails = new PaymentDetailsType[] { pdt };
                sdt.CancelURL = hosting + "Default.aspx";
                sdt.ReturnURL = hosting + "ExpressCheckoutSuccess.aspx";

                SetExpressCheckoutReq req = new SetExpressCheckoutReq()
                {
                    SetExpressCheckoutRequest = new SetExpressCheckoutRequestType()
                    {
                        SetExpressCheckoutRequestDetails = sdt,
                        Version = "60.0"
                    }
                };

                var resp = paypalAAInt.SetExpressCheckout(ref type, req);
                if (resp.Errors != null && resp.Errors.Length > 0)
                {
                    // errors occured
                    throw new Exception("Exception(s) occured when calling PayPal. First exception: " +
                        resp.Errors[0].LongMessage);
                }

                Response.Redirect(string.Format("{0}?cmd=_express-checkout&token={1}",
                    ConfigurationManager.AppSettings["PayPalSubmitUrl"], resp.Token));
            }
        }
        private void SetShippingAddress(GetExpressCheckoutDetailsResponseDetailsType details)
        {
            PaymentDetailsType paymentDetails = details.PaymentDetails.FirstOrDefault();

            if (paymentDetails != null)
            {
                var address = paymentDetails.ShipToAddress.GetAddress();
                if (string.IsNullOrWhiteSpace(address.PhoneNumber))
                {
                    address.PhoneNumber = details.ContactPhone;
                }

                _cartManager.SetShippingAddress(address);
            }
        }
Beispiel #13
0
        public SetExpressCheckoutResponseType SetExpressCheckout(PaymentDetailsItemType[] itemsDetails,
                                                                 string itemsTotal, string taxTotal, string orderTotal,
                                                                 string returnURL, string cancelURL, PaymentActionCodeType paymentAction, CurrencyCodeType currencyCodeType,
                                                                 SolutionTypeType solutionType, string invoiceId, bool isNonShipping)
        {
            // Create the request object
            var pp_request = new SetExpressCheckoutRequestType
            {
                // Create the request details object
                SetExpressCheckoutRequestDetails = new SetExpressCheckoutRequestDetailsType
                {
                    CancelURL             = cancelURL,
                    ReturnURL             = returnURL,
                    NoShipping            = isNonShipping ? "1" : "0",
                    SolutionType          = solutionType,
                    SolutionTypeSpecified = true
                }
            };

            //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
                },
                OrderTotal = new BasicAmountType
                {
                    currencyID = currencyCodeType,
                    Value      = orderTotal
                }
            };

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

            return((SetExpressCheckoutResponseType)caller.Call("SetExpressCheckout", pp_request));
        }
Beispiel #14
0
        private void AddProductsToDetails(PaymentDetailsType detailsType)
        {
            _model.ProductItems.ForEach(p =>
            {
                var assignmentDetails = new PaymentDetailsItemType
                {
                    Name         = p.Title,
                    Description  = p.Description,
                    Amount       = new BasicAmountType(_model.CurrencyCodeType, p.Amount.ToString()),
                    Quantity     = 1,
                    ItemCategory = ItemCategoryType.DIGITAL
                };

                detailsType.PaymentDetailsItem.Add(assignmentDetails);
            });
        }
Beispiel #15
0
        public DoExpressCheckoutPaymentResponseType DoExpressCheckoutPayment(ProcessPaymentRequest processPaymentRequest)
        {
            var result   = new DoExpressCheckoutPaymentResponseType();
            var settings = CommonServices.Settings.LoadSetting <PayPalExpressPaymentSettings>(processPaymentRequest.StoreId);

            // populate payment details
            var paymentDetails = new PaymentDetailsType
            {
                OrderTotal = new BasicAmountType
                {
                    Value      = Math.Round(processPaymentRequest.OrderTotal, 2).ToString("N", new CultureInfo("en-us")),
                    currencyID = PayPalHelper.GetPaypalCurrency(_currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId))
                },
                Custom       = processPaymentRequest.OrderGuid.ToString(),
                ButtonSource = SmartStoreVersion.CurrentFullVersion
            };

            // build the request
            var req = new DoExpressCheckoutPaymentReq
            {
                DoExpressCheckoutPaymentRequest = new DoExpressCheckoutPaymentRequestType
                {
                    Version = PayPalHelper.GetApiVersion(),
                    DoExpressCheckoutPaymentRequestDetails = new DoExpressCheckoutPaymentRequestDetailsType
                    {
                        Token                  = processPaymentRequest.PaypalToken,
                        PayerID                = processPaymentRequest.PaypalPayerId,
                        PaymentAction          = PayPalHelper.GetPaymentAction(settings),
                        PaymentActionSpecified = true,
                        PaymentDetails         = new PaymentDetailsType[]
                        {
                            paymentDetails
                        }
                    }
                }
            };

            //execute request
            using (var service = new PayPalAPIAASoapBinding())
            {
                service.Url = PayPalHelper.GetPaypalServiceUrl(settings);
                service.RequesterCredentials = PayPalHelper.GetPaypalApiCredentials(settings);
                result = service.DoExpressCheckoutPayment(req);
            }
            return(result);
        }
Beispiel #16
0
        public DoExpressCheckoutPaymentResponseType DoExpressCheckoutPayment(ProcessPaymentRequest processPaymentRequest)
        {
            var result   = new DoExpressCheckoutPaymentResponseType();
            var store    = Services.StoreService.GetStoreById(processPaymentRequest.StoreId);
            var settings = Services.Settings.LoadSetting <PayPalExpressPaymentSettings>(processPaymentRequest.StoreId);

            // populate payment details
            var paymentDetails = new PaymentDetailsType
            {
                OrderTotal = new BasicAmountType
                {
                    Value      = Math.Round(processPaymentRequest.OrderTotal, 2).ToString("N", new CultureInfo("en-us")),
                    currencyID = GetApiCurrency(store.PrimaryStoreCurrency)
                },
                Custom       = processPaymentRequest.OrderGuid.ToString(),
                ButtonSource = SmartStoreVersion.CurrentFullVersion
            };

            // build the request
            var req = new DoExpressCheckoutPaymentReq
            {
                DoExpressCheckoutPaymentRequest = new DoExpressCheckoutPaymentRequestType
                {
                    Version = ApiVersion,
                    DoExpressCheckoutPaymentRequestDetails = new DoExpressCheckoutPaymentRequestDetailsType
                    {
                        Token                  = processPaymentRequest.PaypalToken,
                        PayerID                = processPaymentRequest.PaypalPayerId,
                        PaymentAction          = GetPaymentAction(settings),
                        PaymentActionSpecified = true,
                        PaymentDetails         = new PaymentDetailsType[]
                        {
                            paymentDetails
                        }
                    }
                }
            };

            //execute request
            using (var service = GetApiAaService(settings))
            {
                result = service.DoExpressCheckoutPayment(req);
            }
            return(result);
        }
Beispiel #17
0
        public List <PaymentDetailsType> GetPaymentDetails(CartModel cart)
        {
            var paymentDetailsType = new PaymentDetailsType
            {
                ItemTotal          = GetItemTotal(cart),
                PaymentDetailsItem = GetPaymentDetailsItems(cart),
                PaymentAction      = _payPalExpressCheckoutSettings.PaymentAction,
                OrderTotal         = cart.GetCartTotalForPayPal().GetAmountType(),
                TaxTotal           = cart.GetCartTaxForPayPal().GetAmountType(),
                ShippingTotal      = cart.GetShippingTotalForPayPal().GetAmountType()
            };


            return(new List <PaymentDetailsType>
            {
                paymentDetailsType
            });
        }
Beispiel #18
0
        public string SetExpressCheckout(PayPalDGModel model)
        {
            if (model == null)
            {
                throw new ArgumentNullException("model");
            }

            _model.AssertRequiredParameters();
            _model = model;

            var paymentDetails = new PaymentDetailsType();

            AddProductsToDetails(paymentDetails);

            paymentDetails.PaymentAction = PaymentActionCodeType.SALE;
            paymentDetails.ItemTotal     = new BasicAmountType(_model.CurrencyCodeType, _model.GetItemTotalAmount().ToString());
            paymentDetails.OrderTotal    = new BasicAmountType(_model.CurrencyCodeType, _model.GetOrderTotalAmount().ToString());
            paymentDetails.TaxTotal      = new BasicAmountType(_model.CurrencyCodeType, _model.TaxTotalAmount.ToString());

            var ecDetails = CheckoutRequestDetails();

            ecDetails.PaymentDetails.Add(paymentDetails);

            if (_model.SupportCreditCardPayment)
            {
                ecDetails.SolutionType = SolutionTypeType.SOLE;
            }

            var request = new SetExpressCheckoutRequestType {
                SetExpressCheckoutRequestDetails = ecDetails
            };
            var checkoutReq = new SetExpressCheckoutReq {
                SetExpressCheckoutRequest = request
            };

            var service       = new PayPalAPIInterfaceServiceService();
            var setECResponse = service.SetExpressCheckout(checkoutReq);

            var ack = setECResponse.Ack.HasValue ? setECResponse.Ack.Value : AckCodeType.FAILURE;

            AssertCheckoutResponse(ack, setECResponse.Errors);

            return(setECResponse.Token);
        }
        public DoExpressCheckoutPaymentReq Do()
        {
            var paymentDetail = new PaymentDetailsType();

            paymentDetail.PaymentAction = PaymentActionCodeType.SALE;
            paymentDetail.OrderTotal    = new BasicAmountType(CurrencyCodeType.NZD, _details.Amount.ToCurrencyString());

            var request = new DoExpressCheckoutPaymentRequestType {
                Version = PayPalConfig.VersionNumber
            };
            var requestDetails = new DoExpressCheckoutPaymentRequestDetailsType
            {
                PaymentDetails = paymentDetail.PutIntoList(),
                Token          = _details.Token,
                PayerID        = _details.PayerId
            };

            request.DoExpressCheckoutPaymentRequestDetails = requestDetails;

            return(new DoExpressCheckoutPaymentReq {
                DoExpressCheckoutPaymentRequest = request
            });
        }
Beispiel #20
0
        //private void setKeyResponseObjects(PayPalAPIInterfaceServiceService service, DoReferenceTransactionResponseType response)
        //{
        //    HttpContext CurrContext = new System.Web.HttpContext(); ;
        //    CurrContext.Items.Add("Response_apiName", "DoReferenceTransaction");
        //    CurrContext.Items.Add("Response_redirectURL", null);
        //    CurrContext.Items.Add("Response_requestPayload", service.getLastRequest());
        //    CurrContext.Items.Add("Response_responsePayload", service.getLastResponse());

        //    Dictionary<string, string> responseParams = new Dictionary<string, string>();
        //    responseParams.Add("Correlation Id", response.CorrelationID);
        //    responseParams.Add("API Result", response.Ack.ToString());

        //    if (response.Ack.Equals(AckCodeType.FAILURE) ||
        //        (response.Errors != null && response.Errors.Count > 0))
        //    {
        //        CurrContext.Items.Add("Response_error", response.Errors);
        //    }
        //    else
        //    {
        //        CurrContext.Items.Add("Response_error", null);
        //        DoReferenceTransactionResponseDetailsType transactionDetails = response.DoReferenceTransactionResponseDetails;
        //        responseParams.Add("Transaction ID", transactionDetails.TransactionID);

        //        if (transactionDetails.PaymentInfo != null)
        //        {
        //            responseParams.Add("Payment status", transactionDetails.PaymentInfo.PaymentStatus.ToString());
        //        }

        //        if (transactionDetails.PaymentInfo != null)
        //        {
        //            responseParams.Add("Pending reason", transactionDetails.PaymentInfo.PendingReason.ToString());
        //        }
        //    }
        //    CurrContext.Items.Add("Response_keyResponseObject", responseParams);
        //    Server.Transfer("../APIResponse.aspx");
        //}

        private void populateRequestObject(DoReferenceTransactionRequestType request)
        {
            DoReferenceTransactionRequestDetailsType referenceTransactionDetails = new DoReferenceTransactionRequestDetailsType();

            request.DoReferenceTransactionRequestDetails = referenceTransactionDetails;

            referenceTransactionDetails.ReferenceID   = "61K51535A9986391A";
            referenceTransactionDetails.PaymentAction = PaymentActionCodeType.SALE;


            PaymentDetailsType paymentDetails = new PaymentDetailsType();

            referenceTransactionDetails.PaymentDetails = paymentDetails;

            double orderTotal = 0.0;

            double           itemTotal = 0.0;
            CurrencyCodeType currency  = CurrencyCodeType.USD;

            PaymentDetailsItemType itemDetails = new PaymentDetailsItemType();

            itemDetails.Name = "ItemName";

            itemDetails.Amount = new BasicAmountType(currency, "10");

            itemDetails.Quantity = 2;

            itemDetails.ItemCategory = ItemCategoryType.DIGITAL;
            itemTotal += Convert.ToDouble(itemDetails.Amount.value) * itemDetails.Quantity.Value;

            paymentDetails.PaymentDetailsItem.Add(itemDetails);

            orderTotal += itemTotal;
            paymentDetails.ItemTotal  = new BasicAmountType(currency, itemTotal.ToString());
            paymentDetails.OrderTotal = new BasicAmountType(currency, orderTotal.ToString());
        }
Beispiel #21
0
        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);
            }
        }
Beispiel #22
0
        public TransactionResult SubmitPaymentTransaction(CheckoutDetails details)
        {
            //init result structure
            TransactionResult ret = new TransactionResult();

            //set up Request
            //instantiate DoDirectPaymentRequestType and RequestDetails objects
            DoDirectPaymentRequestType request = new DoDirectPaymentRequestType();

            request.Version = PROCESSOR_VERSION;
            DoDirectPaymentRequestDetailsType requestDetails = new DoDirectPaymentRequestDetailsType();

            request.DoDirectPaymentRequestDetails = requestDetails;

            //set payment action
            requestDetails.PaymentAction = PaymentActionCodeType.Sale;

            //set IP
            //requestDetails.IPAddress = Request.UserHostAddress;
            requestDetails.IPAddress = details[CheckoutKeys.IPAddress];

            //set CreditCard info
            CreditCardDetailsType creditCardDetails = new CreditCardDetailsType();

            requestDetails.CreditCard          = creditCardDetails;
            creditCardDetails.CreditCardNumber = details[CheckoutKeys.CardNumber];
            creditCardDetails.CreditCardType   = (CreditCardTypeType)Enum.Parse(typeof(CreditCardTypeType), details[CheckoutKeys.CardType], true);
            creditCardDetails.CVV2             = details[CheckoutKeys.VerificationCode];
            creditCardDetails.ExpMonth         = Int32.Parse(details[CheckoutKeys.ExpireMonth]);
            creditCardDetails.ExpYear          = Int32.Parse(details[CheckoutKeys.ExpireYear]);
            // Switch/Solo
            if (creditCardDetails.CreditCardType == CreditCardTypeType.Solo ||
                creditCardDetails.CreditCardType == CreditCardTypeType.Switch)
            {
                creditCardDetails.StartMonth  = Int32.Parse(details[CheckoutKeys.StartMonth]);
                creditCardDetails.StartYear   = Int32.Parse(details[CheckoutKeys.StartYear]);
                creditCardDetails.IssueNumber = details[CheckoutKeys.IssueNumber];
            }

            //set billing address
            PayerInfoType cardOwner = new PayerInfoType();

            creditCardDetails.CardOwner   = cardOwner;
            cardOwner.PayerName           = new PersonNameType();
            cardOwner.PayerName.FirstName = details[CheckoutKeys.FirstName];
            cardOwner.PayerName.LastName  = details[CheckoutKeys.LastName];

            cardOwner.Address         = new AddressType();
            cardOwner.Address.Street1 = details[CheckoutKeys.Address];
            //??? cardOwner.Address.Street2 = "";
            cardOwner.Address.CityName         = details[CheckoutKeys.City];
            cardOwner.Address.StateOrProvince  = details[CheckoutKeys.State];
            cardOwner.Address.PostalCode       = details[CheckoutKeys.Zip];
            cardOwner.Address.CountrySpecified = true;
            cardOwner.Address.Country          = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), details[CheckoutKeys.Country], true);

            //set payment Details
            PaymentDetailsType paymentDetails = new PaymentDetailsType();

            requestDetails.PaymentDetails = paymentDetails;
            paymentDetails.OrderTotal     = new BasicAmountType();
            //TODO: Add currency support
            paymentDetails.OrderTotal.currencyID = (CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), details[CheckoutKeys.Currency]);
            //paymentDetails.OrderTotal.currencyID = CurrencyCodeType.USD;
            //No currency symbol. Decimal separator must be a period (.), and the thousands separator must be a comma (,)
            paymentDetails.OrderTotal.Value = details[CheckoutKeys.Amount];

            DoDirectPaymentReq paymentRequest = new DoDirectPaymentReq();

            paymentRequest.DoDirectPaymentRequest = request;

            //FINISH set up req
            //setup request Header, API credentials
            PayPalAPIAASoapBinding paypalInterface = new PayPalAPIAASoapBinding();
            UserIdPasswordType     user            = new UserIdPasswordType();

            //set api credentials - username, password, signature
            user.Username  = Username;
            user.Password  = Password;
            user.Signature = Signature;
            // setup service url
            paypalInterface.Url = ServiceUrl;
            paypalInterface.RequesterCredentials             = new CustomSecurityHeaderType();
            paypalInterface.RequesterCredentials.Credentials = user;

            //make call return response
            DoDirectPaymentResponseType paymentResponse = new DoDirectPaymentResponseType();

            paymentResponse = paypalInterface.DoDirectPayment(paymentRequest);
            //write response xml to the ret object
            ret.RawResponse = SerializeObject(paymentResponse);

            switch (paymentResponse.Ack)
            {
            case AckCodeType.Success:
            case AckCodeType.SuccessWithWarning:
                ret.Succeed           = true;
                ret.TransactionId     = paymentResponse.TransactionID;
                ret.TransactionStatus = TransactionStatus.Approved;
                break;

            default:                     // show errors if Ack is NOT Success
                ret.Succeed           = false;
                ret.TransactionStatus = TransactionStatus.Declined;
                if (paymentResponse.Errors != null &&
                    paymentResponse.Errors.Length > 0)
                {
                    ret.StatusCode = PayPalProKeys.ErrorPrefix + paymentResponse.Errors[0].ErrorCode;
                }
                break;
            }
            return(ret);
        }
Beispiel #23
0
        //GET : PayPal/PaymentSuccess
        public async Task <ActionResult> PaymentSuccess(Guid invoiceId)
        {
            GetExpressCheckoutDetailsRequestType request = new GetExpressCheckoutDetailsRequestType();

            request.Version = "104.0";
            request.Token   = Request["token"];
            GetExpressCheckoutDetailsReq wrapper = new GetExpressCheckoutDetailsReq();

            wrapper.GetExpressCheckoutDetailsRequest = request;

            //define sdk configuration
            Dictionary <string, string> sdkConfig = new Dictionary <string, string>();

            sdkConfig.Add("mode", ConfigurationManager.AppSettings["paypal.mode"]);
            sdkConfig.Add("account1.apiUsername", ConfigurationManager.AppSettings["paypal.apiUsername"]);
            sdkConfig.Add("account1.apiPassword", ConfigurationManager.AppSettings["paypal.apiPassword"]);
            sdkConfig.Add("account1.apiSignature", ConfigurationManager.AppSettings["paypal.apiSignature"]);
//            sdkConfig.Add("acct1.UserName", ConfigurationManager.AppSettings["paypal.apiUsername"]);
//            sdkConfig.Add("acct1.Password", ConfigurationManager.AppSettings["paypal.apiPassword"]);
//            sdkConfig.Add("acct1.Signature", ConfigurationManager.AppSettings["paypal.apiSignature"]);

            PayPalAPIInterfaceServiceService      s          = new PayPalAPIInterfaceServiceService(sdkConfig);
            GetExpressCheckoutDetailsResponseType ecResponse = s.GetExpressCheckoutDetails(wrapper);

            if (ecResponse.Ack.HasValue &&
                ecResponse.Ack.Value.ToString() != "FAILURE" &&
                ecResponse.Errors.Count == 0)
            {
                double paymentAmount = 0.0;
                double.TryParse(ecResponse.GetExpressCheckoutDetailsResponseDetails.PaymentDetails.FirstOrDefault().OrderTotal.value, out paymentAmount);

                PaymentDetailsType paymentDetail = new PaymentDetailsType();
                paymentDetail.NotifyURL     = "http://replaceIpnUrl.com";
                paymentDetail.PaymentAction = (PaymentActionCodeType)EnumUtils.GetValue("Sale", typeof(PaymentActionCodeType));
                paymentDetail.OrderTotal    = new BasicAmountType((CurrencyCodeType)EnumUtils.GetValue("USD", typeof(CurrencyCodeType)), paymentAmount + "");
                List <PaymentDetailsType> paymentDetails = new List <PaymentDetailsType>();
                paymentDetails.Add(paymentDetail);

                DoExpressCheckoutPaymentRequestType doExpressCheckoutPaymentRequestType = new DoExpressCheckoutPaymentRequestType();
                request.Version = "104.0";
                DoExpressCheckoutPaymentRequestDetailsType requestDetails = new DoExpressCheckoutPaymentRequestDetailsType();
                requestDetails.PaymentDetails = paymentDetails;
                requestDetails.Token          = Request["token"];
                requestDetails.PayerID        = Request["PayerID"];
                doExpressCheckoutPaymentRequestType.DoExpressCheckoutPaymentRequestDetails = requestDetails;

                DoExpressCheckoutPaymentReq doExpressCheckoutPaymentReq = new DoExpressCheckoutPaymentReq();
                doExpressCheckoutPaymentReq.DoExpressCheckoutPaymentRequest = doExpressCheckoutPaymentRequestType;

                s = new PayPalAPIInterfaceServiceService(sdkConfig);
                DoExpressCheckoutPaymentResponseType doECResponse = s.DoExpressCheckoutPayment(doExpressCheckoutPaymentReq);

                if (doECResponse.Ack.HasValue &&
                    doECResponse.Ack.Value.ToString() != "FAILURE" &&
                    doECResponse.Errors.Count == 0)
                {
                    //create payment object for invoice
                    PaymentService       paymentService       = new PaymentService(this.db);
                    PaymentMethodService paymentMethodService = new PaymentMethodService(this.db);
                    var ccPymtMethod = paymentMethodService.GetCreditCardPaymentMethod(UserContact);

                    if (ccPymtMethod == null)
                    {
                        try
                        {
                            PaymentMethodTypeService paymentMethodTypeService = new PaymentMethodTypeService(this.db);
                            string ccTypeCode = GNPaymentMethodType.Types.CREDIT_CARD.GetCode();
                            var    ccType     = this.db.GNPaymentMethodTypes
                                                .Where(pt => pt.Name == ccTypeCode).FirstOrDefault();

                            await paymentMethodService.Insert(UserContact, new GNPaymentMethod
                            {
                                GNAccountId           = UserContact.GNOrganization.Account.Id,
                                GNPaymentMethodTypeId = ccType.Id,
                                Description           = "PAYPAL",
                                IsDefault             = true,
                                IsActive = true,
                                UsedForRecurrentPayments = false,
                                PCITokenId     = "X",
                                LastFourDigits = "X",
                                ExpirationDate = DateTime.MaxValue,
                                CreateDateTime = DateTime.Now,
                                CreatedBy      = UserContact.Id
                            });
                        }
                        catch (Exception e)
                        {
                            LogUtil.Error(logger, "Error adding PayPal Credit Card payment method!!", e);
                        }

                        ccPymtMethod = paymentMethodService.GetCreditCardPaymentMethod(UserContact);

                        if (ccPymtMethod == null)
                        {
                            throw new Exception("Credit Card Payment Method Not Found!!");
                        }
                    }

                    var ecPaymentInfo = doECResponse.DoExpressCheckoutPaymentResponseDetails.PaymentInfo.FirstOrDefault();

                    double grossAmount = 0.0;
                    double.TryParse(ecPaymentInfo.GrossAmount.value, out grossAmount);

                    if (grossAmount != 0.0)
                    {
                        try
                        {
                            var payment = new GNPayment
                            {
                                Id                = Guid.NewGuid(),
                                GNInvoiceId       = invoiceId,
                                GNPaymentMethodId = ccPymtMethod.Id,
                                PaymentDate       = DateTime.Now,
                                TotalAmount       = grossAmount,
                                Status            = ecPaymentInfo.PaymentStatus.Value.ToString(),
                                ExternalTxnId     = ecPaymentInfo.TransactionID,
                                CreateDateTime    = DateTime.Now,
                                CreatedBy         = UserContact.Id
                            };

                            this.AddInvoiceToPayment(payment);

                            await paymentService.Insert(UserContact, payment);
                        }
                        catch (Exception e)
                        {
                            LogUtil.Error(logger, "Error inserting payment!!", e);
                        }
                    }
                    else
                    {
                        throw new Exception("Payment Amount of 0.0 Not Allowed!!");
                    }
                }
            }

            return(RedirectToAction("MyBillingPayments", "Account"));
        }
        /// <summary>
        /// Builds the <see cref="PaymentDetailsItemType"/>.
        /// </summary>
        /// <param name="invoice">
        /// The invoice.
        /// </param>
        /// <param name="actionCode">
        /// The <see cref="PaymentActionCodeType"/>.
        /// </param>
        /// <returns>
        /// The <see cref="PaymentDetailsType"/>.
        /// </returns>
        public PaymentDetailsType Build(IInvoice invoice, PaymentActionCodeType actionCode)
        {
            // Get the decimal configuration for the current currency
            var currencyCodeType = PayPalApiHelper.GetPayPalCurrencyCode(invoice.CurrencyCode);
            var basicAmountFactory = new PayPalBasicAmountTypeFactory(currencyCodeType);

            // Get the tax total
            var itemTotal = basicAmountFactory.Build(invoice.TotalItemPrice());
            var shippingTotal = basicAmountFactory.Build(invoice.TotalShipping());
            var taxTotal = basicAmountFactory.Build(invoice.TotalTax());
            var invoiceTotal = basicAmountFactory.Build(invoice.Total);

            var items = BuildPaymentDetailsItemTypes(invoice.ProductLineItems(), basicAmountFactory);

            var paymentDetails = new PaymentDetailsType
            {
                PaymentDetailsItem = items.ToList(),
                ItemTotal = itemTotal,
                TaxTotal = taxTotal,
                ShippingTotal = shippingTotal,
                OrderTotal = invoiceTotal,
                PaymentAction = actionCode,
                InvoiceID = invoice.PrefixedInvoiceNumber()
            };

            // ShipToAddress
            if (invoice.ShippingLineItems().Any())
            {
                var addressTypeFactory = new PayPalAddressTypeFactory();
                paymentDetails.ShipToAddress = addressTypeFactory.Build(invoice.GetShippingAddresses().FirstOrDefault());
            }

            return paymentDetails;
        }
        /// <summary>
        /// Construct the Gets the PayPal payment details from our payment and Cart to pass onto PayPal.
        /// </summary>
        /// <remarks>
        /// The PayPal payment detail can be a bit different from OrderForm because
        /// sometimes cart total calculated by Commerce is different with cart total calculated by PalPal,
        /// though this difference is very small (~0.01 currency).
        /// We adjust this into an additional item to ensure PayPal shows the same total number with Commerce.
        /// We also add the Order discount (if any) as and special item with negative price to PayPal payment detail.
        /// See detail about PayPal structure type in this link https://developer.paypal.com/docs/classic/express-checkout/ec_api_flow/
        /// </remarks>
        /// <param name="payment">The payment to take info (Total, LineItem, ...) from</param>
        /// <param name="orderGroup">The order group (to be InvoiceID to pass to PayPal)</param>
        /// <param name="orderNumber">The order number.</param>
        /// <param name="notifyUrl">The notify Url.</param>
        /// <returns>The PayPal payment detail to pass to API request</returns>
        public PaymentDetailsType GetPaymentDetailsType(IPayment payment, IOrderGroup orderGroup, string orderNumber, string notifyUrl)
        {
            var orderForm          = orderGroup.Forms.First(form => form.Payments.Contains(payment));
            var paymentDetailsType = new PaymentDetailsType();

            paymentDetailsType.ButtonSource = "Episerver_Cart_EC";                                        // (Optional) An identification code for use by third-party applications to identify transactions. Character length and limitations: 32 single-byte alphanumeric characters
            paymentDetailsType.InvoiceID    = orderNumber;                                                // Character length and limitations: 127 single-byte alphanumeric characters
            paymentDetailsType.Custom       = orderGroup.CustomerId + "|" + paymentDetailsType.InvoiceID; // A free-form field for your own use. Character length and limitations: 256 single-byte alphanumeric characters
                                                                                                          // NOTE: paymentDetailsType.OrderDescription = 127 single-byte alphanumeric characters string
                                                                                                          // NOTE: paymentDetailsType.TransactionId = string, provided if you have transactionId in your Commerce system // (Optional) Transaction identification number of the transaction that was created.;

            // (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 only applies to DoExpressCheckoutPayment. This value is ignored when set in SetExpressCheckout or GetExpressCheckoutDetails.
            // Character length and limitations: 2,048 single-byte alphanumeric characters
            paymentDetailsType.NotifyURL = notifyUrl;

            var currency      = orderGroup.Currency;
            var totalOrder    = currency.Round(payment.Amount);
            var totalShipping = currency.Round(orderGroup.GetShippingTotal(_orderGroupCalculator).Amount);
            var totalHandling = currency.Round(orderForm.HandlingTotal);
            var totalTax      = currency.Round(orderGroup.GetTaxTotal(_orderGroupCalculator).Amount);
            var lineItemTotal = 0m;

            var paymentDetailItems = new List <PaymentDetailsItemType>();

            foreach (var lineItem in orderForm.GetAllLineItems())
            {
                // recalculate final unit price after all kind of discounts are subtracted from item.ListPrice
                var finalUnitPrice = currency.Round(lineItem.GetExtendedPrice(currency).Amount / lineItem.Quantity);
                lineItemTotal += finalUnitPrice * lineItem.Quantity;

                paymentDetailItems.Add(new PaymentDetailsItemType
                {
                    Name     = lineItem.DisplayName,
                    Number   = lineItem.Code,
                    Quantity = Convert.ToInt32(lineItem.Quantity.ToString("0")),
                    Amount   = ToPayPalAmount(finalUnitPrice, currency)
                });
            }

            // this adjustment also include the gift-card (in sample)
            var orderAdjustment       = totalOrder - totalShipping - totalHandling - totalTax - lineItemTotal;
            var adjustmentForShipping = 0m;

            if (orderAdjustment != 0 || // adjustment for gift card/(order level) promotion case
                lineItemTotal == 0    // in this case, the promotion (or discount) make all lineItemTotal zero, but buyer still have to pay shipping (and/or handling, tax).
                                      // We still need to adjust lineItemTotal for Paypal accepting (need to be greater than zero)
                )
            {
                var paymentDetailItem = new PaymentDetailsItemType
                {
                    Name        = "Order adjustment",
                    Number      = "ORDERADJUSTMENT",
                    Description = "GiftCard, Discount at OrderLevel and/or PayPal-Commerce-calculating difference in cart total",  // Character length and limitations: 127 single-byte characters
                    Quantity    = 1
                };

                var predictLineitemTotal = lineItemTotal + orderAdjustment;
                if (predictLineitemTotal <= 0)
                {
                    // can't overpaid for item. E.g.: total item amount is 68, orderAdjustment is -70, PayPal will refuse ItemTotal = -2
                    // we need to push -2 to shippingTotal or shippingDiscount

                    // HACK: Paypal will not accept an item total of $0, even if there is a shipping fee. The Item total must be at least 1 cent/penny.
                    // We need to take 1 cent/penny from adjustmentForLineItemTotal and push to adjustmentForShipping
                    orderAdjustment       = (-lineItemTotal + 0.01m);     // -68 + 0.01 = -67.99
                    adjustmentForShipping = predictLineitemTotal - 0.01m; // -2 - 0.01 = -2.01
                }
                else
                {
                    // this case means: due to PayPal calculation, buyer need to pay more that what Commerce calculate. Because:
                    // sometimes cart total calculated by Commerce is different with
                    // cart total calculated by PalPal, though this difference is very small (~0.01 currency)
                    // We adjust the items total to make up for that, to ensure PayPal shows the same total number with Commerce
                }

                lineItemTotal += orderAdjustment; // re-adjust the lineItemTotal

                paymentDetailItem.Amount = ToPayPalAmount(orderAdjustment, currency);
                paymentDetailItems.Add(paymentDetailItem);
            }

            if (adjustmentForShipping > 0)
            {
                totalShipping += adjustmentForShipping;
            }
            else
            {
                // Shipping discount for this order. You specify this value as a negative number.
                // NOTE:Character length and limitations: Must not exceed $10,000 USD in any currency.
                // No currency symbol. Regardless of currency, decimal separator must be a period (.), and the optional thousands separator must be a comma (,).
                // Equivalent to nine characters maximum for USD.
                // NOTE:You must set the currencyID attribute to one of the three-character currency codes for any of the supported PayPal currencies.
                paymentDetailsType.ShippingDiscount = ToPayPalAmount(adjustmentForShipping, currency);
            }

            paymentDetailsType.OrderTotal    = ToPayPalAmount(totalOrder, currency);
            paymentDetailsType.ShippingTotal = ToPayPalAmount(totalShipping, currency);
            paymentDetailsType.HandlingTotal = ToPayPalAmount(totalHandling, currency);
            paymentDetailsType.TaxTotal      = ToPayPalAmount(totalTax, currency);
            paymentDetailsType.ItemTotal     = ToPayPalAmount(lineItemTotal, currency);

            paymentDetailsType.PaymentDetailsItem = paymentDetailItems;
            paymentDetailsType.ShipToAddress      = AddressHandling.ToAddressType(orderForm.Shipments.First().ShippingAddress);

            if (orderForm.Shipments.Count > 1)
            {
                // (Optional) The value 1 indicates that this payment is associated with multiple shipping addresses. Character length and limitations: Four single-byte numeric characters.
                paymentDetailsType.MultiShipping = "1";
            }

            return(paymentDetailsType);
        }
Beispiel #26
0
        /// <summary>
        /// Do paypal express checkout
        /// </summary>
        /// <param name="paymentInfo">Payment info required for an order processing</param>
        /// <param name="orderGuid">Unique order identifier</param>
        /// <param name="processPaymentResult">Process payment result</param>
        public void DoExpressCheckout(PaymentInfo paymentInfo,
                                      Guid orderGuid, ProcessPaymentResult processPaymentResult)
        {
            InitSettings();
            TransactMode transactionMode = GetCurrentTransactionMode();

            DoExpressCheckoutPaymentReq         req     = new DoExpressCheckoutPaymentReq();
            DoExpressCheckoutPaymentRequestType request = new DoExpressCheckoutPaymentRequestType();

            req.DoExpressCheckoutPaymentRequest = request;
            request.Version = this.APIVersion;
            DoExpressCheckoutPaymentRequestDetailsType details = new DoExpressCheckoutPaymentRequestDetailsType();

            request.DoExpressCheckoutPaymentRequestDetails = details;
            if (transactionMode == TransactMode.Authorize)
            {
                details.PaymentAction = PaymentActionCodeType.Authorization;
            }
            else
            {
                details.PaymentAction = PaymentActionCodeType.Sale;
            }
            details.PaymentActionSpecified = true;
            details.Token   = paymentInfo.PaypalToken;
            details.PayerID = paymentInfo.PaypalPayerId;

            details.PaymentDetails = new PaymentDetailsType[1];
            PaymentDetailsType paymentDetails1 = new PaymentDetailsType();

            details.PaymentDetails[0]             = paymentDetails1;
            paymentDetails1.OrderTotal            = new BasicAmountType();
            paymentDetails1.OrderTotal.Value      = paymentInfo.OrderTotal.ToString("N", new CultureInfo("en-us"));
            paymentDetails1.OrderTotal.currencyID = PaypalHelper.GetPaypalCurrency(IoC.Resolve <ICurrencyService>().PrimaryStoreCurrency);
            paymentDetails1.Custom       = orderGuid.ToString();
            paymentDetails1.ButtonSource = "nopCommerceCart";

            DoExpressCheckoutPaymentResponseType response = service2.DoExpressCheckoutPayment(req);
            string error;

            if (!PaypalHelper.CheckSuccess(response, out error))
            {
                throw new NopException(error);
            }

            if (response.DoExpressCheckoutPaymentResponseDetails.PaymentInfo != null &&
                response.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0] != null)
            {
                processPaymentResult.AuthorizationTransactionId     = response.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].TransactionID;
                processPaymentResult.AuthorizationTransactionResult = response.Ack.ToString();

                if (transactionMode == TransactMode.Authorize)
                {
                    processPaymentResult.PaymentStatus = PaymentStatusEnum.Authorized;
                }
                else
                {
                    processPaymentResult.PaymentStatus = PaymentStatusEnum.Paid;
                }
            }
            else
            {
                throw new NopException("response.DoExpressCheckoutPaymentResponseDetails.PaymentInfo is null");
            }
        }
Beispiel #27
0
        public SetExpressCheckoutResponseType SetExpressCheckout(PayPalProcessPaymentRequest processPaymentRequest, IList <OrganizedShoppingCartItem> cart)
        {
            var result         = new SetExpressCheckoutResponseType();
            var store          = Services.StoreService.GetStoreById(processPaymentRequest.StoreId);
            var customer       = Services.WorkContext.CurrentCustomer;
            var settings       = Services.Settings.LoadSetting <PayPalExpressPaymentSettings>(processPaymentRequest.StoreId);
            var payPalCurrency = GetApiCurrency(store.PrimaryStoreCurrency);
            var excludingTax   = (Services.WorkContext.GetTaxDisplayTypeFor(customer, store.Id) == TaxDisplayType.ExcludingTax);

            var req = new SetExpressCheckoutReq
            {
                SetExpressCheckoutRequest = new SetExpressCheckoutRequestType
                {
                    Version = ApiVersion,
                    SetExpressCheckoutRequestDetails = new SetExpressCheckoutRequestDetailsType()
                }
            };

            var details = new SetExpressCheckoutRequestDetailsType
            {
                PaymentAction          = GetPaymentAction(settings),
                PaymentActionSpecified = true,
                CancelURL = Services.WebHelper.GetStoreLocation(store.SslEnabled) + "cart",
                ReturnURL = Services.WebHelper.GetStoreLocation(store.SslEnabled) + "Plugins/SmartStore.PayPal/PayPalExpress/GetDetails",
                //CallbackURL = _webHelper.GetStoreLocation(currentStore.SslEnabled) + "Plugins/SmartStore.PayPal/PayPalExpress/ShippingOptions?CustomerID=" + _workContext.CurrentCustomer.Id.ToString(),
                //CallbackTimeout = _payPalExpressPaymentSettings.CallbackTimeout.ToString()
                ReqConfirmShipping = settings.ConfirmedShipment.ToString(),
                NoShipping         = settings.NoShipmentAddress.ToString()
            };

            // populate cart
            var taxRate          = decimal.Zero;
            var unitPriceTaxRate = decimal.Zero;
            var itemTotal        = decimal.Zero;
            var cartItems        = new List <PaymentDetailsItemType>();

            foreach (var item in cart)
            {
                var product   = item.Item.Product;
                var unitPrice = _priceCalculationService.GetUnitPrice(item, true);
                var shoppingCartUnitPriceWithDiscount = excludingTax
                    ? _taxService.GetProductPrice(product, unitPrice, false, customer, out taxRate)
                    : _taxService.GetProductPrice(product, unitPrice, true, customer, out unitPriceTaxRate);

                cartItems.Add(new PaymentDetailsItemType
                {
                    Name     = product.Name,
                    Number   = product.Sku,
                    Quantity = item.Item.Quantity.ToString(),
                    // this is the per item cost
                    Amount = new BasicAmountType
                    {
                        currencyID = payPalCurrency,
                        Value      = shoppingCartUnitPriceWithDiscount.FormatInvariant()
                    }
                });

                itemTotal += (item.Item.Quantity * shoppingCartUnitPriceWithDiscount);
            }
            ;

            // additional handling fee
            var additionalHandlingFee = GetAdditionalHandlingFee(cart);

            cartItems.Add(new PaymentDetailsItemType
            {
                Name     = T("Plugins.Payments.PayPal.PaymentMethodFee").Text,
                Quantity = "1",
                Amount   = new BasicAmountType()
                {
                    currencyID = payPalCurrency,
                    Value      = additionalHandlingFee.FormatInvariant()
                }
            });

            itemTotal += GetAdditionalHandlingFee(cart);

            //shipping
            var shippingTotal = decimal.Zero;

            if (cart.RequiresShipping())
            {
                decimal?shoppingCartShippingBase = OrderTotalCalculationService.GetShoppingCartShippingTotal(cart);
                if (shoppingCartShippingBase.HasValue && shoppingCartShippingBase > 0)
                {
                    shippingTotal = _currencyService.ConvertFromPrimaryStoreCurrency(shoppingCartShippingBase.Value, Services.WorkContext.WorkingCurrency);
                }
                else
                {
                    shippingTotal = settings.DefaultShippingPrice;
                }
            }

            //This is the default if the Shipping Callback fails
            //var shippingOptions = new List<ShippingOptionType>();
            //shippingOptions.Add(new ShippingOptionType()
            //{
            //    ShippingOptionIsDefault = "true",
            //    ShippingOptionName = "Standard Shipping",
            //    ShippingOptionAmount = new BasicAmountType()
            //    {
            //        Value = shippingTotal.ToString(), //This is the default value used for shipping if the Instant Update API returns an error or does not answer within the callback time
            //        currencyID = PaypalHelper.GetPaypalCurrency(_currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId))
            //    }
            //});
            //details.FlatRateShippingOptions = shippingOptions.ToArray();
            //details.TotalType = TotalType.EstimatedTotal;

            // get total tax
            //SortedDictionary<decimal, decimal> taxRates = null;
            //decimal shoppingCartTaxBase = OrderTotalCalculationService.GetTaxTotal(cart, out taxRates);
            //decimal shoppingCartTax = _currencyService.ConvertFromPrimaryStoreCurrency(shoppingCartTaxBase, CommonServices.WorkContext.WorkingCurrency);

            // discount
            var discount = -processPaymentRequest.Discount;

            if (discount != 0)
            {
                cartItems.Add(new PaymentDetailsItemType
                {
                    Name     = T("Plugins.Payments.PayPal.ThreadrockDiscount").Text,
                    Quantity = "1",
                    Amount   = new BasicAmountType // this is the total discount
                    {
                        currencyID = payPalCurrency,
                        Value      = discount.FormatInvariant()
                    }
                });

                itemTotal += discount;
            }

            if (!cart.IsRecurring())
            {
                //we don't apply gift cards for recurring products
                var giftCards = _giftCardService.GetActiveGiftCardsAppliedByCustomer(customer, Services.StoreContext.CurrentStore.Id);
                if (giftCards != null)
                {
                    foreach (var gc in giftCards)
                    {
                        if (itemTotal > decimal.Zero)
                        {
                            decimal remainingAmount = gc.GetGiftCardRemainingAmount();
                            decimal amountCanBeUsed = decimal.Zero;
                            if (itemTotal > remainingAmount)
                            {
                                amountCanBeUsed = remainingAmount;
                            }
                            else
                            {
                                amountCanBeUsed = itemTotal - .01M;
                            }

                            decimal amountToSubtract = -amountCanBeUsed;

                            cartItems.Add(new PaymentDetailsItemType
                            {
                                Name     = T("Plugins.Payments.PayPal.GiftcardApplied").Text,
                                Quantity = "1",
                                Amount   = new BasicAmountType
                                {
                                    currencyID = payPalCurrency,
                                    Value      = amountToSubtract.FormatInvariant()
                                }
                            });

                            //reduce subtotal
                            itemTotal += amountToSubtract;
                        }
                    }
                }
            }

            // populate payment details
            var paymentDetails = new PaymentDetailsType
            {
                ItemTotal = new BasicAmountType
                {
                    Value      = Math.Round(itemTotal, 2).FormatInvariant(),
                    currencyID = payPalCurrency
                },
                ShippingTotal = new BasicAmountType
                {
                    Value      = Math.Round(shippingTotal, 2).FormatInvariant(),
                    currencyID = payPalCurrency
                },
                //TaxTotal = new BasicAmountType
                //{
                //    Value = Math.Round(shoppingCartTax, 2).ToString("N", new CultureInfo("en-us")),
                //    currencyID = PayPalHelper.GetPaypalCurrency(_currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId))
                //},
                OrderTotal = new BasicAmountType
                {
                    Value      = Math.Round(itemTotal + shippingTotal, 2).FormatInvariant(),
                    currencyID = payPalCurrency
                },
                Custom             = processPaymentRequest.OrderGuid.ToString(),
                ButtonSource       = SmartStoreVersion.CurrentFullVersion,
                PaymentAction      = GetPaymentAction(settings),
                PaymentDetailsItem = cartItems.ToArray()
            };

            details.PaymentDetails = new[] { paymentDetails };

            details.ShippingMethodSpecified = true;

            req.SetExpressCheckoutRequest.SetExpressCheckoutRequestDetails.Custom = processPaymentRequest.OrderGuid.ToString();
            req.SetExpressCheckoutRequest.SetExpressCheckoutRequestDetails        = details;

            using (var service = GetApiAaService(settings))
            {
                result = service.SetExpressCheckout(req);
            }

            var checkoutState = _httpContext.GetCheckoutState();

            if (checkoutState.CustomProperties.ContainsKey("PayPalExpressButtonUsed"))
            {
                checkoutState.CustomProperties["PayPalExpressButtonUsed"] = true;
            }
            else
            {
                checkoutState.CustomProperties.Add("PayPalExpressButtonUsed", true);
            }

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

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

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

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

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

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

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

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

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

            doDirectPaymentRequestDetails.CreditCard = creditCard;

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

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

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

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

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

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

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

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

                // # Success values
                if (responseDoDirectPaymentResponseType.Ack.ToString().Trim().ToUpper().Equals("SUCCESS"))
                {
                    // Unique identifier of the transaction
                    logger.Info("Transaction ID : " + responseDoDirectPaymentResponseType.TransactionID + "\n");
                    Console.WriteLine("Transaction ID : " + responseDoDirectPaymentResponseType.TransactionID + "\n");
                }
                // # Error Values
                else
                {
                    List <ErrorType> errorMessages = responseDoDirectPaymentResponseType.Errors;
                    foreach (ErrorType error in errorMessages)
                    {
                        logger.Debug("API Error Message : " + error.LongMessage);
                        Console.WriteLine("API Error Message : " + error.LongMessage + "\n");
                    }
                }
            }
        }
        // # Exception log
        catch (System.Exception ex)
        {
            // Log the exception message
            logger.Debug("Error Message : " + ex.Message);
            Console.WriteLine("Error Message : " + ex.Message);
        }
        return(responseDoDirectPaymentResponseType);
    }
Beispiel #29
0
    //#DoReferenceTransaction API Operation
    //The DoReferenceTransaction API operation processes a payment from a buyer’s account, which is identified by a previous transaction.
    public DoReferenceTransactionResponseType DoReferenceTransactionAPIOperation()
    {
        DoReferenceTransactionResponseType responseDoReferenceTransactionResponseType = new DoReferenceTransactionResponseType();

        try
        {
            // Create the DoReferenceTransactionReq object
            DoReferenceTransactionReq doReferenceTransaction = new DoReferenceTransactionReq();

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

            // The total cost of the transaction to the buyer. If shipping cost and
            // tax charges are known, include them in this value. If not, this value
            // should be the current subtotal of the order.

            // If the transaction includes one or more one-time purchases, this field must be equal to
            // the sum of the purchases. Set this field to 0 if the transaction does
            // not include a one-time purchase such as when you set up a billing
            // agreement for a recurring payment that is not immediately charged.
            // When the field is set to 0, purchase-specific fields are ignored
            //
            // * `Currency ID` - You must set the currencyID attribute to one of the
            // 3-character currency codes for any of the supported PayPal
            // currencies.
            // * `Amount`
            BasicAmountType orderTotal = new BasicAmountType(CurrencyCodeType.USD, "3.00");
            paymentDetails.OrderTotal = orderTotal;

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

            // `DoReferenceTransactionRequestDetails` takes mandatory params:
            //
            // * `Reference Id` - A transaction ID from a previous purchase, such as a
            // credit card charge using the DoDirectPayment API, or a billing
            // agreement ID.
            // * `Payment Action Code` - How you want to obtain payment. It is one of
            // the following values:
            // * Authorization
            // * Sale
            // * Order
            // * None
            // * `Payment Details`
            DoReferenceTransactionRequestDetailsType doReferenceTransactionRequestDetails
                = new DoReferenceTransactionRequestDetailsType("97U72738FY126561H", PaymentActionCodeType.SALE, paymentDetails);
            DoReferenceTransactionRequestType doReferenceTransactionRequest = new DoReferenceTransactionRequestType(doReferenceTransactionRequestDetails);
            doReferenceTransaction.DoReferenceTransactionRequest = doReferenceTransactionRequest;

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

            // # API call
            // Invoke the DoReferenceTransaction method in service wrapper object
            responseDoReferenceTransactionResponseType = service.DoReferenceTransaction(doReferenceTransaction);

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

                // # Success values
                if (responseDoReferenceTransactionResponseType.Ack.ToString().Trim().ToUpper().Equals("SUCCESS"))
                {
                    // The final amount charged, including any shipping and taxes from your Merchant Profile
                    logger.Info("Amount : " + responseDoReferenceTransactionResponseType.DoReferenceTransactionResponseDetails.Amount.currencyID
                                + " " + responseDoReferenceTransactionResponseType.DoReferenceTransactionResponseDetails.Amount.value + "\n");
                    Console.WriteLine("Amount : " + responseDoReferenceTransactionResponseType.DoReferenceTransactionResponseDetails.Amount.currencyID
                                      + " " + responseDoReferenceTransactionResponseType.DoReferenceTransactionResponseDetails.Amount.value + "\n");
                }
                // # Error Values
                else
                {
                    List <ErrorType> errorMessages = responseDoReferenceTransactionResponseType.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(responseDoReferenceTransactionResponseType);
    }
        public SetExpressCheckoutResponseType SetExpressCheckout(PayPalProcessPaymentRequest processPaymentRequest,
                                                                 IList <Core.Domain.Orders.OrganizedShoppingCartItem> cart)
        {
            var result       = new SetExpressCheckoutResponseType();
            var currentStore = CommonServices.StoreContext.CurrentStore;

            var req = new SetExpressCheckoutReq
            {
                SetExpressCheckoutRequest = new SetExpressCheckoutRequestType
                {
                    Version = PayPalHelper.GetApiVersion(),
                    SetExpressCheckoutRequestDetails = new SetExpressCheckoutRequestDetailsType()
                }
            };

            var details = new SetExpressCheckoutRequestDetailsType
            {
                PaymentAction          = PayPalHelper.GetPaymentAction(Settings),
                PaymentActionSpecified = true,
                CancelURL = CommonServices.WebHelper.GetStoreLocation(currentStore.SslEnabled) + "cart",
                ReturnURL = CommonServices.WebHelper.GetStoreLocation(currentStore.SslEnabled) + "Plugins/SmartStore.PayPal/PayPalExpress/GetDetails",
                //CallbackURL = _webHelper.GetStoreLocation(currentStore.SslEnabled) + "Plugins/SmartStore.PayPal/PayPalExpress/ShippingOptions?CustomerID=" + _workContext.CurrentCustomer.Id.ToString(),
                //CallbackTimeout = _payPalExpressPaymentSettings.CallbackTimeout.ToString()
                ReqConfirmShipping = Settings.ConfirmedShipment.ToString(),
                NoShipping         = Settings.NoShipmentAddress.ToString()
            };

            // populate cart
            decimal itemTotal = decimal.Zero;
            var     cartItems = new List <PaymentDetailsItemType>();

            foreach (OrganizedShoppingCartItem item in cart)
            {
                decimal shoppingCartUnitPriceWithDiscountBase = _priceCalculationService.GetUnitPrice(item, true);
                decimal shoppingCartUnitPriceWithDiscount     = _currencyService.ConvertFromPrimaryStoreCurrency(shoppingCartUnitPriceWithDiscountBase, CommonServices.WorkContext.WorkingCurrency);
                decimal priceIncludingTier = shoppingCartUnitPriceWithDiscount;
                cartItems.Add(new PaymentDetailsItemType()
                {
                    Name     = item.Item.Product.Name,
                    Number   = item.Item.Product.Sku,
                    Quantity = item.Item.Quantity.ToString(),
                    Amount   = new BasicAmountType() // this is the per item cost
                    {
                        currencyID = PayPalHelper.GetPaypalCurrency(_currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId)),
                        Value      = (priceIncludingTier).ToString("N", new CultureInfo("en-us"))
                    }
                });
                itemTotal += (item.Item.Quantity * priceIncludingTier);
            }
            ;

            decimal shippingTotal = decimal.Zero;

            if (cart.RequiresShipping())
            {
                decimal?shoppingCartShippingBase = OrderTotalCalculationService.GetShoppingCartShippingTotal(cart);
                if (shoppingCartShippingBase.HasValue && shoppingCartShippingBase > 0)
                {
                    shippingTotal = _currencyService.ConvertFromPrimaryStoreCurrency(shoppingCartShippingBase.Value, CommonServices.WorkContext.WorkingCurrency);
                }
                else
                {
                    shippingTotal = Settings.DefaultShippingPrice;
                }
            }

            //This is the default if the Shipping Callback fails
            //var shippingOptions = new List<ShippingOptionType>();
            //shippingOptions.Add(new ShippingOptionType()
            //{
            //    ShippingOptionIsDefault = "true",
            //    ShippingOptionName = "Standard Shipping",
            //    ShippingOptionAmount = new BasicAmountType()
            //    {
            //        Value = shippingTotal.ToString(), //This is the default value used for shipping if the Instant Update API returns an error or does not answer within the callback time
            //        currencyID = PaypalHelper.GetPaypalCurrency(_currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId))
            //    }
            //});
            //details.FlatRateShippingOptions = shippingOptions.ToArray();
            //details.TotalType = TotalType.EstimatedTotal;

            // get total tax
            SortedDictionary <decimal, decimal> taxRates = null;
            decimal shoppingCartTaxBase = OrderTotalCalculationService.GetTaxTotal(cart, out taxRates);
            decimal shoppingCartTax     = _currencyService.ConvertFromPrimaryStoreCurrency(shoppingCartTaxBase, CommonServices.WorkContext.WorkingCurrency);
            decimal discount            = -processPaymentRequest.Discount;


            // Add discounts to PayPal order
            if (discount != 0)
            {
                cartItems.Add(new PaymentDetailsItemType()
                {
                    Name     = "Threadrock Discount",
                    Quantity = "1",
                    Amount   = new BasicAmountType() // this is the total discount
                    {
                        currencyID = PayPalHelper.GetPaypalCurrency(_currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId)),
                        Value      = discount.ToString("N", new CultureInfo("en-us"))
                    }
                });

                itemTotal += discount;
            }

            // get customer
            int customerId = Convert.ToInt32(CommonServices.WorkContext.CurrentCustomer.Id.ToString());
            var customer   = _customerService.GetCustomerById(customerId);

            if (!cart.IsRecurring())
            {
                //we don't apply gift cards for recurring products
                var giftCards = _giftCardService.GetActiveGiftCardsAppliedByCustomer(customer);
                if (giftCards != null)
                {
                    foreach (var gc in giftCards)
                    {
                        if (itemTotal > decimal.Zero)
                        {
                            decimal remainingAmount = gc.GetGiftCardRemainingAmount();
                            decimal amountCanBeUsed = decimal.Zero;
                            if (itemTotal > remainingAmount)
                            {
                                amountCanBeUsed = remainingAmount;
                            }
                            else
                            {
                                amountCanBeUsed = itemTotal - .01M;
                            }

                            decimal amountToSubtract = -amountCanBeUsed;

                            cartItems.Add(new PaymentDetailsItemType()
                            {
                                Name     = "Giftcard Applied",
                                Quantity = "1",
                                Amount   = new BasicAmountType()
                                {
                                    currencyID = PayPalHelper.GetPaypalCurrency(_currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId)),
                                    Value      = amountToSubtract.ToString("N", new CultureInfo("en-us"))
                                }
                            });

                            //reduce subtotal
                            itemTotal += amountToSubtract;
                        }
                    }
                }
            }

            // populate payment details
            var paymentDetails = new PaymentDetailsType
            {
                ItemTotal = new BasicAmountType
                {
                    Value      = Math.Round(itemTotal, 2).ToString("N", new CultureInfo("en-us")),
                    currencyID = PayPalHelper.GetPaypalCurrency(_currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId))
                },
                ShippingTotal = new BasicAmountType
                {
                    Value      = Math.Round(shippingTotal, 2).ToString("N", new CultureInfo("en-us")),
                    currencyID = PayPalHelper.GetPaypalCurrency(_currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId))
                },
                TaxTotal = new BasicAmountType
                {
                    Value      = Math.Round(shoppingCartTax, 2).ToString("N", new CultureInfo("en-us")),
                    currencyID = PayPalHelper.GetPaypalCurrency(_currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId))
                },
                OrderTotal = new BasicAmountType
                {
                    Value      = Math.Round(itemTotal + shoppingCartTax + shippingTotal, 2).ToString("N", new CultureInfo("en-us")),
                    currencyID = PayPalHelper.GetPaypalCurrency(_currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId))
                },
                Custom             = processPaymentRequest.OrderGuid.ToString(),
                ButtonSource       = SmartStoreVersion.CurrentFullVersion,
                PaymentAction      = PayPalHelper.GetPaymentAction(Settings),
                PaymentDetailsItem = cartItems.ToArray()
            };

            details.PaymentDetails = new[] { paymentDetails };
            //details.MaxAmount = new BasicAmountType()  // this is the per item cost
            //{
            //    currencyID = PaypalHelper.GetPaypalCurrency(_currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId)),
            //    Value = (decimal.Parse(paymentDetails.OrderTotal.Value) + 30).ToString()
            //};

            details.ShippingMethodSpecified = true;

            req.SetExpressCheckoutRequest.SetExpressCheckoutRequestDetails.Custom = processPaymentRequest.OrderGuid.ToString();
            req.SetExpressCheckoutRequest.SetExpressCheckoutRequestDetails        = details;

            using (var service = new PayPalAPIAASoapBinding())
            {
                service.Url = PayPalHelper.GetPaypalServiceUrl(Settings);
                service.RequesterCredentials = PayPalHelper.GetPaypalApiCredentials(Settings);
                result = service.SetExpressCheckout(req);
            }

            _httpContext.GetCheckoutState().CustomProperties.Add("PayPalExpressButtonUsed", true);

            return(result);
        }
Beispiel #31
0
        // ProcessCard() is used for Credit Card processing via Website Payments Pro,
        // just like other credit card gateways.
        // ProcessPaypal() is used for Express Checkout and PayPal payments.
        public override string ProcessCard(int OrderNumber, int CustomerID, decimal OrderTotal, bool useLiveTransactions, TransactionModeEnum TransactionMode, Address UseBillingAddress, string CardExtraCode, Address UseShippingAddress, string CAVV, string ECI, string XID, out string AVSResult, out string AuthorizationResult, out string AuthorizationCode, out string AuthorizationTransID, out string TransactionCommandOut, out string TransactionResponse)
        {
            String result = AppLogic.ro_OK;

            AuthorizationCode     = String.Empty;
            AuthorizationResult   = String.Empty;
            AuthorizationTransID  = String.Empty;
            AVSResult             = String.Empty;
            TransactionCommandOut = String.Empty;
            TransactionResponse   = String.Empty;
            try
            {
                // the request details object contains all payment details
                DoDirectPaymentRequestDetailsType RequestDetails = new DoDirectPaymentRequestDetailsType();

                // define the payment action to 'Sale'
                // (another option is 'Authorization', which would be followed later with a DoCapture API call)
                RequestDetails.PaymentAction = (PaymentActionCodeType)CommonLogic.IIF(AppLogic.TransactionModeIsAuthOnly(), (int)PaymentActionCodeType.Authorization, (int)PaymentActionCodeType.Sale);

                // define the total amount and currency for the transaction
                PaymentDetailsType PaymentDetails = new PaymentDetailsType();

                BasicAmountType totalAmount = new BasicAmountType();
                totalAmount.Value               = Localization.CurrencyStringForGatewayWithoutExchangeRate(OrderTotal);
                totalAmount.currencyID          = (CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), AppLogic.AppConfig("Localization.StoreCurrency"), true);
                PaymentDetails.OrderTotal       = totalAmount;
                PaymentDetails.InvoiceID        = OrderNumber.ToString();
                PaymentDetails.ButtonSource     = PayPal.BN + "_DP_US";
                PaymentDetails.OrderDescription = AppLogic.AppConfig("StoreName");

                // define the credit card to be used

                CreditCardDetailsType creditCard = new CreditCardDetailsType();
                creditCard.CreditCardNumber  = UseBillingAddress.CardNumber;
                creditCard.ExpMonth          = Localization.ParseUSInt(UseBillingAddress.CardExpirationMonth);
                creditCard.ExpYear           = Localization.ParseUSInt(UseBillingAddress.CardExpirationYear);
                creditCard.ExpMonthSpecified = true;
                creditCard.ExpYearSpecified  = true;
                creditCard.CVV2 = CardExtraCode;

                if (UseBillingAddress.CardType == "AmericanExpress")
                {
                    creditCard.CreditCardType = (CreditCardTypeType)Enum.Parse(typeof(CreditCardTypeType), "Amex", true);
                }
                else
                {
                    creditCard.CreditCardType = (CreditCardTypeType)Enum.Parse(typeof(CreditCardTypeType), UseBillingAddress.CardType, true);
                }
                creditCard.CreditCardTypeSpecified = true;

                PayerInfoType  cardHolder      = new PayerInfoType();
                PersonNameType oPersonNameType = new PersonNameType();
                oPersonNameType.FirstName  = UseBillingAddress.FirstName;
                oPersonNameType.LastName   = UseBillingAddress.LastName;
                oPersonNameType.MiddleName = String.Empty;
                oPersonNameType.Salutation = String.Empty;
                oPersonNameType.Suffix     = String.Empty;
                cardHolder.PayerName       = oPersonNameType;

                AddressType PayerAddress = new AddressType();
                PayerAddress.Street1          = UseBillingAddress.Address1;
                PayerAddress.CityName         = UseBillingAddress.City;
                PayerAddress.StateOrProvince  = UseBillingAddress.State;
                PayerAddress.PostalCode       = UseBillingAddress.Zip;
                PayerAddress.Country          = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), AppLogic.GetCountryTwoLetterISOCode(UseBillingAddress.Country), true);
                PayerAddress.CountrySpecified = true;

                if (UseShippingAddress != null)
                {
                    AddressType shippingAddress = new AddressType();
                    shippingAddress.Name             = (UseShippingAddress.FirstName + " " + UseShippingAddress.LastName).Trim();
                    shippingAddress.Street1          = UseShippingAddress.Address1;
                    shippingAddress.Street2          = UseShippingAddress.Address2 + CommonLogic.IIF(UseShippingAddress.Suite != "", " Ste " + UseShippingAddress.Suite, "");
                    shippingAddress.CityName         = UseShippingAddress.City;
                    shippingAddress.StateOrProvince  = UseShippingAddress.State;
                    shippingAddress.PostalCode       = UseShippingAddress.Zip;
                    shippingAddress.Country          = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), AppLogic.GetCountryTwoLetterISOCode(UseShippingAddress.Country), true);
                    shippingAddress.CountrySpecified = true;
                    PaymentDetails.ShipToAddress     = shippingAddress;
                }

                cardHolder.Address   = PayerAddress;
                creditCard.CardOwner = cardHolder;

                RequestDetails.CreditCard     = creditCard;
                RequestDetails.PaymentDetails = PaymentDetails;
                RequestDetails.IPAddress      = CommonLogic.CustomerIpAddress();            // cart.ThisCustomer.LastIPAddress;

                if (RequestDetails.IPAddress == "::1")
                {
                    RequestDetails.IPAddress = "127.0.0.1";
                }

                // instantiate the actual request object
                PaymentRequest         = new DoDirectPaymentRequestType();
                PaymentRequest.Version = API_VER;
                PaymentRequest.DoDirectPaymentRequestDetails = RequestDetails;
                DDPReq = new DoDirectPaymentReq();
                DDPReq.DoDirectPaymentRequest = PaymentRequest;

                DoDirectPaymentResponseType responseDetails = (DoDirectPaymentResponseType)IPayPal.DoDirectPayment(DDPReq);

                //if (LogToErrorTable)
                //{
                //    PayPalController.Log(XmlCommon.SerializeObject(DDPReq, DDPReq.GetType()), "DoDirectPayment Request");
                //    PayPalController.Log(XmlCommon.SerializeObject(responseDetails, responseDetails.GetType()), "DoDirectPayment Response");
                //}

                if (responseDetails != null && responseDetails.Ack.ToString().StartsWith("success", StringComparison.InvariantCultureIgnoreCase))
                {
                    AuthorizationTransID = CommonLogic.IIF(TransactionMode.ToString().ToLower() == AppLogic.ro_TXModeAuthOnly.ToLower(), "AUTH=", "CAPTURE=") + responseDetails.TransactionID.ToString();
                    AuthorizationCode    = responseDetails.CorrelationID;
                    AVSResult            = responseDetails.AVSCode;
                    result = AppLogic.ro_OK;
                    AuthorizationResult = responseDetails.Ack.ToString() + "|AVSCode=" + responseDetails.AVSCode.ToString() + "|CVV2Code=" + responseDetails.CVV2Code.ToString();
                }
                else
                {
                    if (responseDetails.Errors != null)
                    {
                        String Separator = String.Empty;
                        for (int ix = 0; ix < responseDetails.Errors.Length; ix++)
                        {
                            AuthorizationResult += Separator;
                            AuthorizationResult += responseDetails.Errors[ix].LongMessage;                            // record failed TX
                            TransactionResponse += Separator;
                            try
                            {
                                TransactionResponse += String.Format("|{0},{1},{2}|", responseDetails.Errors[ix].ShortMessage, responseDetails.Errors[ix].ErrorCode, responseDetails.Errors[ix].LongMessage);                                 // record failed TX
                            }
                            catch { }
                            Separator = ", ";
                        }
                    }
                    result = AuthorizationResult;
                    // just store something here, as there is no other way to get data out of this gateway about the failure for logging in failed transaction table
                }
            }
            catch
            {
                result = "Transaction Failed";
            }
            return(result);
        }
Beispiel #32
0
        private PaymentDetailsType CreatePayPalPaymentDetails(IInvoice invoice, ProcessorArgumentCollection args = null)
        {
            string articleBySkuPath = args.GetArticleBySkuPath(_settings.ArticleBySkuPath.IsEmpty() ? null : GetWebsiteUrl() + _settings.ArticleBySkuPath);
            var    currencyCodeType = PayPalCurrency(invoice.CurrencyCode());
            var    currencyDecimals = CurrencyDecimals(currencyCodeType);

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

            var paymentDetailItems = new List <PaymentDetailsItemType>();

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

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

            return(paymentDetails);
        }