private PaypalResponse ProcessResponse(SetExpressCheckoutResponseType setECResponse) { PaypalResponse responseObject = new PaypalResponse(); responseObject.ApiStatus = setECResponse.Ack.ToString(); if (setECResponse.Ack.Equals(AckCodeType.FAILURE) || (setECResponse.Errors != null && setECResponse.Errors.Count > 0)) { responseObject.ResponseError = setECResponse.Errors; responseObject.ResponseRedirectURL = null; responseObject.CorrelationID = setECResponse.CorrelationID; responseObject.Timestamp = setECResponse.Timestamp; responseObject.ACK = setECResponse.Ack.ToString(); //Todo Log Error to database return(responseObject); } else { responseObject.CorrelationID = setECResponse.CorrelationID; responseObject.Timestamp = setECResponse.Timestamp; responseObject.ACK = responseObject.ACK = setECResponse.Ack.ToString(); responseObject.ResponseError = null; responseObject.ECToken = setECResponse.Token; responseObject.ResponseRedirectURL = System.Configuration.ConfigurationManager.AppSettings["RedirectURL"] + "_express-checkout&token=" + setECResponse.Token; //Log to Database return(responseObject); } }
public void SavePayPalTransactionStartTest() { string customerId = "someCustomerId"; string prodId = "someProdId"; var response = new SetExpressCheckoutResponseType() { Ack = AckCodeType.CustomCode, Any = new XmlDocument().CreateElement("someXmlElement"), Build = "someBuild", CorrelationID = "someCorrelationId", Errors = new []{ new ErrorType { ErrorCode = "someErrorCode", ErrorParameters = new []{ new ErrorParameterType { ParamID = "someParamId", Value = "someValue" }}, LongMessage = "someLongMsg", SeverityCode = SeverityCodeType.CustomCode, ShortMessage = "someShortMsg" }}, Timestamp = new DateTime(), TimestampSpecified = true, Token = "someToken", Version = "someVersion" }; var ppProcessor = new PayPalProcessorAccessor(); ppProcessor.SavePayPalTransactionStart(customerId, prodId, response); //verify saved var ds = GetTable("PayPalBeginExpressCheckout"); Assert.IsTrue(isObjectSaved(customerId, prodId, response, ds)); }
protected void Submit_Click(object sender, EventArgs e) { // Create request object SetExpressCheckoutRequestType request = new SetExpressCheckoutRequestType(); populateRequestObject(request); // Invoke the API SetExpressCheckoutReq wrapper = new SetExpressCheckoutReq(); wrapper.SetExpressCheckoutRequest = request; // Configuration map containing signature credentials and other required configuration. // For a full list of configuration parameters refer in wiki page // [https://github.com/paypal/sdk-core-dotnet/wiki/SDK-Configuration-Parameters] Dictionary <string, string> configurationMap = Configuration.GetAcctAndConfig(); // Create the PayPalAPIInterfaceServiceService service object to make the API call PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(configurationMap); // # API call // Invoke the SetExpressCheckout method in service wrapper object SetExpressCheckoutResponseType setECResponse = service.SetExpressCheckout(wrapper); // Check for API return status HttpContext CurrContext = HttpContext.Current; CurrContext.Items.Add("paymentDetails", request.SetExpressCheckoutRequestDetails.PaymentDetails); setKeyResponseObjects(service, setECResponse); }
public override void PreRedirect(FinancialGateway financialGateway, PaymentInfo paymentInfo, List <GatewayAccountItem> selectedAccounts, out string errorMessage) { // Create request object SetExpressCheckoutRequestType request = populateRequestObject(financialGateway, paymentInfo, selectedAccounts); // Invoke the API SetExpressCheckoutReq wrapper = new SetExpressCheckoutReq(); wrapper.SetExpressCheckoutRequest = request; // Create the PayPalAPIInterfaceServiceService service object to make the API call PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(GetCredentials(financialGateway)); // # API call // Invoke the SetExpressCheckout method in service wrapper object SetExpressCheckoutResponseType setECResponse = service.SetExpressCheckout(wrapper); // Check for API return status String url = financialGateway.GetAttributeValue("PayPalURL") + "_express-checkout&token=" + setECResponse.Token; mRedirectUrl = url; errorMessage = string.Empty; return; }
// A helper method used by APIResponse.aspx that returns select response parameters // of interest. private void setKeyResponseObjects(PayPalAPIInterfaceServiceService service, SetExpressCheckoutResponseType setECResponse) { Dictionary <string, string> keyResponseParameters = new Dictionary <string, string>(); keyResponseParameters.Add("API Status", setECResponse.Ack.ToString()); HttpContext CurrContext = HttpContext.Current; if (setECResponse.Ack.Equals(AckCodeType.FAILURE) || (setECResponse.Errors != null && setECResponse.Errors.Count > 0)) { CurrContext.Items.Add("Response_error", setECResponse.Errors); CurrContext.Items.Add("Response_redirectURL", null); } else { CurrContext.Items.Add("Response_error", null); keyResponseParameters.Add("EC token", setECResponse.Token); CurrContext.Items.Add("Response_redirectURL", ConfigManager.Instance.GetProperty("paypalUrl") + "_express-checkout&token=" + setECResponse.Token); } CurrContext.Items.Add("Response_keyResponseObject", keyResponseParameters); CurrContext.Items.Add("Response_apiName", "SetExpressCheckout"); CurrContext.Items.Add("Response_requestPayload", service.getLastRequest()); CurrContext.Items.Add("Response_responsePayload", service.getLastResponse()); Server.Transfer("../APIResponse.aspx"); }
public ActionResult BuyProduct(int?productId) { if (!productId.HasValue) { return(RedirectToAction("PayPalCancel")); } Order order = PayPalHelper.CreateOrder(productId.Value); if (order == null) { return(RedirectToAction("PayPalCancel")); } string domain = PayPalHelper.GetDomainName(Request); var returnURL = domain + "/Payment/PaymentDetails"; var cancelURL = domain + "/Payment/PaypalCancel"; SetExpressCheckoutReq request = PayPalHelper.GetSetExpressCheckoutReq(order, returnURL, cancelURL); CustomSecurityHeaderType credentials = PayPalHelper.GetPayPalCredentials(); PayPalAPIAAInterfaceClient client = new PayPalAPIAAInterfaceClient(); SetExpressCheckoutResponseType response = client.SetExpressCheckout(ref credentials, request); if (response.Errors != null && response.Errors.Length > 0) { throw new Exception("Exception occured when calling PayPal: " + response.Errors[0].LongMessage); } string redirectUrl = string.Format("{0}?cmd=_express-checkout&token={1}", PayPalHelper.GetPaypalRequestUrl(), response.Token); return(Redirect(redirectUrl)); }
/// <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 void SetExpressCheckout() { SetExpressCheckoutSample sample = new SetExpressCheckoutSample(); SetExpressCheckoutResponseType responseSetExpressCheckoutResponseType = sample.SetExpressCheckoutAPIOperation(); Assert.IsNotNull(responseSetExpressCheckoutResponseType); Assert.AreEqual(responseSetExpressCheckoutResponseType.Ack.ToString().ToUpper(), "SUCCESS"); Assert.IsNotNull(responseSetExpressCheckoutResponseType.Token); }
public static StartPayPalPaymentResponse ToResponse(this SetExpressCheckoutResponseType instance) { return(new StartPayPalPaymentResponse { Token = instance.Token, Status = instance.Ack.GetValueOrDefault().ToString(), Errors = instance .Errors .Select(x => x.ToPaypalError()) .ToList() }); }
public PaypalResponse SetExpressCheckout(string userpackageID, string email, string orderDescription, string billingAgreementText, string LogoURL, string brandName, double itemTotalAmount, string PlanName, double planAmount, string planDescription) { // Create request object SetExpressCheckoutRequestType request = new SetExpressCheckoutRequestType(); PopulateRequestObject(request, email, orderDescription, billingAgreementText, LogoURL, brandName, itemTotalAmount, PlanName, planAmount, planDescription); // Invoke the API SetExpressCheckoutReq wrapper = new SetExpressCheckoutReq(); wrapper.SetExpressCheckoutRequest = request; // Configuration map containing signature credentials and other required configuration. // For a full list of configuration parameters refer in wiki page // [https://github.com/paypal/sdk-core-dotnet/wiki/SDK-Configuration-Parameters] Dictionary <string, string> configurationMap = Configuration.GetAcctAndConfig(); // Create the PayPalAPIInterfaceServiceService service object to make the API call PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(configurationMap); string fileName = DateTime.Now.ToString("Request_" + userpackageID + "_" + "yyyy-MM-dd-HH-mm", CultureInfo.InvariantCulture) + ".txt"; string baseDirectory = AppDomain.CurrentDomain.BaseDirectory; string path = "~/App_Data/"; path = path.Replace("~/", "").TrimStart('/').Replace('/', '\\'); path = path + fileName; string reqString = string.Empty; reqString = JsonConvert.SerializeObject(wrapper); string text = "Paypal request: " + DateTime.Now.ToString(); text += Environment.NewLine + Environment.NewLine + "request string: " + reqString; System.IO.File.WriteAllText(Path.Combine(baseDirectory, path), text); // # API call // Invoke the SetExpressCheckout method in service wrapper object SetExpressCheckoutResponseType setECResponse = service.SetExpressCheckout(wrapper); string responseString = string.Empty; responseString = JsonConvert.SerializeObject(setECResponse); PaypalResponse responsePaypal = new PaypalResponse(); responsePaypal = ProcessResponse(setECResponse); return(responsePaypal); }
public SetExpressCheckoutResponse GetSetExpressCheckoutRedirectUrl(CartModel cart) { SetExpressCheckoutResponseType setExpressCheckoutResponseType = _payPalInterfaceService.SetExpressCheckout(cart); return(setExpressCheckoutResponseType .HandleResponse <SetExpressCheckoutResponseType, SetExpressCheckoutResponse>( (type, response) => { response.Url = _payPalUrlService.GetExpressCheckoutRedirectUrl(type.Token); _cartManager.SetPayPalExpressToken(type.Token); }, (type, response) => { response.Errors.Add("An error occurred"); type.RaiseErrors(); })); }
protected void Submit_Click(object sender, EventArgs e) { // Create request object SetExpressCheckoutRequestType request = new SetExpressCheckoutRequestType(); populateRequestObject(request); // Invoke the API SetExpressCheckoutReq wrapper = new SetExpressCheckoutReq(); wrapper.SetExpressCheckoutRequest = request; PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(); SetExpressCheckoutResponseType setECResponse = service.SetExpressCheckout(wrapper); // Check for API return status HttpContext CurrContext = HttpContext.Current; CurrContext.Items.Add("paymentDetails", request.SetExpressCheckoutRequestDetails.PaymentDetails); setKeyResponseObjects(service, setECResponse); }
public override ProcessPaymentResult ProcessPayment(ProcessPaymentEvaluationContext context) { var retVal = new ProcessPaymentResult(); if (!(context.Store != null && !string.IsNullOrEmpty(context.Store.Url))) { throw new NullReferenceException("no store with this id"); } var config = GetConfigMap(context.Store); var url = context.Store.Url; var request = CreatePaypalRequest(context.Order, context.Store, context.Payment); var service = new PayPalAPIInterfaceServiceService(config); SetExpressCheckoutResponseType setEcResponse = null; try { setEcResponse = service.SetExpressCheckout(request); CheckResponse(setEcResponse); retVal.IsSuccess = true; retVal.NewPaymentStatus = PaymentStatus.Pending; retVal.OuterId = setEcResponse.Token; var redirectBaseUrl = GetBaseUrl(Mode); retVal.RedirectUrl = string.Format(redirectBaseUrl, retVal.OuterId); } catch (System.Exception ex) { retVal.Error = ex.Message; } return(retVal); }
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); }
// # SetExpressCheckout API Operation // The SetExpressCheckout API operation initiates an Express Checkout transaction. public SetExpressCheckoutResponseType SetExpressCheckoutAPIOperation() { // Create the SetExpressCheckoutResponseType object SetExpressCheckoutResponseType responseSetExpressCheckoutResponseType = new SetExpressCheckoutResponseType(); try { // # SetExpressCheckoutReq SetExpressCheckoutRequestDetailsType setExpressCheckoutRequestDetails = new SetExpressCheckoutRequestDetailsType(); // URL to which the buyer's browser is returned after choosing to pay // with PayPal. For digital goods, you must add JavaScript to this page // to close the in-context experience. // `Note: // PayPal recommends that the value be the final review page on which // the buyer confirms the order and payment or billing agreement.` setExpressCheckoutRequestDetails.ReturnURL = "http://localhost/return"; // URL to which the buyer is returned if the buyer does not approve the // use of PayPal to pay you. For digital goods, you must add JavaScript // to this page to close the in-context experience. // `Note: // PayPal recommends that the value be the original page on which the // buyer chose to pay with PayPal or establish a billing agreement.` setExpressCheckoutRequestDetails.CancelURL = "http://localhost/cancel"; // # Payment Information // list of information about the payment List <PaymentDetailsType> paymentDetailsList = new List <PaymentDetailsType>(); // information about the first payment PaymentDetailsType paymentDetails1 = new PaymentDetailsType(); // Total cost of the transaction to the buyer. If shipping cost and tax // charges are known, include them in this value. If not, this value // should be the current sub-total of the order. // // If the transaction includes one or more one-time purchases, this field must be equal to // the sum of the purchases. Set this field to 0 if the transaction does // not include a one-time purchase such as when you set up a billing // agreement for a recurring payment that is not immediately charged. // When the field is set to 0, purchase-specific fields are ignored. // // * `Currency Code` - You must set the currencyID attribute to one of the // 3-character currency codes for any of the supported PayPal // currencies. // * `Amount` BasicAmountType orderTotal1 = new BasicAmountType(CurrencyCodeType.USD, "2.00"); paymentDetails1.OrderTotal = orderTotal1; // How you want to obtain payment. When implementing parallel payments, // this field is required and must be set to `Order`. When implementing // digital goods, this field is required and must be set to `Sale`. If the // transaction does not include a one-time purchase, this field is // ignored. It is one of the following values: // // * `Sale` - This is a final sale for which you are requesting payment // (default). // * `Authorization` - This payment is a basic authorization subject to // settlement with PayPal Authorization and Capture. // * `Order` - This payment is an order authorization subject to // settlement with PayPal Authorization and Capture. // `Note: // You cannot set this field to Sale in SetExpressCheckout request and // then change the value to Authorization or Order in the // DoExpressCheckoutPayment request. If you set the field to // Authorization or Order in SetExpressCheckout, you may set the field // to Sale.` paymentDetails1.PaymentAction = PaymentActionCodeType.ORDER; // Unique identifier for the merchant. For parallel payments, this field // is required and must contain the Payer Id or the email address of the // merchant. SellerDetailsType sellerDetails1 = new SellerDetailsType(); sellerDetails1.PayPalAccountID = "*****@*****.**"; paymentDetails1.SellerDetails = sellerDetails1; // A unique identifier of the specific payment request, which is // required for parallel payments. paymentDetails1.PaymentRequestID = "PaymentRequest1"; // `Address` to which the order is shipped, which takes mandatory params: // // * `Street Name` // * `City` // * `State` // * `Country` // * `Postal Code` AddressType shipToAddress1 = new AddressType(); shipToAddress1.Street1 = "Ape Way"; shipToAddress1.CityName = "Austin"; shipToAddress1.StateOrProvince = "TX"; shipToAddress1.Country = CountryCodeType.US; shipToAddress1.PostalCode = "78750"; paymentDetails1.ShipToAddress = shipToAddress1; // IPN URL // * PayPal Instant Payment Notification is a call back system that is initiated when a transaction is completed // * The transaction related IPN variables will be received on the call back URL specified in the request // * The IPN variables have to be sent back to the PayPal system for validation, upon validation PayPal will send a response string "VERIFIED" or "INVALID" // * PayPal would continuously resend IPN if a wrong IPN is sent paymentDetails1.NotifyURL = "http://IPNhost"; // information about the second payment PaymentDetailsType paymentDetails2 = new PaymentDetailsType(); // Total cost of the transaction to the buyer. If shipping cost and tax // charges are known, include them in this value. If not, this value // should be the current sub-total of the order. // // If the transaction includes one or more one-time purchases, this field must be equal to // the sum of the purchases. Set this field to 0 if the transaction does // not include a one-time purchase such as when you set up a billing // agreement for a recurring payment that is not immediately charged. // When the field is set to 0, purchase-specific fields are ignored. // // * `Currency Code` - You must set the currencyID attribute to one of the // 3-character currency codes for any of the supported PayPal // currencies. // * `Amount` BasicAmountType orderTotal2 = new BasicAmountType(CurrencyCodeType.USD, "4.00"); paymentDetails2.OrderTotal = orderTotal2; // How you want to obtain payment. When implementing parallel payments, // this field is required and must be set to `Order`. When implementing // digital goods, this field is required and must be set to `Sale`. If the // transaction does not include a one-time purchase, this field is // ignored. It is one of the following values: // // * `Sale` - This is a final sale for which you are requesting payment // (default). // * `Authorization` - This payment is a basic authorization subject to // settlement with PayPal Authorization and Capture. // * `Order` - This payment is an order authorization subject to // settlement with PayPal Authorization and Capture. // `Note: // You cannot set this field to Sale in SetExpressCheckout request and // then change the value to Authorization or Order in the // DoExpressCheckoutPayment request. If you set the field to // Authorization or Order in SetExpressCheckout, you may set the field // to Sale.` paymentDetails2.PaymentAction = PaymentActionCodeType.ORDER; // Unique identifier for the merchant. For parallel payments, this field // is required and must contain the Payer Id or the email address of the // merchant. SellerDetailsType sellerDetails2 = new SellerDetailsType(); sellerDetails2.PayPalAccountID = "*****@*****.**"; paymentDetails2.SellerDetails = sellerDetails2; // A unique identifier of the specific payment request, which is // required for parallel payments. paymentDetails2.PaymentRequestID = "PaymentRequest2"; // IPN URL // * PayPal Instant Payment Notification is a call back system that is initiated when a transaction is completed // * The transaction related IPN variables will be received on the call back URL specified in the request // * The IPN variables have to be sent back to the PayPal system for validation, upon validation PayPal will send a response string "VERIFIED" or "INVALID" // * PayPal would continuously resend IPN if a wrong IPN is sent paymentDetails2.NotifyURL = "http://IPNhost"; // `Address` to which the order is shipped, which takes mandatory params: // // * `Street Name` // * `City` // * `State` // * `Country` // * `Postal Code` AddressType shipToAddress2 = new AddressType(); shipToAddress2.Street1 = "Ape Way"; shipToAddress2.CityName = "Austin"; shipToAddress2.StateOrProvince = "TX"; shipToAddress2.Country = CountryCodeType.US; shipToAddress2.PostalCode = "78750"; paymentDetails2.ShipToAddress = shipToAddress2; paymentDetailsList.Add(paymentDetails1); paymentDetailsList.Add(paymentDetails2); setExpressCheckoutRequestDetails.PaymentDetails = paymentDetailsList; SetExpressCheckoutReq setExpressCheckout = new SetExpressCheckoutReq(); SetExpressCheckoutRequestType setExpressCheckoutRequest = new SetExpressCheckoutRequestType(setExpressCheckoutRequestDetails); setExpressCheckout.SetExpressCheckoutRequest = setExpressCheckoutRequest; // Create the service wrapper object to make the API call PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(); // # API call // Invoke the SetExpressCheckout method in service wrapper object responseSetExpressCheckoutResponseType = service.SetExpressCheckout(setExpressCheckout); if (responseSetExpressCheckoutResponseType != null) { // Response envelope acknowledgement string acknowledgement = "SetExpressCheckout API Operation - "; acknowledgement += responseSetExpressCheckoutResponseType.Ack.ToString(); logger.Info(acknowledgement + "\n"); Console.WriteLine(acknowledgement + "\n"); // # Success values if (responseSetExpressCheckoutResponseType.Ack.ToString().Trim().ToUpper().Equals("SUCCESS")) { // # Redirecting to PayPal for authorization // Once you get the "Success" response, needs to authorise the // transaction by making buyer to login into PayPal. For that, // need to construct redirect url using EC token from response. // For example, // `redirectURL="https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token="+setExpressCheckoutResponse.Token;` // Express Checkout Token logger.Info("Express Checkout Token : " + responseSetExpressCheckoutResponseType.Token + "\n"); Console.WriteLine("Express Checkout Token : " + responseSetExpressCheckoutResponseType.Token + "\n"); } // # Error Values else { List <ErrorType> errorMessages = responseSetExpressCheckoutResponseType.Errors; foreach (ErrorType error in errorMessages) { logger.Debug("API Error Message : " + error.LongMessage); Console.WriteLine("API Error Message : " + error.LongMessage + "\n"); } } } } // # Exception log catch (System.Exception ex) { // Log the exception message logger.Debug("Error Message : " + ex.Message); Console.WriteLine("Error Message : " + ex.Message); } return(responseSetExpressCheckoutResponseType); }
public ProcessPaymentResult ProcessPayment(ProcessPaymentRequest processPaymentRequest) { var paymentResponse = new ProcessPaymentResult(); var req = new SetExpressCheckoutReq(); req.SetExpressCheckoutRequest = new SetExpressCheckoutRequestType { Version = Settings.Version }; var details = new SetExpressCheckoutRequestDetailsType(); req.SetExpressCheckoutRequest.SetExpressCheckoutRequestDetails = details; var currencyCode = (CurrencyCodeType)Utils.GetEnumValueByName(typeof(CurrencyCodeType), processPaymentRequest.CurrencyCode); var oPayDetail = new PaymentDetailsType(); oPayDetail.OrderTotal = new BasicAmountType(); oPayDetail.OrderTotal.Value = (processPaymentRequest.OrderTotal).ToString("N", new CultureInfo("en-gb")); oPayDetail.OrderTotal.currencyID = currencyCode; oPayDetail.ShippingMethod = ShippingServiceCodeType.ShippingMethodStandard; oPayDetail.ItemTotal = new BasicAmountType(); oPayDetail.ItemTotal.Value = (processPaymentRequest.OrderTotal - processPaymentRequest.Order.ShippingCharge.Raw.WithTax).ToString("N", new CultureInfo("en-gb")); oPayDetail.ItemTotal.currencyID = currencyCode; oPayDetail.ShippingMethodSpecified = true; oPayDetail.ShippingTotal = new BasicAmountType(); oPayDetail.ShippingTotal.Value = processPaymentRequest.Order.ShippingCharge.Raw.WithTax.ToString("N", new CultureInfo("en-gb")); oPayDetail.ShippingTotal.currencyID = currencyCode; oPayDetail.OrderDescription = "Order Total:" + processPaymentRequest.OrderTotal.ToString(); oPayDetail.PaymentActionSpecified = true; oPayDetail.PaymentAction = PaymentActionCodeType.Authorization; oPayDetail.InvoiceID = processPaymentRequest.OrderId; var oItems = new List <PaymentDetailsItemType>(); int i = 1; foreach (var itm in processPaymentRequest.Order.Items) { var oItem = new PaymentDetailsItemType { Number = i.ToString(CultureInfo.InvariantCulture) }; oItem.Name = itm.StockCode; oItem.Description = itm.Name; oItem.Amount = new BasicAmountType(); decimal itmPrice = itm.Price.Raw.WithTax; oItem.Amount.Value = itmPrice.ToString("N", new CultureInfo("en-gb")); oItem.Amount.currencyID = currencyCode; oItem.Quantity = itm.Qty.ToString(CultureInfo.InvariantCulture); i = i + 1; oItems.Add(oItem); } if (processPaymentRequest.Order.Discount.Raw.WithTax > 0) { var odiscountItem = new PaymentDetailsItemType { Number = i.ToString(CultureInfo.InvariantCulture) }; odiscountItem.Name = "Discount"; odiscountItem.Description = "Discount"; odiscountItem.Amount = new BasicAmountType(); decimal itmPrice = -processPaymentRequest.Order.Discount.Raw.WithTax; odiscountItem.Amount.Value = itmPrice.ToString("N", new CultureInfo("en-GB")); odiscountItem.Amount.currencyID = currencyCode; odiscountItem.Quantity = (1).ToString(CultureInfo.InvariantCulture); oItems.Add(odiscountItem); } if (processPaymentRequest.Order.GrandTotal.Raw.WithTax > processPaymentRequest.OrderTotal) { var odiscountItem = new PaymentDetailsItemType { Number = i.ToString(CultureInfo.InvariantCulture) }; odiscountItem.Name = "Paid By Other Source"; odiscountItem.Description = "Other Source"; odiscountItem.Amount = new BasicAmountType(); decimal itmPrice = -(processPaymentRequest.Order.GrandTotal.Raw.WithTax - processPaymentRequest.OrderTotal); odiscountItem.Amount.Value = itmPrice.ToString("N", new CultureInfo("en-GB")); odiscountItem.Amount.currencyID = currencyCode; odiscountItem.Quantity = (1).ToString(CultureInfo.InvariantCulture); oItems.Add(odiscountItem); } oPayDetail.PaymentDetailsItem = oItems.ToArray(); PaymentDetailsType[] oPayDetails = { oPayDetail }; details.PaymentDetails = oPayDetails; details.ReturnURL = Settings.NotificationUrl + "?oid=" + processPaymentRequest.OrderId + "&payid=" + processPaymentRequest.PaymentId; details.CancelURL = Settings.CancelUrl + "/" + processPaymentRequest.BasketId; System.Net.ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); var credentials = PaypalSecurityHeader(); SetExpressCheckoutResponseType response = _paypalService2.SetExpressCheckout(ref credentials, req); if (response.Ack == AckCodeType.Success) { paymentResponse.AuthorizationTransactionUrl = GetPaypalUrl(response.Token); paymentResponse.UseAuthUrlToRedirect = true; } else { foreach (var er in response.Errors) { paymentResponse.AddError(er.ErrorCode + " : " + er.ShortMessage); } } return(paymentResponse); }
private ActionResult Processing_PayPal(int claim, PaymentMode payment) { if (payment == null) { throw new System.ArgumentNullException("payment"); } PaymentBeforeProcessingResult beforePaymentResult = BookingProvider.BeforePaymentProcessing(UrlLanguage.CurrentLanguage, payment.paymentparam); if (beforePaymentResult == null) { throw new System.Exception("cannot get payment details"); } if (!beforePaymentResult.success) { throw new System.Exception("payment details fail"); } System.Collections.Generic.List <PaymentDetailsType> paymentDetails = new System.Collections.Generic.List <PaymentDetailsType>(); PaymentDetailsType paymentDetail = new PaymentDetailsType(); paymentDetail.AllowedPaymentMethod = new AllowedPaymentMethodType?(AllowedPaymentMethodType.ANYFUNDINGSOURCE); CurrencyCodeType currency = (CurrencyCodeType)EnumUtils.GetValue(payment.payrest.currency, typeof(CurrencyCodeType)); PaymentDetailsItemType paymentItem = new PaymentDetailsItemType(); paymentItem.Name = string.Format(PaymentStrings.ResourceManager.Get("PaymentForOrderFormat"), claim); paymentItem.Amount = new BasicAmountType(new CurrencyCodeType?(currency), payment.payrest.total.ToString("#.00", System.Globalization.NumberFormatInfo.InvariantInfo)); paymentItem.Quantity = new int?(1); paymentItem.ItemCategory = new ItemCategoryType?(ItemCategoryType.PHYSICAL); paymentItem.Description = string.Format("Booking #{0}", claim); paymentDetail.PaymentDetailsItem = new System.Collections.Generic.List <PaymentDetailsItemType> { paymentItem }; paymentDetail.PaymentAction = new PaymentActionCodeType?(PaymentActionCodeType.SALE); paymentDetail.OrderTotal = new BasicAmountType(paymentItem.Amount.currencyID, paymentItem.Amount.value); paymentDetails.Add(paymentDetail); SetExpressCheckoutRequestDetailsType ecDetails = new SetExpressCheckoutRequestDetailsType(); ecDetails.ReturnURL = new Uri(base.Request.BaseServerAddress(), base.Url.Action("processingresult", new { id = "paypal", success = true })).ToString(); ecDetails.CancelURL = new Uri(base.Request.BaseServerAddress(), base.Url.Action("processingresult", new { id = "paypal", success = false })).ToString(); ecDetails.NoShipping = "1"; ecDetails.AllowNote = "0"; ecDetails.SolutionType = new SolutionTypeType?(SolutionTypeType.SOLE); ecDetails.SurveyEnable = "0"; ecDetails.PaymentDetails = paymentDetails; ecDetails.InvoiceID = beforePaymentResult.invoiceNumber; SetExpressCheckoutRequestType request = new SetExpressCheckoutRequestType(); request.Version = "104.0"; request.SetExpressCheckoutRequestDetails = ecDetails; SetExpressCheckoutReq wrapper = new SetExpressCheckoutReq(); wrapper.SetExpressCheckoutRequest = request; System.Collections.Generic.Dictionary <string, string> config = PaymentController.PayPal_CreateConfig(); PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(config); SetExpressCheckoutResponseType setECResponse = service.SetExpressCheckout(wrapper); System.Collections.Generic.KeyValuePair <string, string> sandboxConfig = config.FirstOrDefault((System.Collections.Generic.KeyValuePair <string, string> m) => m.Key == "mode"); string sandboxServer = (sandboxConfig.Key != null && sandboxConfig.Value == "sandbox") ? ".sandbox" : ""; return(base.View("PaymentSystems\\PayPal", new ProcessingContext { Reservation = BookingProvider.GetReservationState(UrlLanguage.CurrentLanguage, claim), PaymentMode = payment, BeforePaymentResult = beforePaymentResult, RedirectUrl = string.Format("https://www{0}.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token={1}", sandboxServer, base.Server.UrlEncode(setECResponse.Token)) })); // return new RedirectResult(string.Format("https://www{0}.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token={1}", sandboxServer, base.Server.UrlEncode(setECResponse.Token))); }
protected void Page_Load(object sender, EventArgs e) { HttpContext CurrContext = HttpContext.Current; // Create the SetExpressCheckoutResponseType object SetExpressCheckoutResponseType responseSetExpressCheckoutResponseType = new SetExpressCheckoutResponseType(); try { // Check if the EC methos is shorcut or mark string ecMethod = ""; if (Request.QueryString["ExpressCheckoutMethod"] != null) { ecMethod = Request.QueryString["ExpressCheckoutMethod"]; } else if ((string)(Session["ExpressCheckoutMethod"]) != null) { ecMethod = (string)(Session["ExpressCheckoutMethod"]); } string item_name = ""; string item_id = ""; string item_desc = ""; string item_quantity = ""; string item_amount = ""; //string tax_amount = ""; //string shipping_amount = ""; //string handling_amount = ""; //string shipping_discount_amount = ""; //string insurance_amount = ""; string total_amount = ""; string currency_code = ""; string payment_type = ""; string roundedtotal = ""; string roundeditmamt = ""; // From Marck EC Page //string shipping_rate = ""; string first_name = ""; string last_name = ""; string street1 = ""; string street2 = ""; string city = ""; string state = ""; string postal_code = ""; string country = ""; string phone = ""; //Double new_total_rate = 0.00; AddressType shipToAddress = new AddressType(); if (ecMethod != null && ecMethod == "ShorcutExpressCheckout") { // Get parameters from index page (shorcut express checkout) item_name = Request.Form["item_name"]; item_id = Request.Form["item_id"]; item_desc = Request.Form["item_desc"]; item_quantity = Request.Form["item_quantity"]; item_amount = Request.Form["item_amount"]; total_amount = Request.Form["total_amount"]; currency_code = Request.Form["currency_code_type"]; payment_type = Request.Form["payment_type"]; Session["Total_Amount"] = total_amount; roundeditmamt = (Math.Round(double.Parse(item_amount), 2)).ToString(); roundedtotal = (Math.Round(double.Parse(total_amount), 2)).ToString(); } else if (ecMethod != null && ecMethod == "MarkExpressCheckout") { // Get parameters from mark ec page //shipping_rate = Request.Form["shipping_method"].ToString(); item_name = Request.Form["item_name"]; item_id = Request.Form["item_id"]; item_desc = Request.Form["item_desc"]; item_quantity = Request.Form["item_quantity"]; item_amount = Request.Form["item_amount"]; //tax_amount = Request.Form["tax_amount"]; //shipping_amount = Request.Form["shipping_amount"]; //handling_amount = Request.Form["handling_amount"]; //shipping_discount_amount = Request.Form["shipping_discount_amount"]; //insurance_amount = Request.Form["insurance_amount"]; total_amount = Request.Form["total_amount"]; currency_code = Request.Form["currency_code"]; payment_type = Request.Form["payment_type"]; first_name = Request.Form["FIRST_NAME"]; last_name = Request.Form["LAST_NAME"]; street1 = Request.Form["STREET_1"]; street2 = Request.Form["STREET_2"]; city = Request.Form["CITY"]; state = Request.Form["STATE"]; postal_code = Request.Form["POSTAL_CODE"]; country = Request.Form["COUNTRY"]; phone = Request.Form["PHONE"]; roundeditmamt = (Math.Round(double.Parse(item_amount), 2)).ToString(); roundedtotal = (Math.Round(double.Parse(total_amount), 2)).ToString(); // Set the details of new shipping address //shipToAddress.Name = first_name + " " + last_name; //shipToAddress.Street1 = street1; //if (!street2.Equals("")) //{ // shipToAddress.Street2 = street2; //} //shipToAddress.CityName = city; //shipToAddress.StateOrProvince = state; //string countrycode = country; //CountryCodeType countryCodeType = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), countrycode, true); //shipToAddress.Country = countryCodeType; //shipToAddress.PostalCode = postal_code; //if (!phone.Equals("")) //{ // shipToAddress.Phone = phone; //} //Double total_rate = Convert.ToDouble(total_amount); //Double old_shipping_rate = Convert.ToDouble(shipping_amount); //Double new_shipping_rate = Convert.ToDouble(shipping_rate); // Calculate new order total based on shipping method selected //new_total_rate = total_rate - old_shipping_rate + new_shipping_rate; //Session["Total_Amount"] = new_total_rate.ToString(); //total_amount = new_total_rate.ToString(); //shipping_amount = new_shipping_rate.ToString(); } Session["SellerEmail"] = SellerEmail; CurrencyCodeType currencyCode_Type = (CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), currency_code, true); Session["currency_code_type"] = currencyCode_Type; PaymentActionCodeType payment_ActionCode_Type = (PaymentActionCodeType)Enum.Parse(typeof(PaymentActionCodeType), payment_type, true); Session["payment_action_type"] = payment_ActionCode_Type; // SetExpressCheckoutRequestDetailsType object SetExpressCheckoutRequestDetailsType setExpressCheckoutRequestDetails = new SetExpressCheckoutRequestDetailsType(); // (Required) URL to which the buyer's browser is returned after choosing to pay with PayPal. setExpressCheckoutRequestDetails.ReturnURL = ReturnUrl; //(Required) URL to which the buyer is returned if the buyer does not approve the use of PayPal to pay you setExpressCheckoutRequestDetails.CancelURL = CancelUrl; // A URL to your logo image. Use a valid graphics format, such as .gif, .jpg, or .png setExpressCheckoutRequestDetails.cppLogoImage = LogoUrl; // To display the border in your principal identifying color, set the "cppCartBorderColor" parameter to the 6-digit hexadecimal value of that color // setExpressCheckoutRequestDetails.cppCartBorderColor = "0000CD"; //Item details PaymentDetailsItemType itemDetails = new PaymentDetailsItemType(); itemDetails.Name = item_name; itemDetails.Amount = new BasicAmountType(currencyCode_Type, roundeditmamt); itemDetails.Quantity = Convert.ToInt32(item_quantity); itemDetails.Description = item_desc; itemDetails.Number = item_id; //Add more items if necessary by using the class 'PaymentDetailsItemType' // Payment Information List <PaymentDetailsType> paymentDetailsList = new List <PaymentDetailsType>(); PaymentDetailsType paymentDetails = new PaymentDetailsType(); paymentDetails.PaymentAction = payment_ActionCode_Type; paymentDetails.ItemTotal = new BasicAmountType(currencyCode_Type, roundeditmamt);//item amount //paymentDetails.TaxTotal = new BasicAmountType(currencyCode_Type, tax_amount); //tax amount; //paymentDetails.ShippingTotal = new BasicAmountType(currencyCode_Type, shipping_amount); //shipping amount //paymentDetails.HandlingTotal = new BasicAmountType(currencyCode_Type, handling_amount); //handling amount //paymentDetails.ShippingDiscount = new BasicAmountType(currencyCode_Type, shipping_discount_amount); //shipping discount //paymentDetails.InsuranceTotal = new BasicAmountType(currencyCode_Type, insurance_amount); //insurance amount paymentDetails.OrderTotal = new BasicAmountType(currencyCode_Type, roundedtotal); // order total amount paymentDetails.PaymentDetailsItem.Add(itemDetails); // Unique identifier for the merchant. SellerDetailsType sellerDetails = new SellerDetailsType(); sellerDetails.PayPalAccountID = SellerEmail; paymentDetails.SellerDetails = sellerDetails; if (ecMethod != null && ecMethod == "MarkExpressCheckout") { paymentDetails.ShipToAddress = shipToAddress; } paymentDetailsList.Add(paymentDetails); setExpressCheckoutRequestDetails.PaymentDetails = paymentDetailsList; // Collect Shipping details if MARK express checkout SetExpressCheckoutReq setExpressCheckout = new SetExpressCheckoutReq(); SetExpressCheckoutRequestType setExpressCheckoutRequest = new SetExpressCheckoutRequestType(setExpressCheckoutRequestDetails); setExpressCheckout.SetExpressCheckoutRequest = setExpressCheckoutRequest; // Create the service wrapper object to make the API call PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(); // API call // Invoke the SetExpressCheckout method in service wrapper object responseSetExpressCheckoutResponseType = service.SetExpressCheckout(setExpressCheckout); if (responseSetExpressCheckoutResponseType != null) { // Response envelope acknowledgement string acknowledgement = "SetExpressCheckout API Operation - "; acknowledgement += responseSetExpressCheckoutResponseType.Ack.ToString(); //logger.Debug(acknowledgement + "\n"); System.Diagnostics.Debug.WriteLine(acknowledgement + "\n"); // # Success values if (responseSetExpressCheckoutResponseType.Ack.ToString().Trim().ToUpper().Equals("SUCCESS")) { // # Redirecting to PayPal for authorization // Once you get the "Success" response, needs to authorise the // transaction by making buyer to login into PayPal. For that, // need to construct redirect url using EC token from response. // Express Checkout Token string EcToken = responseSetExpressCheckoutResponseType.Token; //logger.Info("Express Checkout Token : " + EcToken + "\n"); System.Diagnostics.Debug.WriteLine("Express Checkout Token : " + EcToken + "\n"); // Store the express checkout token in session to be used in GetExpressCheckoutDetails & DoExpressCheckout API operations Session["EcToken"] = EcToken; Response.Redirect(RedirectUrl + HttpUtility.UrlEncode(EcToken), false); Context.ApplicationInstance.CompleteRequest(); } // # Error Values else { List <ErrorType> errorMessages = responseSetExpressCheckoutResponseType.Errors; string errorMessage = ""; foreach (ErrorType error in errorMessages) { //logger.Debug("API Error Message : " + error.LongMessage); System.Diagnostics.Debug.WriteLine("API Error Message : " + error.LongMessage + "\n"); errorMessage = errorMessage + error.LongMessage; } //Redirect to error page in case of any API errors CurrContext.Items.Add("APIErrorMessage", errorMessage); Server.Transfer("~/Response.aspx"); } } } catch (System.Exception ex) { // Log the exception message //logger.Debug("Error Message : " + ex.Message); System.Diagnostics.Debug.WriteLine("Error Message : " + ex.Message); } }
public new void SavePayPalTransactionStart(string customerId, string prodId, SetExpressCheckoutResponseType response) { base.SavePayPalTransactionBegin(customerId, prodId, response); }
public string GenerateOrder(List <ItemPayPal> items) { // Create request object SetExpressCheckoutRequestType request = new SetExpressCheckoutRequestType(); SetExpressCheckoutRequestDetailsType ecDetails = new SetExpressCheckoutRequestDetailsType(); /* Populate payment requestDetails. * SetExpressCheckout allows parallel payments of upto 10 payments. * This samples shows just one payment. */ PaymentDetailsType paymentDetails = new PaymentDetailsType(); ecDetails.PaymentDetails.Add(paymentDetails); // (Required) Total cost of the transaction to the buyer. If shipping cost and tax charges are known, include them in this value. If not, this value should be the current sub-total of the order. If the transaction includes one or more one-time purchases, this field must be equal to the sum of the purchases. Set this field to 0 if the transaction does not include a one-time purchase such as when you set up a billing agreement for a recurring payment that is not immediately charged. When the field is set to 0, purchase-specific fields are ignored. double orderTotal = 0.0; // Sum of cost of all items in this order. For digital goods, this field is required. double itemTotal = 0.0; CurrencyCodeType currency = CurrencyCodeType.MXN; //(Optional) Description of items the buyer is purchasing. // Note: // The value you specify is available only if the transaction includes a purchase. // This field is ignored if you set up a billing agreement for a recurring payment // that is not immediately charged. // Character length and limitations: 127 single-byte alphanumeric characters paymentDetails.OrderDescription = ""; // How you want to obtain payment. When implementing parallel payments, // this field is required and must be set to Order. // When implementing digital goods, this field is required and must be set to Sale. // If the transaction does not include a one-time purchase, this field is ignored. // It is one of the following values: // Sale – This is a final sale for which you are requesting payment (default). // Authorization – This payment is a basic authorization subject to settlement with PayPal Authorization and Capture. // Order – This payment is an order authorization subject to settlement with PayPal Authorization and Capture. paymentDetails.PaymentAction = PaymentActionCodeType.SALE; paymentDetails.ButtonSource = "PTSH"; foreach (ItemPayPal item in items) { PaymentDetailsItemType details = new PaymentDetailsItemType() { Name = item.Name, Amount = new BasicAmountType(currency, ((decimal)item.Price).ToString()), Quantity = item.Quantity }; // Indicates whether an item is digital or physical. For digital goods, this field is required and must be set to Digital. It is one of the following values: // 1.Digital // 2.Physical // This field is available since version 65.1. //itemDetails.ItemCategory = ItemCategoryType.DIGITAL; itemTotal += Convert.ToDouble(details.Amount.value) * details.Quantity.Value; //(Optional) Item description. // Character length and limitations: 127 single-byte characters // This field is introduced in version 53.0. details.Description = item.Description; paymentDetails.PaymentDetailsItem.Add(details); } orderTotal += itemTotal; paymentDetails.ItemTotal = new BasicAmountType(currency, itemTotal.ToString()); paymentDetails.OrderTotal = new BasicAmountType(currency, orderTotal.ToString()); paymentDetails.Custom = "9998"; paymentDetails.InvoiceID = null; ecDetails.ReturnURL = AppSettings.PayPalCallbackOk; ecDetails.CancelURL = AppSettings.PayPalCallbackFail; ecDetails.NoShipping = "1"; ecDetails.AllowNote = "0"; ecDetails.cppCartBorderColor = "0b5ba1"; // (Optional) URL for the image you want to appear at the top left of the payment page. The image has a maximum size of 750 pixels wide by 90 pixels high. PayPal recommends that you provide an image that is stored on a secure (https) server. If you do not specify an image, the business name displays. ecDetails.cppHeaderImage = ""; request.SetExpressCheckoutRequestDetails = ecDetails; /////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Invoke the API SetExpressCheckoutReq wrapper = new SetExpressCheckoutReq(); wrapper.SetExpressCheckoutRequest = request; System.Net.ServicePointManager.Expect100Continue = false; // Configuration map containing signature credentials and other required configuration. // For a full list of configuration parameters refer in wiki page // [https://github.com/paypal/sdk-core-dotnet/wiki/SDK-Configuration-Parameters] // Create the PayPalAPIInterfaceServiceService service object to make the API call PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(_payPalConfiguration); //wrapper.SetExpressCheckoutRequest.Version = "84.0"; // # API call // Invoke the SetExpressCheckout method in service wrapper object SetExpressCheckoutResponseType setECResponse = service.SetExpressCheckout(wrapper); // Check for API return status if (setECResponse.Ack.Equals(AckCodeType.FAILURE) || (setECResponse.Errors != null && setECResponse.Errors.Any())) { return(string.Empty); } return(setECResponse.Token); }
protected void SavePayPalTransactionBeginError(string customerId, string prodId, SetExpressCheckoutResponseType response) { string responseStr = JSONHelper.Serialize(response); Log.InfoFormat("Saving new-with-error PayPal transaction: customerId={0}, prodId={1}, response={2}", customerId, prodId, responseStr); try { using (var conn = new SqlConnection(Settings.Default.PayPalDb)) using (var cmd = conn.CreateCommand()) { cmd.CommandText = "INSERT INTO PayPalExpressCheckoutBeginError (CustomerId, ProdId, Token, Response)" + "VALUES (@customerId, @prodId, @token, @response)"; var customerIdParam = cmd.Parameters.Add("@customerId", SqlDbType.VarChar); customerIdParam.Value = customerId; var prodIdParam = cmd.Parameters.Add("@prodId", SqlDbType.VarChar); prodIdParam.Value = prodId; var tokenParam = cmd.Parameters.Add("@token", SqlDbType.VarChar); tokenParam.Value = response.Token; var responseParam = cmd.Parameters.Add("@response", SqlDbType.VarChar); responseParam.Value = responseStr; conn.Open(); int rows = cmd.ExecuteNonQuery(); if (rows != 1) throw new ApplicationException("Inserting a transaction returned rows != 1: " + rows); } } catch (Exception e) { Log.Error("Saving transaction failed. ", e); // we don't rethrow the exception. We'll try to complete the transaction. } }
private bool isObjectSaved(string customerId, string prodId, SetExpressCheckoutResponseType response, DataSet ds) { foreach (DataTable table in ds.Tables) { foreach (DataRow row in table.Rows) { if ((string)row["CustomerId"] == customerId && (string)row["ProdId"] == prodId && (string)row["Response"] == JSONHelper.Serialize(response)) return true; } } return false; }
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); }
public static PayPalResponceModel Pay(string email, CartViewModel cart, string expressCheckoutSuccessUrl, string paymentFailureUrl) { Dictionary <string, string> config = PayPal.Api.ConfigManager.Instance.GetProperties(); PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(config); SetExpressCheckoutRequestType setExpressCheckoutReqType = new SetExpressCheckoutRequestType(); SetExpressCheckoutRequestDetailsType details = new SetExpressCheckoutRequestDetailsType(); List <PaymentDetailsType> payDetails = new List <PaymentDetailsType>(); PaymentDetailsType paydtl = new PaymentDetailsType(); paydtl.PaymentAction = PaymentActionCodeType.ORDER; BasicAmountType shippingTotal = new BasicAmountType(); shippingTotal.value = cart.ShippingCost.ToString(); shippingTotal.currencyID = CurrencyCodeType.USD; decimal itemsTotal = 0.0M; List <PaymentDetailsItemType> lineItems = new List <PaymentDetailsItemType>(); foreach (var cartItem in cart.Items) { PaymentDetailsItemType item = new PaymentDetailsItemType(); BasicAmountType amt = new BasicAmountType(); amt.currencyID = CurrencyCodeType.USD; amt.value = "50"; item.Quantity = cartItem.Count; itemsTotal += 50 * cartItem.Count; item.Name = string.Format("{0} {1} Shirt", cartItem.Project.ShirtColor, cartItem.Project.SizeString); item.Amount = amt; lineItems.Add(item); } decimal orderTotal = itemsTotal + cart.ShippingCost; paydtl.OrderTotal = new BasicAmountType(CurrencyCodeType.USD, Convert.ToString(orderTotal)); paydtl.PaymentDetailsItem = lineItems; paydtl.ShippingTotal = shippingTotal; paydtl.PaymentDetailsItem = lineItems; payDetails.Add(paydtl); details.BuyerEmail = email; details.PaymentDetails = payDetails; details.ReturnURL = expressCheckoutSuccessUrl; details.CancelURL = paymentFailureUrl; setExpressCheckoutReqType.SetExpressCheckoutRequestDetails = details; SetExpressCheckoutReq expressCheckoutReq = new SetExpressCheckoutReq(); expressCheckoutReq.SetExpressCheckoutRequest = setExpressCheckoutReqType; SetExpressCheckoutResponseType response = null; try { response = service.SetExpressCheckout(expressCheckoutReq); } catch (Exception ex) { return(new PayPalResponceModel { Success = false, ErrorMessage = ex.Message }); } if (!response.Ack.ToString().Trim().ToUpper().Equals(AckCode.FAILURE.ToString()) && !response.Ack.ToString().Trim().ToUpper().Equals(AckCode.FAILUREWITHWARNING.ToString())) { var redirectUrl = string.Format("{0}_express-checkout&token={1}", config["paypalResultUrl"], response.Token); return(new PayPalResponceModel { Success = true, RedirectUrl = redirectUrl }); } return(new PayPalResponceModel { Success = false, ErrorMessage = string.Join(". ", response.Errors.Select(x => x.LongMessage).ToList()) }); }
private async Task <ActionResult> DoMakePayment(GNInvoice invoice, double paymentAmount, string cancelURL, RedirectToRouteResult errorRedirectAction) { SetExpressCheckoutResponseType ecResponse = null; try { CurrencyCodeType currencyUSD = (CurrencyCodeType)EnumUtils.GetValue("USD", typeof(CurrencyCodeType)); //define payment details List <PaymentDetailsType> paymentDetails = new List <PaymentDetailsType>() { new PaymentDetailsType { PaymentDetailsItem = new List <PaymentDetailsItemType>() { new PaymentDetailsItemType { Name = invoice.Name, Amount = new BasicAmountType(currencyUSD, Math.Round(paymentAmount, 2) + ""), Quantity = 1, ItemCategory = (ItemCategoryType)EnumUtils.GetValue("Physical", typeof(ItemCategoryType)) } }, PaymentAction = (PaymentActionCodeType)EnumUtils.GetValue("Sale", typeof(PaymentActionCodeType)), OrderTotal = new BasicAmountType(currencyUSD, (Math.Round(paymentAmount, 2) * 1) + "") } }; //define checkout request details SetExpressCheckoutReq expressCheckoutRequest = new SetExpressCheckoutReq() { SetExpressCheckoutRequest = new SetExpressCheckoutRequestType() { Version = "104.0", SetExpressCheckoutRequestDetails = new SetExpressCheckoutRequestDetailsType() { ReturnURL = Url.Action("PaymentSuccess", "PayPal", new { invoiceId = invoice.Id }, protocol: GetURLScheme()), CancelURL = cancelURL, PaymentDetails = paymentDetails } } }; //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"]); //instantiate PayPal API service and send Express Checkout Request PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(sdkConfig); ecResponse = service.SetExpressCheckout(expressCheckoutRequest); } catch (Exception e) { LogUtil.Error(logger, "Error sending PayPal payment!!", e); } if (ecResponse != null && ecResponse.Ack.HasValue && ecResponse.Ack.Value.ToString() != "FAILURE" && ecResponse.Errors.Count == 0) { //redirect to PayPal if (ConfigurationManager.AppSettings["paypal.mode"] == "live") { string paypalURL = "https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=" + ecResponse.Token; return(RedirectPermanent(paypalURL)); } else { string paypalURL = "https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=" + ecResponse.Token; return(RedirectPermanent(paypalURL)); } } else { errorRedirectAction.RouteValues["error"] = string.Join(",", ecResponse.Errors.Select(e => e.LongMessage).ToArray()); return(errorRedirectAction); } }
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()); }