/// <summary> /// Sets paypal express checkout /// </summary> /// <param name="OrderTotal">Order total</param> /// <param name="ReturnURL">Return URL</param> /// <param name="CancelURL">Cancel URL</param> /// <returns>Express checkout URL</returns> public string SetExpressCheckout(decimal OrderTotal, string ReturnURL, string CancelURL) { InitSettings(); TransactMode transactionMode = GetCurrentTransactionMode(); SetExpressCheckoutReq req = new SetExpressCheckoutReq(); req.SetExpressCheckoutRequest = new SetExpressCheckoutRequestType(); req.SetExpressCheckoutRequest.Version = this.APIVersion; SetExpressCheckoutRequestDetailsType details = new SetExpressCheckoutRequestDetailsType(); req.SetExpressCheckoutRequest.SetExpressCheckoutRequestDetails = details; if (transactionMode == TransactMode.Authorize) { details.PaymentAction = PaymentActionCodeType.Authorization; } else { details.PaymentAction = PaymentActionCodeType.Sale; } details.PaymentActionSpecified = true; details.OrderTotal = new BasicAmountType(); details.OrderTotal.Value = OrderTotal.ToString("N", new CultureInfo("en-us")); details.OrderTotal.currencyID = PaypalHelper.GetPaypalCurrency(CurrencyManager.PrimaryStoreCurrency); details.ReturnURL = ReturnURL; details.CancelURL = CancelURL; SetExpressCheckoutResponseType response = service2.SetExpressCheckout(req); string error; if (PaypalHelper.CheckSuccess(response, out error)) { return(GetPaypalUrl(response.Token)); } throw new NopException(error); }
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); }
public static string StartEC(ShoppingCart cart, bool boolBypassOrderReview, IDictionary <string, string> checkoutOptions) { var payPalRefund = new PayPalAPISoapBinding(); var payPalBinding = new PayPalAPIAASoapBinding(); var redirectUrl = new StringBuilder(); var ecOrderTotal = new BasicAmountType(); var request = new SetExpressCheckoutReq(); var requestType = new SetExpressCheckoutRequestType(); var requestDetails = new SetExpressCheckoutRequestDetailsType(); var response = new SetExpressCheckoutResponseType(); var result = string.Empty; var urlHelper = DependencyResolver.Current.GetService <UrlHelper>(); //Express checkout GetPaypalRequirements(out payPalRefund, out payPalBinding); ecOrderTotal.Value = Localization.CurrencyStringForGatewayWithoutExchangeRate(cart.Total(true)); if (cart.HasRecurringComponents() && AppLogic.AppConfigBool("Recurring.UseGatewayInternalBilling")) { //Have to send extra details on the SetExpressCheckoutReq or the token will be invalid for creating a recurring profile later var recurringAgreement = new BillingAgreementDetailsType(); var recurringAgreementList = new List <BillingAgreementDetailsType>(); recurringAgreement.BillingType = BillingCodeType.RecurringPayments; recurringAgreement.BillingAgreementDescription = "Recurring order created on " + System.DateTime.Now.ToShortDateString() + " from " + AppLogic.AppConfig("StoreName"); recurringAgreementList.Add(recurringAgreement); requestDetails.BillingAgreementDetails = recurringAgreementList.ToArray(); } request.SetExpressCheckoutRequest = requestType; requestType.SetExpressCheckoutRequestDetails = requestDetails; ecOrderTotal.currencyID = (CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), AppLogic.AppConfig("Localization.StoreCurrency"), true); requestDetails.OrderTotal = ecOrderTotal; if (AppLogic.AppConfigBool("PayPal.RequireConfirmedAddress")) { requestDetails.ReqConfirmShipping = "1"; } else { requestDetails.ReqConfirmShipping = "0"; } requestDetails.ReturnURL = string.Format("{0}{1}", AppLogic.GetStoreHTTPLocation( useSsl: true, includeScriptLocation: true, noVirtualNoSlash: true), urlHelper.Action( actionName: ActionNames.PayPalExpressReturn, controllerName: ControllerNames.PayPalExpress)); if (boolBypassOrderReview) { requestDetails.ReturnURL = string.Format("{0}?BypassOrderReview=true", requestDetails.ReturnURL); } requestDetails.CancelURL = string.Format("{0}{1}", AppLogic.GetStoreHTTPLocation( useSsl: true, includeScriptLocation: true, noVirtualNoSlash: true), urlHelper.Action( actionName: ActionNames.Index, controllerName: ControllerNames.Checkout)); requestDetails.LocaleCode = AppLogic.AppConfig("PayPal.DefaultLocaleCode"); requestDetails.PaymentAction = PaymentActionCodeType.Authorization; if (AppLogic.TransactionModeIsAuthCapture() || AppLogic.AppConfigBool("PayPal.ForceCapture") || PayPalController.GetAppropriateExpressType() == ExpressAPIType.PayPalAcceleratedBording) { requestDetails.PaymentAction = PaymentActionCodeType.Sale; } requestDetails.SolutionType = SolutionTypeType.Sole; requestDetails.PaymentActionSpecified = true; requestType.Version = API_VER; if (!string.IsNullOrWhiteSpace(AppLogic.AppConfig("PayPal.Express.PageStyle"))) { requestDetails.PageStyle = AppLogic.AppConfig("PayPal.Express.PageStyle").Trim(); } if (!string.IsNullOrWhiteSpace(AppLogic.AppConfig("PayPal.Express.HeaderImage"))) { requestDetails.cppheaderimage = AppLogic.AppConfig("PayPal.Express.HeaderImage").Trim(); } if (!string.IsNullOrWhiteSpace(AppLogic.AppConfig("PayPal.Express.HeaderBackColor"))) { requestDetails.cppheaderbackcolor = AppLogic.AppConfig("PayPal.Express.HeaderBackColor").Trim(); } if (!string.IsNullOrWhiteSpace(AppLogic.AppConfig("PayPal.Express.HeaderBorderColor"))) { requestDetails.cppheaderbordercolor = AppLogic.AppConfig("PayPal.Express.HeaderBorderColor").Trim(); } if (!string.IsNullOrWhiteSpace(AppLogic.AppConfig("PayPal.Express.PayFlowColor"))) { requestDetails.cpppayflowcolor = AppLogic.AppConfig("PayPal.Express.PayFlowColor").Trim(); } if (checkoutOptions != null && checkoutOptions.ContainsKey("UserSelectedFundingSource") && checkoutOptions["UserSelectedFundingSource"] == "BML") { var fundingSourceDetails = new FundingSourceDetailsType(); fundingSourceDetails.AllowPushFunding = "0"; fundingSourceDetails.UserSelectedFundingSource = UserSelectedFundingSourceType.BML; fundingSourceDetails.UserSelectedFundingSourceSpecified = true; requestDetails.FundingSourceDetails = fundingSourceDetails; } try { response = payPalBinding.SetExpressCheckout(request); if (response.Ack.ToString().StartsWith("success", StringComparison.InvariantCultureIgnoreCase)) { result = AppLogic.ro_OK; } else { if (response.Errors != null) { bool first = true; for (int ix = 0; ix < response.Errors.Length; ix++) { if (!first) { result += ", "; } result += "Error: [" + response.Errors[ix].ErrorCode + "] " + response.Errors[ix].LongMessage; first = false; } } } } catch (Exception) { result = "Failed to start PayPal Express Checkout! Please try another payment method."; } if (result == AppLogic.ro_OK) { var useIntegratedCheckout = AppLogic.AppConfigBool("PayPal.Express.UseIntegratedCheckout"); if (AppLogic.AppConfigBool("UseLiveTransactions") == true) { redirectUrl.Append(useIntegratedCheckout ? AppLogic.AppConfig("PayPal.Express.IntegratedCheckout.LiveURL") : AppLogic.AppConfig("PayPal.Express.LiveURL")); } else { redirectUrl.Append(useIntegratedCheckout ? AppLogic.AppConfig("PayPal.Express.IntegratedCheckout.SandboxURL") : AppLogic.AppConfig("PayPal.Express.SandboxURL")); } redirectUrl.Append(useIntegratedCheckout ? "?token=" : "?cmd=_express-checkout&token="); redirectUrl.Append(response.Token); if (boolBypassOrderReview) { redirectUrl.Append("&useraction=commit"); } // Set active payment method to PayPalExpress DB.ExecuteSQL(string.Format("UPDATE Address SET PaymentMethodLastUsed={0} WHERE AddressID={1}", DB.SQuote(AppLogic.ro_PMPayPalExpress), cart.ThisCustomer.PrimaryBillingAddressID)); SetECFaultRedirect(cart.ThisCustomer, redirectUrl.ToString()); } else { var error = new ErrorMessage(HttpUtility.HtmlEncode(result)); redirectUrl.Append(urlHelper.BuildCheckoutLink(error.MessageId)); } return(redirectUrl.ToString()); }