public override ProcessPaymentResult ProcessPayment(ProcessPaymentEvaluationContext context) { var retVal = new ProcessPaymentResult(); if (context.Order != null && context.Store != null && context.Payment != null) { KlarnaLocalization localization; string countryName = null; string currency = context.Order.Currency.ToString(); if (context.Order.Addresses != null && context.Order.Addresses.Count > 0) { var address = context.Order.Addresses.FirstOrDefault(); countryName = address.CountryName; } if (!string.IsNullOrEmpty(countryName)) { localization = GetLocalization(currency, countryName); } else { localization = GetLocalization(currency, null); } if (localization != null) { if (localization.CountryName == "US" || localization.CountryName == "GB") { retVal = NewCreateKlarnaOrder(localization, context); } else { retVal = OldCreateKlarnaOrder(localization, context); } } else { retVal.Error = "Klarna is not available for this order"; } } return(retVal); }
public override ProcessPaymentResult ProcessPayment(ProcessPaymentEvaluationContext context) { if (context.Order == null) { throw new ArgumentNullException("context.Order is null"); } if (context.Payment == null) { throw new ArgumentNullException("context.Payment is null"); } if (context.Store == null) { throw new ArgumentNullException("context.Store is null"); } if (string.IsNullOrEmpty(context.Store.Url)) { throw new NullReferenceException("URL of store not set"); } var retVal = new ProcessPaymentResult(); var service = new PayPalAPIInterfaceServiceService(GetConfigMap()); var request = GetSetExpressCheckoutRequest(context.Order, context.Store, context.Payment); try { var setEcResponse = service.SetExpressCheckout(request); CheckResponse(setEcResponse); retVal.IsSuccess = true; retVal.NewPaymentStatus = context.Payment.PaymentStatus = PaymentStatus.Pending; retVal.OuterId = context.Payment.OuterId = setEcResponse.Token; var redirectBaseUrl = GetBaseUrl(Mode); retVal.RedirectUrl = string.Format(redirectBaseUrl, retVal.OuterId); } catch (System.Exception ex) { retVal.Error = ex.Message; } return(retVal); }
private ProcessPaymentResult PrepareFormContent(ProcessPaymentEvaluationContext context) { var formContent = _stripeCheckoutService.GetCheckoutFormContent(new StripeCheckoutSettings { PublishableKey = ApiPublishableKey, TokenAttributeName = _stripeTokenAttrName, Order = context.Order, Store = context.Store, }); var result = new ProcessPaymentResult(); result.IsSuccess = true; result.NewPaymentStatus = context.Payment.PaymentStatus = PaymentStatus.Pending; result.HtmlForm = formContent; result.OuterId = null; return(result); }
public override ProcessPaymentResult ProcessPayment(ProcessPaymentEvaluationContext context) { var retVal = new ProcessPaymentResult(); GatewaySettings settings = new GatewaySettings(); settings.setCredentials(ProfileId, ProfileKey) .setVerbose(true) .setHostUrl(GatewaySettings.URL_CERT); Gateway gateway = new Gateway(settings); GatewayRequest request = new GatewayRequest(GatewayRequest.TransactionType.SALE); if (string.IsNullOrEmpty(context.Payment.OuterId)) { request.setCardData("4012888812348882", "1216"); } else { request.setTokenData(context.Payment.OuterId, string.Empty); } request.setAmount("1.03"); GatewayResponse response = gateway.run(request); var tranId = response.getTransactionId(); var errorCode = response.getErrorCode(); if (errorCode.Equals("000")) { retVal.OuterId = tranId; retVal.IsSuccess = true; retVal.NewPaymentStatus = PaymentStatus.Pending; //maybe } else { retVal.NewPaymentStatus = PaymentStatus.Voided; retVal.Error = string.Format("Mes error {0}", errorCode); } return(retVal); }
public IHttpActionResult ProcessOrderPayments([FromBody] BankCardInfo bankCardInfo, string orderId, string paymentId) { var order = _customerOrderService.GetById(orderId, coreModel.CustomerOrderResponseGroup.Full); if (order == null) { throw new NullReferenceException("order"); } var payment = order.InPayments.FirstOrDefault(x => x.Id == paymentId); if (payment == null) { throw new NullReferenceException("payment"); } var store = _storeService.GetById(order.StoreId); var paymentMethod = store.PaymentMethods.FirstOrDefault(x => x.Code == payment.GatewayCode); if (payment == null) { throw new NullReferenceException("appropriate paymentMethod not found"); } var context = new ProcessPaymentEvaluationContext { Order = order, Payment = payment, Store = store, BankCardInfo = bankCardInfo }; var result = paymentMethod.ProcessPayment(context); _customerOrderService.Update(new coreModel.CustomerOrder[] { order }); var retVal = new webModel.ProcessPaymentResult(); retVal.InjectFrom(result); retVal.PaymentMethodType = paymentMethod.PaymentMethodType; return(Ok(retVal)); }
public override ProcessPaymentResult ProcessPayment(ProcessPaymentEvaluationContext context) { if (context.Store == null) { throw new NullReferenceException("Store should not be null."); } if (context.BankCardInfo == null) { throw new NullReferenceException("BankCardInfo should not be null."); } var retVal = new ProcessPaymentResult(); var payPalService = new PayPalService(GetConfiguration(), _logger); var result = payPalService.ProcessCreditCard(context); PaymentStatus newStatus; if (result.Succeeded) { context.Payment.IsApproved = true; retVal.OuterId = result.PaymentId; retVal.IsSuccess = true; context.Payment.CapturedDate = DateTime.UtcNow; newStatus = PaymentStatus.Paid; } else { context.Payment.IsApproved = false; retVal.Error = result.Error; retVal.IsSuccess = false; context.Payment.VoidedDate = DateTime.UtcNow; newStatus = PaymentStatus.Voided; } retVal.NewPaymentStatus = context.Payment.PaymentStatus = newStatus; return(retVal); }
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 override ProcessPaymentResult ProcessPayment(ProcessPaymentEvaluationContext context) { if (context.Store == null) { throw new NullReferenceException("Store should not be null."); } if (context.BankCardInfo == null) { throw new NullReferenceException("BankCardInfo should not be null."); } var retVal = new ProcessPaymentResult(); var doDirectPaymentRequest = GetDoDirectPaymentRequest(context); var service = GetService(); var response = service.DoDirectPayment(doDirectPaymentRequest); string error; bool success = CheckResponse(response, out error); if (success) { retVal.OuterId = response.TransactionID; retVal.IsSuccess = (response.Ack.Value == AckCodeType.SUCCESS || response.Ack.Value == AckCodeType.SUCCESSWITHWARNING); retVal.NewPaymentStatus = retVal.IsSuccess ? PaymentStatus.Paid : PaymentStatus.Voided; } else { retVal.Error = error; } return(retVal); }
private ProcessPaymentResult NewCreateKlarnaOrder(KlarnaLocalization localization, ProcessPaymentEvaluationContext context) { var retVal = new ProcessPaymentResult(); var orderLineItems = GetOrderLineItems(context.Order); MerchantUrls merchantUrls = new MerchantUrls { Terms = new System.Uri( string.Format("{0}/{1}", context.Store.Url, TermsUrl)), Checkout = new System.Uri( string.Format("{0}/{1}", context.Store.Url, CheckoutUrl)), Confirmation = new System.Uri( string.Format("{0}/{1}?sid=123&orderId={2}&", context.Store.Url, ConfirmationUrl, context.Order.Id) + "klarna_order={checkout.order.uri}"), Push = new System.Uri( string.Format("{0}/{1}?sid=123&orderId={2}&", context.Store.Url, "admin/api/paymentcallback", context.Order.Id) + "klarna_order={checkout.order.uri}") }; CheckoutOrderData orderData = new CheckoutOrderData() { PurchaseCountry = localization.CountryName, PurchaseCurrency = localization.Currency, Locale = localization.Locale, OrderAmount = (int)(context.Order.Sum * 100), OrderTaxAmount = (int)(context.Order.Tax * 100), OrderLines = orderLineItems, MerchantUrls = merchantUrls }; var connector = ConnectorFactory.Create( AppKey, AppSecret, Client.TestBaseUrl); Client client = new Client(connector); var checkout = client.NewCheckoutOrder(); checkout.Create(orderData); orderData = checkout.Fetch(); retVal.IsSuccess = true; retVal.NewPaymentStatus = PaymentStatus.Pending; retVal.OuterId = orderData.OrderId; retVal.HtmlForm = string.Format("<div>{0}</div>", orderData.HtmlSnippet); return(retVal); }
private Hashtable PrepareProcessPaymentRequest(ProcessPaymentEvaluationContext context) { if (context.BankCardInfo == null) { throw new NullReferenceException("BankCardInfo should not be null."); } Hashtable request = new Hashtable(); request.Add("merchantID", MerchantId); request.Add("merchantReferenceCode", context.Payment.Number); if (IsSeparatePaymentAction()) { request.Add("ccAuthService_run", "true"); } else { request.Add("ccAuthService_run", "true"); request.Add("ccCaptureService_run", "true"); } if (IsTest()) { request.Add("sendToProduction", "false"); } else { request.Add("sendToProduction", "true"); } // Set billing address of payment as address for request var address = context.Payment.BillingAddress; // Set first billing address in order if (address == null && context.Order.Addresses != null) { address = context.Order.Addresses.FirstOrDefault(a => a.AddressType == AddressType.Billing || a.AddressType == AddressType.BillingAndShipping); } // Set any first address in order if (address == null) { address = context.Order.Addresses.FirstOrDefault(); } // Throw exception, is no address if (address == null) { throw new NullReferenceException("No address, payment can't be processed"); } SetBillingAddress(address, request); SetCreditCardInfo(context.BankCardInfo, request); request.Add("purchaseTotals_currency", context.Payment.Currency.ToString()); request.Add("item_0_unitPrice", context.Payment.Sum.ToString(CultureInfo.InvariantCulture)); //request.Add("item_0_quantity", "1"); return(request); }
public PayPalRestProcessResult ProcessCreditCard(ProcessPaymentEvaluationContext context) { Payer payer; Transaction transaction; try { var shippingAddress = context.Order.Addresses.FirstOrDefault( a => a.AddressType == VirtoCommerce.Domain.Commerce.Model.AddressType.BillingAndShipping || a.AddressType == VirtoCommerce.Domain.Commerce.Model.AddressType.Shipping); if (shippingAddress == null) { throw new Exception("No shipping address available."); } var billingAddress = context.Order.Addresses.FirstOrDefault( a => a.AddressType == VirtoCommerce.Domain.Commerce.Model.AddressType .BillingAndShipping || a.AddressType == VirtoCommerce.Domain.Commerce.Model.AddressType.Billing) ?? shippingAddress; transaction = new Transaction { amount = new Amount { currency = context.Order.Currency, total = context.Order.Total.ToString("N2"), details = new Details { shipping = context.Order.ShippingSubTotal.ToString("N2"), subtotal = context.Order.SubTotal.ToString("N2"), tax = context.Order.TaxTotal.ToString("N2"), } }, description = $"Order from {context.Store.Name}.", item_list = new ItemList { shipping_address = new ShippingAddress { city = shippingAddress.City, country_code = GetPayPalCountryCode(shippingAddress.CountryCode), line1 = shippingAddress.Line1, line2 = shippingAddress.Line2, phone = shippingAddress.Phone, postal_code = shippingAddress.PostalCode, state = shippingAddress.RegionId, recipient_name = FormattedName(shippingAddress) } }, invoice_number = Guid.NewGuid().ToString() }; payer = new Payer { payment_method = "credit_card", funding_instruments = new List <FundingInstrument> { new FundingInstrument { credit_card = new CreditCard { billing_address = new Address { city = billingAddress.City, country_code = GetPayPalCountryCode(billingAddress.CountryCode), line1 = billingAddress.Line1, line2 = billingAddress.Line2, phone = billingAddress.Phone, postal_code = billingAddress.PostalCode, state = billingAddress.RegionId, }, cvv2 = context.BankCardInfo.BankCardCVV2, expire_month = context.BankCardInfo.BankCardMonth, expire_year = context.BankCardInfo.BankCardYear, first_name = billingAddress.FirstName, last_name = billingAddress.LastName, number = context.BankCardInfo.BankCardNumber, type = GetPayPalCreditCardType(context.BankCardInfo.BankCardType) } } }, payer_info = new PayerInfo { email = billingAddress.Email } }; } catch (Exception) { _logger.Error( $"Failed to create PayPal payment API request from OrderContext. {JsonConvert.SerializeObject(context)}"); _logger.Trace($"Failed to create PayPal payment API request from OrderContext. {JsonConvert.SerializeObject(context)}"); throw; } var payment = new Payment { intent = "Sale", payer = payer, transactions = new List <Transaction> { transaction } }; try { var accessToken = new OAuthTokenCredential(_configuration.ToDictionary()).GetAccessToken(); var apiContext = new APIContext(accessToken) { Config = _configuration.ToDictionary() }; var createdPayment = payment.Create(apiContext); if (createdPayment.state == "failed") { return(new PayPalRestProcessResult { Succeeded = false, Error = createdPayment.failure_reason }); } return(new PayPalRestProcessResult { Succeeded = true, Error = string.Empty, PaymentId = createdPayment.id }); } catch (Exception exception) { _logger.Error($"Payment processing through PayPal failed. {JsonConvert.SerializeObject(context)}"); _logger.Trace($"Payment processing through PayPal failed. {JsonConvert.SerializeObject(context)}"); return(new PayPalRestProcessResult { Succeeded = false, Error = $"{exception.Message}", PaymentId = string.Empty }); } }
private ProcessPaymentResult OldCreateKlarnaOrder(KlarnaLocalization localization, ProcessPaymentEvaluationContext context) { var retVal = new ProcessPaymentResult(); var cartItems = CreateKlarnaCartItems(context.Order); //Create cart var cart = new Dictionary <string, object> { { "items", cartItems } }; var data = new Dictionary <string, object> { { "cart", cart } }; //Create klarna order "http://example.com" context.Store.Url var connector = Connector.Create(AppSecret); Order order = null; var merchant = new Dictionary <string, object> { { "id", AppKey }, { "terms_uri", string.Format("{0}/{1}", context.Store.Url, TermsUrl) }, { "checkout_uri", string.Format("{0}/{1}", context.Store.Url, CheckoutUrl) }, { "confirmation_uri", string.Format("{0}/{1}?sid=123&orderId={2}&", context.Store.Url, ConfirmationUrl, context.Order.Id) + "klarna_order={checkout.order.uri}" }, { "push_uri", string.Format("{0}/{1}?sid=123&orderId={2}&", context.Store.Url, "admin/api/paymentcallback", context.Order.Id) + "klarna_order={checkout.order.uri}" }, { "back_to_store_uri", context.Store.Url } }; var layout = new Dictionary <string, object> { { "layout", "desktop" } }; data.Add("purchase_country", localization.CountryName); data.Add("purchase_currency", localization.Currency); data.Add("locale", localization.Locale); data.Add("merchant", merchant); data.Add("gui", layout); order = new Order(connector) { BaseUri = new Uri(GetCheckoutBaseUrl(localization.Currency)), ContentType = _contentType }; order.Create(data); order.Fetch(); //Gets snippet var gui = order.GetValue("gui") as JObject; var html = gui["snippet"].Value <string>(); retVal.IsSuccess = true; retVal.NewPaymentStatus = PaymentStatus.Pending; retVal.HtmlForm = html; retVal.OuterId = order.GetValue("id") as string; return(retVal); }
public override ProcessPaymentResult ProcessPayment(ProcessPaymentEvaluationContext context) { var retVal = new ProcessPaymentResult(); if (context.Store == null) { throw new NullReferenceException("no store with this id"); } if (!(!string.IsNullOrEmpty(context.Store.SecureUrl) || !string.IsNullOrEmpty(context.Store.Url))) { throw new NullReferenceException("store must specify Url or SecureUrl property"); } var url = string.Empty; if (!string.IsNullOrEmpty(context.Store.SecureUrl)) { url = context.Store.SecureUrl; } else { url = context.Store.Url; } var config = GetConfigMap(); var service = new AdaptivePaymentsService(config); var request = CreatePaypalRequest(context.Order, context.Payment, url); var payResponse = service.Pay(request); var setPaymentOptionsResponse = service.SetPaymentOptions(new SetPaymentOptionsRequest { payKey = payResponse.payKey, senderOptions = new SenderOptions { referrerCode = "Virto_SP" } }); var executePaymentResponse = service.ExecutePayment(new ExecutePaymentRequest { payKey = payResponse.payKey, actionType = "PAY", requestEnvelope = new RequestEnvelope { errorLanguage = "en_US" } }); if (executePaymentResponse.error != null && executePaymentResponse.error.Count > 0) { var sb = new StringBuilder(); foreach (var error in executePaymentResponse.error) { sb.AppendLine(error.message); } retVal.Error = sb.ToString(); retVal.NewPaymentStatus = PaymentStatus.Voided; } else { retVal.OuterId = payResponse.payKey; retVal.IsSuccess = true; var redirectBaseUrl = GetBaseUrl(Mode); retVal.RedirectUrl = string.Format(redirectBaseUrl, retVal.OuterId); retVal.NewPaymentStatus = PaymentStatus.Pending; } return(retVal); }
public IHttpActionResult ProcessOrderPayments(string orderId, string paymentId, [SwaggerOptional] BankCardInfo bankCardInfo) { var order = _customerOrderService.GetByIds(new[] { orderId }, CustomerOrderResponseGroup.Full.ToString()) .FirstOrDefault(); if (order == null) { var searchCriteria = AbstractTypeFactory <CustomerOrderSearchCriteria> .TryCreateInstance(); searchCriteria.Number = orderId; searchCriteria.ResponseGroup = CustomerOrderResponseGroup.Full.ToString(); order = _searchService.SearchCustomerOrders(searchCriteria).Results.FirstOrDefault(); } if (order == null) { throw new InvalidOperationException($"Cannot find order with ID {orderId}"); } var payment = order.InPayments.FirstOrDefault(x => x.Id == paymentId); if (payment == null) { throw new InvalidOperationException($"Cannot find payment with ID {paymentId}"); } var store = _storeService.GetById(order.StoreId); var paymentMethod = store.PaymentMethods.FirstOrDefault(x => x.Code == payment.GatewayCode); if (paymentMethod == null) { throw new InvalidOperationException($"Cannot find payment method with code {payment.GatewayCode}"); } var parameters = new NameValueCollection(); foreach (var key in HttpContext.Current.Request.Headers.AllKeys) { parameters.Add(key, HttpContext.Current.Request.Headers[key]); } var context = new ProcessPaymentEvaluationContext { Order = order, Payment = payment, Store = store, BankCardInfo = bankCardInfo, Parameters = parameters }; var result = paymentMethod.ProcessPayment(context); if (result.OuterId != null) { payment.OuterId = result.OuterId; } _customerOrderService.SaveChanges(new[] { order }); return(Ok(result)); }
/// <summary> /// Method that contains logic of registration payment in external payment system /// </summary> /// <param name="context"></param> /// <returns>Result of registration payment in external payment system</returns> public abstract ProcessPaymentResult ProcessPayment(ProcessPaymentEvaluationContext context);
public override ProcessPaymentResult ProcessPayment(ProcessPaymentEvaluationContext context) { var retVal = new ProcessPaymentResult(); if (context.Order != null && context.Store != null && context.Payment != null) { if (!(!string.IsNullOrEmpty(context.Store.SecureUrl) || !string.IsNullOrEmpty(context.Store.Url))) { throw new NullReferenceException("store must specify Url or SecureUrl property"); } var baseStoreUrl = string.Empty; if (!string.IsNullOrEmpty(context.Store.SecureUrl)) { baseStoreUrl = context.Store.SecureUrl; } else { baseStoreUrl = context.Store.Url; } var orderId = context.Order.Number; //get md5 hash passing the order number, currency ISO code and order total var md5Hash = CalculateMD5Hash(orderId, context.Order.Currency, (int)(context.Order.Sum * 100)); var reqparm = new NameValueCollection(); reqparm.Add(acceptUrlFormDataName, AcceptUrl); reqparm.Add(callbackUrlFormDataName, CallbackUrl); reqparm.Add(cancelUrlFormDataName, AcceptUrl); reqparm.Add(merchantIdFormDataName, MerchantId); reqparm.Add(orderIdFormDataName, orderId); reqparm.Add(orderInternalIdFormDataName, context.Order.Id); reqparm.Add(amountFormDataName, ((int)(context.Order.Sum * 100)).ToString()); reqparm.Add(currencyFormDataName, context.Order.Currency.ToString()); reqparm.Add(languageFormDataName, context.Store.DefaultLanguage.Substring(0, 2)); reqparm.Add(md5KeyFormDataName, md5Hash); reqparm.Add(decoratorFormDataName, FormDecoarator); if (Mode == "test") { reqparm.Add(testModeFormDataName, "1"); } //build form to post to FlexWin var checkoutform = string.Empty; checkoutform += string.Format("<form name='dibs' action='{0}' method='POST' charset='UTF-8'>", RedirectUrl); checkoutform += "<p>You'll be redirected to DIBS payment in a moment. If not, click the 'Procced' button...</p>"; const string paramTemplateString = "<INPUT TYPE='hidden' name='{0}' value='{1}'>"; foreach (string key in reqparm) { checkoutform += string.Format(paramTemplateString, key, reqparm[key]); } checkoutform += "<button type='submit'>Proceed</button>"; checkoutform += "</form>"; checkoutform += "<script language='javascript'>document.dibs.submit();</script>"; retVal.HtmlForm = checkoutform; retVal.IsSuccess = true; retVal.NewPaymentStatus = PaymentStatus.Pending; } return(retVal); }
public void ProcessCreditCardWhenEverythingIsPerfect() { var context = new ProcessPaymentEvaluationContext { BankCardInfo = new BankCardInfo { BankCardNumber = "4012888888881881", BankCardCVV2 = "000", BankCardMonth = 11, BankCardYear = 2018, BankCardType = "VISA" }, Order = new CustomerOrder { Addresses = new List <Address> { new Address { AddressType = AddressType.Shipping, City = "Lehi", CountryCode = "USA", CountryName = "United States", Email = "*****@*****.**", FirstName = "Sam", LastName = "Smith", Line1 = "123 Main St.", Line2 = string.Empty, MiddleName = string.Empty, RegionId = "UT", Phone = "8889637845", PostalCode = "84043", Name = "Sam Smith", Organization = string.Empty, RegionName = "Utah", Zip = "84043" } }, Currency = "USD", Items = new List <LineItem> { new LineItem { Currency = "USD", Price = 12.50M, Quantity = 1, TaxPercentRate = 1.0M } }, Shipments = new List <Shipment> { new Shipment { Currency = "USD", Price = 10.50M, TaxPercentRate = 0.0M, } } }, Payment = new PaymentIn { BillingAddress = new Address { AddressType = AddressType.Billing, City = "Lehi", CountryCode = "USA", CountryName = "United States", Email = "*****@*****.**", FirstName = "Sam", LastName = "Smith", Line1 = "123 Main St.", Line2 = string.Empty, MiddleName = string.Empty, RegionId = "UT", Phone = "8889637845", PostalCode = "84043", Name = "Sam Smith", Organization = string.Empty, RegionName = "Utah", Zip = "84043" } }, Store = new Store { Name = "My Store" } }; var result = _payPalService.ProcessCreditCard(context); Assert.IsNotNull(result); Assert.AreEqual(string.Empty, result.Error); Assert.IsNotNull(result.PaymentId); Assert.AreEqual(true, result.Succeeded); }