/// <summary>
        /// Process a payment
        /// </summary>
        /// <param name="processPaymentRequest">Payment info required for an order processing</param>
        /// <returns>Process payment result</returns>
        public ProcessPaymentResult ProcessPayment(ProcessPaymentRequest processPaymentRequest)
        {
            var result = new ProcessPaymentResult
            {
                AllowStoringCreditCardNumber = true
            };

            ProcessPaymentInstapago(processPaymentRequest, out result);

            switch (_instaPagoPaymentSettings.TransactMode)
            {
            case TransactMode.Pending:
                result.NewPaymentStatus = PaymentStatus.Pending;
                break;

            case TransactMode.Authorize:
                result.NewPaymentStatus = PaymentStatus.Authorized;
                break;

            case TransactMode.AuthorizeAndCapture:
                result.NewPaymentStatus = PaymentStatus.Paid;
                break;

            default:
                result.AddError("Not supported transaction type");
                break;
            }

            return(result);
        }
Beispiel #2
0
        /// <summary>
        /// Process recurring payment
        /// </summary>
        /// <param name="processPaymentRequest">Payment info required for an order processing</param>
        /// <returns>Process payment result</returns>
        public override ProcessPaymentResult ProcessRecurringPayment(ProcessPaymentRequest processPaymentRequest)
        {
            var result = new ProcessPaymentResult();

            result.AddError(_localizationService.GetResource("Common.Payment.NoRecurringPaymentSupport"));
            return(result);
        }
Beispiel #3
0
        /// <summary>
        /// 定期付款
        /// </summary>
        public ProcessPaymentResult ProcessRecurringPayment(ProcessPaymentRequest processPaymentRequest)
        {
            var result = new ProcessPaymentResult();

            result.AddError("不支持定期付款");
            return(result);
        }
Beispiel #4
0
        /// <summary>
        /// Process a payment
        /// </summary>
        /// <param name="processPaymentRequest">Payment info required for an order processing</param>
        /// <returns>Process payment result</returns>
        public ProcessPaymentResult ProcessPayment(ProcessPaymentRequest processPaymentRequest)
        {
            var result = new ProcessPaymentResult();

            var customer = _customerService.GetCustomerById(processPaymentRequest.CustomerId);
            //var orderTotal = Math.Round(processPaymentRequest.OrderTotal, 2);

            StripeCreditCardInfo cc = new StripeCreditCardInfo();

            cc.CVC      = processPaymentRequest.CreditCardCvv2;
            cc.FullName = customer.BillingAddress.FirstName + " " + customer.BillingAddress.LastName;

            cc.Number          = processPaymentRequest.CreditCardNumber;
            cc.ExpirationMonth = processPaymentRequest.CreditCardExpireMonth;
            cc.ExpirationYear  = processPaymentRequest.CreditCardExpireYear;
            cc.AddressLine1    = customer.BillingAddress.Address1;
            cc.AddressLine2    = customer.BillingAddress.Address2;
            if (customer.BillingAddress.Country.TwoLetterIsoCode.ToLower() == "us")
            {
                cc.StateOrProvince = customer.BillingAddress.StateProvince.Abbreviation;
            }
            else
            {
                cc.StateOrProvince = "ot";
            }

            cc.ZipCode = customer.BillingAddress.ZipPostalCode;

            cc.Country = customer.BillingAddress.Country.TwoLetterIsoCode;

            StripePayment payment = new StripePayment(_stripePaymentSettings.TransactionKey);

            try
            {
                StripeCharge charge = payment.Charge((int)(processPaymentRequest.OrderTotal * 100),
                                                     _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId).CurrencyCode.ToLower(),
                                                     cc, string.Format("charge for {0} - {1}",
                                                                       cc.FullName, processPaymentRequest.PurchaseOrderNumber));

                if (charge != null)
                {
                    result.NewPaymentStatus               = PaymentStatus.Paid;
                    _stripePaymentSettings.TransactMode   = TransactMode.AuthorizeAndCapture;
                    result.AuthorizationTransactionId     = charge.ID;
                    result.AuthorizationTransactionResult = StripeChargeStatus.SUCCESS;
                    //need this for refund
                    result.AuthorizationTransactionCode = _stripePaymentSettings.TransactionKey;
                }
            }
            catch (StripeException stripeException)
            {
                result.AuthorizationTransactionResult = stripeException.StripeError.Message;
                result.AuthorizationTransactionCode   = stripeException.StripeError.Code;
                result.AuthorizationTransactionId     = "-1";
                result.AddError(string.Format("Declined ({0}: {1} - {2})", result.AuthorizationTransactionCode,
                                              result.AuthorizationTransactionResult, _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId).CurrencyCode));
            }

            return(result);
        }
Beispiel #5
0
        public override ProcessPaymentResult ProcessRecurringPayment(ProcessPaymentRequest processPaymentRequest)
        {
            var result   = new ProcessPaymentResult();
            var settings = CommonServices.Settings.LoadSetting <ManualPaymentSettings>(processPaymentRequest.StoreId);

            result.AllowStoringCreditCardNumber = true;
            switch (settings.TransactMode)
            {
            case TransactMode.Pending:
                result.NewPaymentStatus = PaymentStatus.Pending;
                break;

            case TransactMode.Authorize:
                result.NewPaymentStatus = PaymentStatus.Authorized;
                break;

            case TransactMode.Paid:
                result.NewPaymentStatus = PaymentStatus.Paid;
                break;

            default:
            {
                result.AddError(T("Common.Payment.TranactionTypeNotSupported"));
                return(result);
            }
            }

            return(result);
        }
 private void ConvertToChargeResult(Receipt receipt, ProcessPaymentResult result)
 {
     if (receipt.GetComplete() == "false")
     {
         result.AddError("Payment is not successful. Please try again or check payment option.");
     }
     result.AvsResult  = receipt.GetAvsResultCode();
     result.Cvv2Result = receipt.GetCavvResultCode();
     result.AuthorizationTransactionId     = receipt.GetReferenceNum();
     result.AuthorizationTransactionCode   = receipt.GetAuthCode();
     result.AuthorizationTransactionResult = receipt.GetResponseCode();
     result.CaptureTransactionId           = receipt.GetTxnNumber(); // required for refund
     result.CaptureTransactionResult       = receipt.GetTransactionId();
     if (receipt.GetResponseCode() != null || receipt.GetResponseCode() != "null")
     {
         int responseCode = Int32.Parse(receipt.GetResponseCode().ToString());
         //Moneris reference
         //Transaction Response Code < 50: Transaction approved >= 50: Transaction declined
         //NULL: Transaction was not sent for authorization For further details on the response codes that are returned please see the Response Codes table
         if (responseCode < 50)
         {
             result.NewPaymentStatus = PaymentStatus.Paid;
         }
     }
 }
Beispiel #7
0
        /// <summary>
        /// Process a payment
        /// </summary>
        /// <param name="processPaymentRequest">Payment info required for an order processing</param>
        /// <returns>
        /// A task that represents the asynchronous operation
        /// The task result contains the process payment result
        /// </returns>
        public Task <ProcessPaymentResult> ProcessPaymentAsync(ProcessPaymentRequest processPaymentRequest)
        {
            var result = new ProcessPaymentResult
            {
                AllowStoringCreditCardNumber = true
            };

            switch (_manualPaymentSettings.TransactMode)
            {
            case TransactMode.Pending:
                result.NewPaymentStatus = PaymentStatus.Pending;
                break;

            case TransactMode.Authorize:
                result.NewPaymentStatus = PaymentStatus.Authorized;
                break;

            case TransactMode.AuthorizeAndCapture:
                result.NewPaymentStatus = PaymentStatus.Paid;
                break;

            default:
                result.AddError("Not supported transaction type");
                break;
            }

            return(Task.FromResult(result));
        }
        public ProcessPaymentResult Authorize(ProcessPaymentRequest paymentRequest)
        {
            var result = new ProcessPaymentResult();

            var dataKey = paymentRequest.CustomValues["SavedCardVault"] as string;
            var isNewCardSaveAllowed = System.Convert.ToBoolean(paymentRequest.CustomValues["IsNewCardSaveAllowed"]);
            // Expire date "YYMM" format
            var expireDate = GetExpireDate(paymentRequest.CreditCardExpireYear, paymentRequest.CreditCardExpireMonth);

            try
            {
                if (isNewCardSaveAllowed)
                {
                    // Vault Add card
                    dataKey = AddCardToVault(paymentRequest.CreditCardNumber, expireDate, paymentRequest.CustomerId.ToString());
                    // TODO: save into database
                }
                Receipt receipt = PerformAuthorizeTransation(dataKey, paymentRequest.CreditCardNumber, expireDate, paymentRequest.CustomerId.ToString(),
                                                             paymentRequest.OrderGuid.ToString(), paymentRequest.OrderTotal.ToString(), paymentRequest.CreditCardCvv2);

                result.AvsResult  = receipt.GetAvsResultCode();
                result.Cvv2Result = receipt.GetCvdResultCode();
                result.AuthorizationTransactionId     = receipt.GetTxnNumber();
                result.AuthorizationTransactionCode   = receipt.GetAuthCode();
                result.AuthorizationTransactionResult = receipt.GetResponseCode();
            }
            catch (Exception ex)
            {
                result.AddError(ex.Message);
            }

            return(result);
        }
Beispiel #9
0
        /// <summary>
        /// Process a payment
        /// </summary>
        /// <param name="processPaymentRequest">Payment info required for an order processing</param>
        /// <returns>Process payment result</returns>
        public ProcessPaymentResult ProcessPayment(ProcessPaymentRequest processPaymentRequest)
        {
            var result = new ProcessPaymentResult();

            result.AllowStoringCreditCardNumber = true;
            switch (_manualPaymentSettings.TransactMode)
            {
            case TransactMode.Pending:
                result.NewPaymentStatus = PaymentStatus.Pending;
                break;

            case TransactMode.Authorize:
                result.NewPaymentStatus = PaymentStatus.Authorized;
                break;

            case TransactMode.AuthorizeAndCapture:
                result.NewPaymentStatus = PaymentStatus.Paid;
                break;

            default:
            {
                result.AddError("Not supported transaction type");
                return(result);
            }
            }

            return(result);
        }
        /// <summary>
        /// Process recurring payment
        /// </summary>
        /// <param name="processPaymentRequest">Payment info required for an order processing</param>
        /// <returns>Process payment result</returns>
        public ProcessPaymentResult ProcessRecurringPayment(ProcessPaymentRequest processPaymentRequest)
        {
            var result = new ProcessPaymentResult();

            result.AddError("Recurring payment not supported");
            return(result);
        }
Beispiel #11
0
        /// <summary>
        /// Process recurring payment
        /// </summary>
        /// <param name="processPaymentRequest">Payment info required for an order processing</param>
        /// <returns>Process payment result</returns>
        public async Task <ProcessPaymentResult> ProcessRecurringPayment(ProcessPaymentRequest processPaymentRequest)
        {
            var result = new ProcessPaymentResult();

            result.AddError("Recurring payment not supported");
            return(await Task.FromResult(result));
        }
Beispiel #12
0
        public override ProcessPaymentResult ProcessPayment(ProcessPaymentRequest processPaymentRequest)
        {
            var result = new ProcessPaymentResult();

            result.AllowStoringCreditCardNumber = true;
            switch (_settings.TransactMode)
            {
            case TransactMode.Pending:
                result.NewPaymentStatus = PaymentStatus.Pending;
                break;

            case TransactMode.Authorize:
                result.NewPaymentStatus = PaymentStatus.Authorized;
                break;

            case TransactMode.AuthorizeAndCapture:
                result.NewPaymentStatus = PaymentStatus.Paid;
                break;

            default:
            {
                result.AddError(T("Common.Payment.TranactionTypeNotSupported"));
                return(result);
            }
            }

            return(result);
        }
        public ProcessPaymentResult ProcessRecurringPayment(ProcessPaymentRequest processPaymentRequest)
        {
            ProcessPaymentResult p = new ProcessPaymentResult();

            p.AddError("Recurring payment not supported.");
            return(p);
        }
Beispiel #14
0
        /// <summary>
        /// Process a payment
        /// </summary>
        /// <param name="processPaymentRequest">Payment info required for an order processing</param>
        /// <returns>Process payment result</returns>
        public override ProcessPaymentResult ProcessPayment(ProcessPaymentRequest processPaymentRequest)
        {
            var result   = new ProcessPaymentResult();
            var settings = Services.Settings.LoadSetting <PayPalExpressPaymentSettings>(processPaymentRequest.StoreId);

            var doPayment = DoExpressCheckoutPayment(processPaymentRequest);

            if (doPayment.Ack == AckCodeType.Success)
            {
                if (GetPaymentAction(settings) == PaymentActionCodeType.Authorization)
                {
                    result.AuthorizationTransactionId     = doPayment.DoExpressCheckoutPaymentResponseDetails.PaymentInfo.FirstOrDefault().TransactionID;
                    result.AuthorizationTransactionResult = doPayment.Ack.ToString();

                    result.NewPaymentStatus = PaymentStatus.Authorized;
                }
                else
                {
                    result.CaptureTransactionId     = doPayment.DoExpressCheckoutPaymentResponseDetails.PaymentInfo.FirstOrDefault().TransactionID;
                    result.CaptureTransactionResult = doPayment.Ack.ToString();

                    result.NewPaymentStatus = PaymentStatus.Paid;
                }

                //result.AuthorizationTransactionId = processPaymentRequest.PaypalToken;
                //result.CaptureTransactionId = doPayment.DoExpressCheckoutPaymentResponseDetails.PaymentInfo.FirstOrDefault().TransactionID;
                //result.CaptureTransactionResult = doPayment.Ack.ToString();
            }
            else
            {
                result.NewPaymentStatus = PaymentStatus.Pending;

                if (doPayment?.Errors?.Any() ?? false)
                {
                    foreach (var error in doPayment.Errors)
                    {
                        result.AddError(string.Format("{0} | {1} | {2}", error.ErrorCode, error.ShortMessage, error.LongMessage));
                    }
                }
                else
                {
                    result.AddError(T("Admin.Common.UnknownError") + " " + doPayment.Ack.ToString());
                }
            }

            return(result);
        }
        /// <summary>
        /// Process a payment
        /// </summary>
        /// <param name="processPaymentRequest">Payment info required for an order processing</param>
        /// <returns>Process payment result</returns>
        public ProcessPaymentResult ProcessPayment(ProcessPaymentRequest processPaymentRequest)
        {
            var result = new ProcessPaymentResult();

            var orderGuid = processPaymentRequest.OrderGuid;


            if (orderGuid == Guid.NewGuid())
            {
                result.AddError("SagePay Server transaction code does not exist!");
                return(result);
            }

            var transx = _sagePayServerTransactionService.GetSagePayServerTransactionByVendorTxCode(orderGuid.ToString());

            if (transx == null)
            {
                result.AddError(String.Format("SagePay Server transaction code {0} does not exist.", orderGuid.ToString()));
                return(result);
            }

            if ((transx.Status == "OK") || (transx.Status == "AUTHENTICATED") || (transx.Status == "REGISTERED"))
            {
                if (_sagePayServerPaymentSettings.TransactType == SagePayServerPaymentSettings.TransactTypeValues.PAYMENT)
                {
                    result.NewPaymentStatus = PaymentStatus.Paid;
                }
                else if (_sagePayServerPaymentSettings.TransactType == SagePayServerPaymentSettings.TransactTypeValues.DEFERRED)
                {
                    result.NewPaymentStatus = PaymentStatus.Authorized;
                }
                else
                {
                    result.NewPaymentStatus = PaymentStatus.Pending;
                }
                result.AuthorizationTransactionId     = transx.Id.ToString();
                result.AuthorizationTransactionCode   = transx.VPSTxId;
                result.AuthorizationTransactionResult = transx.ToString();
            }
            else
            {
                result.AddError(transx.StatusDetail);
            }


            return(result);
        }
        /// <summary>
        /// Process a payment
        /// </summary>
        /// <param name="processPaymentRequest">Payment info required for an order processing</param>
        /// <returns>Process payment result</returns>
        public ProcessPaymentResult ProcessPayment(ProcessPaymentRequest processPaymentRequest)
        {
            var result = new ProcessPaymentResult();

            try
            {
                result.AllowStoringCreditCardNumber = false;
                var          customer = _customerService.GetCustomerById(processPaymentRequest.CustomerId);
                var          order    = _orderService.GetOrderByGuid(processPaymentRequest.OrderGuid);
                string       currency = _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId).CurrencyCode;
                PaymentModel pm       = new PaymentModel();
                pm = getPayment("?token=" + processPaymentRequest.CustomValues["paymenttoken"]);
                string paymentid = pm.id;
                string amount    = processPaymentRequest.OrderTotal.ToString();
                amount = Regex.Replace(amount, @"[^\d]", "");

                //string urlappend = "?payment=" + payment + "&amount=" + amount + "&currency=" + currency + "&description=" + description;
                string           urlbuilder = "?payment=" + paymentid + "&amount=" + amount + "&currency=" + currency + "&description=Order from Store ID: " + processPaymentRequest.StoreId.ToString() + " PaymentID: " + pm.id;
                TransactionModel trans      = new TransactionModel();
                //_logger.InsertLog(Core.Domain.Logging.LogLevel.Information, "url for transaction", urlbuilder);
                trans = getTransaction(urlbuilder, pm);
                string responsecode  = trans.response_code;
                string transactionid = trans.id;
                //set the transaction variables
                if (responsecode == "20000")
                {
                    //successful response
                    result.AuthorizationTransactionCode   = transactionid;
                    result.AuthorizationTransactionResult = responsecode;
                    result.NewPaymentStatus = PaymentStatus.Paid;
                    //_logger.InsertLog(Core.Domain.Logging.LogLevel.Information, "success at paymill proceessorder" + responsecode + urlbuilder + paymentid, trans.status + urlbuilder + paymentid, null);
                }
                else
                {
                    //failed transaction
                    _logger.InsertLog(Core.Domain.Logging.LogLevel.Information, "failure at paymill proceessorder" + responsecode, trans.status, null);
                    result.AddError(getErrorcodes(responsecode, trans.status));
                }
            }
            catch (Exception ex)
            {
                _logger.InsertLog(Core.Domain.Logging.LogLevel.Error, ex.Message, ex.ToString());
                result.AddError(ex.ToString());
            }
            return(result);
        }
Beispiel #17
0
        public ProcessPaymentResult ProcessPayment(ProcessPaymentRequest processPaymentRequest)
        {
            var resp = new ProcessPaymentResult
            {
                OrderId      = processPaymentRequest.OrderId,
                CurrencyCode = processPaymentRequest.CurrencyCode,
                AuthorizationTransactionUrl = Settings.NotificationUrl + "/" + processPaymentRequest.OrderId,
                UseAuthUrlToRedirect        = true
            };
            var req = new PreAuth
            {
                id           = GetGivexIdentification(),
                givexNumber  = processPaymentRequest.CardNo,
                reference    = processPaymentRequest.OrderNo + "." + processPaymentRequest.PaymentId,
                amount       = processPaymentRequest.OrderTotal,
                securityCode = processPaymentRequest.Cvv
            };

            try
            {
                var givResp = _givexClient.PreAuth(req);
                if ((givResp != null))
                {
                    resp.AuthorizationTransactionCode = givResp.authCode.ToString();
                    resp.AuthorizedAmount             = givResp.amount;
                    // resp.BalanceAmount = givResp.certBalance;
                }
                else
                {
                    resp.AddError(ErrorCodesPayment.InvalidResponseFromPSP.ToString());
                }
            }
            catch (EndpointNotFoundException endPointExc)
            {
                resp.AddError(ErrorCodesPayment.EndPointNotFound.ToString() + " " + endPointExc.Message);
            }
            catch (FaultException ex)
            {
                resp.AddError(ErrorCodesPayment.RejectedByPSP.ToString() + " " + ex.Message);
            }
            catch (Exception genEx)
            {
                resp.AddError(ErrorCodesPayment.ExceptionInServiceCall.ToString() + " " + genEx.Message);
            }
            return(resp);
        }
Beispiel #18
0
        /// <summary>
        /// Process recurring payment
        /// </summary>
        /// <param name="processPaymentRequest">Payment info required for an order processing</param>
        /// <returns>Process payment result</returns>
        public Task <ProcessPaymentResult> ProcessRecurringPaymentAsync(ProcessPaymentRequest processPaymentRequest)
        {
            var result = new ProcessPaymentResult();

            result.AddError("Recurring method not supported");

            return(Task.FromResult(result));
        }
Beispiel #19
0
        /// <summary>
        /// Process recurring payment
        /// </summary>
        /// <param name="processPaymentRequest">Payment info required for an order processing</param>
        /// <returns>Process payment result</returns>
        public ProcessPaymentResult ProcessRecurringPayment(ProcessPaymentRequest processPaymentRequest)
        {
            var result = new ProcessPaymentResult();

            result.AddError("Not supported transaction type");

            return(result);
        }
        public ProcessPaymentResult ProcessRecurringPayment(ProcessPaymentRequest processPaymentRequest)
        {
            Debug.WriteLine("ProcessRecurringPayment");
            var result = new ProcessPaymentResult();

            result.AddError("Recurring payment not supported");
            return(result);
            //throw new NotImplementedException();
        }
Beispiel #21
0
        /// <summary>
        /// Process a payment
        /// </summary>
        /// <param name="processPaymentRequest">Payment info required for an order processing</param>
        /// <returns>Process payment result</returns>
        public ProcessPaymentResult ProcessPayment(ProcessPaymentRequest processPaymentRequest)
        {
            var result   = new ProcessPaymentResult();
            var customer = _customerService.GetCustomerById(processPaymentRequest.CustomerId);

            var postValues = new Dictionary <string, string>
            {
                { "location_id", _paySafePaymentSettings.LocationId },
                { "payment_method", "cc" },
                { "action", _paySafePaymentSettings.TransactMode == TransactMode.AuthorizeAndCapture ? "sale" : "authonly" },
                { "account_number", processPaymentRequest.CreditCardNumber },
                { "exp_date", $"{processPaymentRequest.CreditCardExpireMonth}{processPaymentRequest.CreditCardExpireYear.ToString().Substring(2, 2)}" },
                { "ccv", processPaymentRequest.CreditCardCvv2 },
                { "transaction_amount", processPaymentRequest.OrderTotal.ToString("0.00", CultureInfo.InvariantCulture) },
                { "billing_street", customer.BillingAddress.Address1 },
                { "billing_city", customer.BillingAddress.City },
                { "billing_phone", customer.BillingAddress.PhoneNumber },
                { "billing_state", customer.BillingAddress.StateProvince.Abbreviation },
                { "billing_zip", customer.BillingAddress.ZipPostalCode }
            };

            var json = JsonConvert.SerializeObject(new { transaction = postValues });
            var data = new StringContent(json, Encoding.UTF8, "application/json");

            try
            {
                _httpClient.DefaultRequestHeaders.Add("developer-id", _paySafePaymentSettings.DeveloperId);
                _httpClient.DefaultRequestHeaders.Add("user-id", _paySafePaymentSettings.UserId);
                _httpClient.DefaultRequestHeaders.Add("user-api-key", _paySafePaymentSettings.UserApiKey);
                var response          = _httpClient.PostAsync(GetUrl(), data).Result;
                var paySafeResponse   = JsonConvert.DeserializeObject <PaySafeResponse>(response.Content.ReadAsStringAsync().Result);
                var transactionResult = paySafeResponse.Transaction;

                if (response.IsSuccessStatusCode && !string.IsNullOrEmpty(transactionResult.Id))
                {
                    result.AuthorizationTransactionCode   = $"{transactionResult.Id},{transactionResult.AuthCode}";
                    result.AuthorizationTransactionResult = $"Approved.  Status ID: {transactionResult.StatusId}, Reason Code: {transactionResult.ReasonCodeId}";

                    result.AvsResult  = transactionResult.AvsEnhanced;
                    result.Cvv2Result = transactionResult.CvvResponse;

                    result.NewPaymentStatus = _paySafePaymentSettings.TransactMode == TransactMode.AuthorizeAndCapture
                        ? PaymentStatus.Paid
                        : PaymentStatus.Authorized;
                }
            }
            catch (Exception exception)
            {
                _logger.Error("PaySafe Error", exception, customer);
                result.AddError("Exception Occurred: " + exception.Message);
                return(result);
            }

            return(result);
        }
Beispiel #22
0
        /// <summary>
        /// Process a payment
        /// </summary>
        /// <param name="processPaymentRequest">Payment info required for an order processing</param>
        /// <returns>Process payment result</returns>
        public override ProcessPaymentResult ProcessPayment(ProcessPaymentRequest processPaymentRequest)
        {
            var result = new ProcessPaymentResult();

            result.NewPaymentStatus = PaymentStatus.Pending;

            if (_paypalStandardSettings.BusinessEmail.IsNullOrEmpty() || _paypalStandardSettings.PdtToken.IsNullOrEmpty())
            {
                result.AddError(T("Plugins.Payments.PayPalStandard.InvalidCredentials"));
            }

            return(result);
        }
        /// <summary>
        /// Process a payment
        /// </summary>
        /// <param name="processPaymentRequest">Payment info required for an order processing</param>
        /// <returns>Process payment result</returns>
        public override ProcessPaymentResult ProcessPayment(ProcessPaymentRequest processPaymentRequest)
        {
            var result = new ProcessPaymentResult();

            result.NewPaymentStatus = PaymentStatus.Pending;

            // codehint: sm-add
            if (_paypalStandardPaymentSettings.BusinessEmail.IsNullOrEmpty() || _paypalStandardPaymentSettings.PdtToken.IsNullOrEmpty())
            {
                result.AddError(_localizationService.GetResource("Plugins.Payments.PayPalStandard.InvalidCredentials"));
            }

            return(result);
        }
Beispiel #24
0
        public ProcessPaymentResult ProcessPayment(ProcessPaymentRequest processPaymentRequest)
        {
            var result = new ProcessPaymentResult();

            var token = processPaymentRequest.CustomValues["paymenttoken"].ToString();
            var primaryStoreCurrency = _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId);
            int amount = (int)(Decimal.Round(processPaymentRequest.OrderTotal, 2) * 100);

            CreateTransactionRequest createTransactionRequest = new CreateTransactionRequest()
            {
                Amount     = amount,
                Currency   = primaryStoreCurrency.CurrencyCode,
                CardId     = token,
                MerchantId = _paylikePaymentSettings.MerchantId,
                Descriptor = string.Empty,
                Custom     = new Dictionary <string, string>()
                {
                }
            };

            createTransactionRequest.Custom.Add("NopOrderGuid", processPaymentRequest.OrderGuid.ToString());

            var createTransactionResponse = _paylikeTransactionService.CreateTransaction(createTransactionRequest);

            if (createTransactionResponse.IsError)
            {
                result.AddError(createTransactionResponse.ErrorMessage);
                result.AddError(createTransactionResponse.ErrorContent);
            }
            else
            {
                result.AuthorizationTransactionId = createTransactionResponse.Content.Id;
                result.NewPaymentStatus           = PaymentStatus.Authorized;
            }

            return(result);
        }
Beispiel #25
0
        /// <summary>
        /// Process a payment
        /// </summary>
        /// <param name="processPaymentRequest">Payment info required for an order processing</param>
        /// <returns>Process payment result</returns>
        public override ProcessPaymentResult ProcessPayment(ProcessPaymentRequest processPaymentRequest)
        {
            var result = new ProcessPaymentResult();

            result.NewPaymentStatus = PaymentStatus.Pending;

            var settings = _commonServices.Settings.LoadSetting <PayPalStandardPaymentSettings>(processPaymentRequest.StoreId);

            if (settings.BusinessEmail.IsEmpty() || settings.PdtToken.IsEmpty())
            {
                result.AddError(T("Plugins.Payments.PayPalStandard.InvalidCredentials"));
            }

            return(result);
        }
Beispiel #26
0
        public ProcessPaymentResult Charge(string token,
                                           decimal orderSubTotal,
                                           int sellerCustomerId,
                                           ProcessPaymentRequest processPaymentRequest)
        {
            var stripeSeller        = _customerEntityService.GetOrCreate(sellerCustomerId);
            var StripeBasedTotal    = NopDecimalToStripeInt(processPaymentRequest.OrderTotal);
            var stripebasedSubTotal = NopDecimalToStripeDecimal(orderSubTotal);

            // fee is 20% of total without shipping
            var appFee       = Convert.ToInt32(Math.Floor(stripebasedSubTotal * 0.2m)); // todo configurable appfee percent
            var chargeAmount = StripeBasedTotal - appFee;

            var chargeOptions = new StripeChargeCreateOptions()
            {
                Amount = chargeAmount,
                SourceTokenOrExistingSourceId = token,
                ApplicationFee = appFee,
                Currency       = "USD" // TODO currency
            };

            _logger.Information("Stripe charge with Token: " + token + ", Amount: " + chargeAmount + ", AppFee: " + appFee);


            var charge = _stripeChargeService.Create(chargeOptions, new StripeRequestOptions()
            {
                IdempotencyKey         = processPaymentRequest.OrderGuid.ToString("N"),
                StripeConnectAccountId = stripeSeller.StripeUserId
            });
            var result = new ProcessPaymentResult();

            if (charge.Paid)
            {
                result.NewPaymentStatus = Core.Domain.Payments.PaymentStatus.Paid;
                var stripeOrderCharge = new StripeOrderCharge();
                stripeOrderCharge.CustomerId       = processPaymentRequest.CustomerId;
                stripeOrderCharge.SellerCustomerId = sellerCustomerId;
                stripeOrderCharge.OrderGuid        = processPaymentRequest.OrderGuid;
                stripeOrderCharge.StripeChargeId   = charge.Id;
                _orderChargeEntityService.Create(stripeOrderCharge);
            }
            else
            {
                result.AddError("Error " + charge.FailureCode + " " + charge.FailureMessage);
            }
            return(result);
        }
        // TODO: need refactor
        public ProcessPaymentResult Capture(string orderId, string amount, string authTransactionNumber)
        {
            var result = new ProcessPaymentResult();

            var completion = CreateCompletion(orderId, amount, authTransactionNumber);

            try
            {
                var receipt = PerformTransation(completion);
                // Build result
            }
            catch (Exception ex)
            {
                result.AddError(ex.Message);
            }

            return(result);
        }
        public ProcessPaymentResult ChargeWithoutValidation(ProcessPaymentRequest paymentRequest)
        {
            var result  = new ProcessPaymentResult();
            var dataKey = paymentRequest.CustomValues["SavedCardVault"] as string;
            var isNewCardSaveAllowed = System.Convert.ToBoolean(paymentRequest.CustomValues["IsNewCardSaveAllowed"]);
            // Expire date "YYMM" format
            var expireDate = GetExpireDate(paymentRequest.CreditCardExpireYear, paymentRequest.CreditCardExpireMonth);

            try
            {
                if (isNewCardSaveAllowed)
                {
                    // Vault Add card
                    dataKey = AddCardToVault(paymentRequest.CreditCardNumber, expireDate, paymentRequest.CustomerId.ToString());
                    // TODO: save into database
                }
                Receipt receipt = null;
                if (!string.IsNullOrEmpty(dataKey))
                {
                    // Create purchase with dataKey
                    var purchase = CreatePurchaseWithVault(dataKey, paymentRequest.OrderGuid.ToString(),
                                                           paymentRequest.OrderTotal.ToString(), paymentRequest.CreditCardCvv2);

                    receipt = PerformTransation(purchase);
                }
                else
                {
                    // Create purchase
                    var purchase = CreatePurchase(paymentRequest.CreditCardNumber, expireDate, paymentRequest.CustomerId.ToString(),
                                                  paymentRequest.OrderGuid.ToString(), paymentRequest.OrderTotal.ToString(), paymentRequest.CreditCardCvv2);

                    receipt = PerformTransation(purchase);
                }
                // Build result
                ConvertToChargeResult(receipt, result);
            }
            catch (Exception ex)
            {
                result.NewPaymentStatus = PaymentStatus.Pending;
                result.AddError(ex.Message);
            }

            return(result);
        }
Beispiel #29
0
        /// <summary>
        /// Process a payment
        /// </summary>
        /// <param name="processPaymentRequest">Payment info required for an order processing</param>
        /// <returns>Process payment result</returns>
        public override ProcessPaymentResult ProcessPayment(ProcessPaymentRequest processPaymentRequest)
        {
            var result   = new ProcessPaymentResult();
            var settings = Services.Settings.LoadSetting <PayPalExpressPaymentSettings>(processPaymentRequest.StoreId);

            var doPayment = DoExpressCheckoutPayment(processPaymentRequest);

            if (doPayment.Ack == AckCodeType.Success)
            {
                if (GetPaymentAction(settings) == PaymentActionCodeType.Authorization)
                {
                    result.AuthorizationTransactionId     = doPayment.DoExpressCheckoutPaymentResponseDetails.PaymentInfo.FirstOrDefault().TransactionID;
                    result.AuthorizationTransactionResult = doPayment.Ack.ToString();

                    result.NewPaymentStatus = PaymentStatus.Authorized;
                }
                else
                {
                    result.CaptureTransactionId     = doPayment.DoExpressCheckoutPaymentResponseDetails.PaymentInfo.FirstOrDefault().TransactionID;
                    result.CaptureTransactionResult = doPayment.Ack.ToString();

                    result.NewPaymentStatus = PaymentStatus.Paid;
                }

                //result.AuthorizationTransactionId = processPaymentRequest.PaypalToken;
                //result.CaptureTransactionId = doPayment.DoExpressCheckoutPaymentResponseDetails.PaymentInfo.FirstOrDefault().TransactionID;
                //result.CaptureTransactionResult = doPayment.Ack.ToString();
            }
            else
            {
                result.NewPaymentStatus = PaymentStatus.Pending;

                result.Errors.Each(x => result.AddError(x));
            }

            return(result);
        }
        /// <summary>
        /// Process a payment
        /// </summary>
        /// <param name="processPaymentRequest">Payment info required for an order processing</param>
        /// <returns>Process payment result</returns>
        public ProcessPaymentResult ProcessPayment(ProcessPaymentRequest processPaymentRequest)
        {
            var customers = new StripeCustomerService();
            var charges   = new StripeChargeService();

            var stripeSourceId = processPaymentRequest.CustomValues["StripeSourceId"] as string;

            var result       = new ProcessPaymentResult();
            var stripeCharge = _stripeService.ChargeAmount(stripeSourceId,
                                                           _stripePaymentSettings.ConnectAccountId,
                                                           processPaymentRequest.OrderGuid.ToString(),
                                                           Decimal.ToInt32(processPaymentRequest.OrderTotal * 100));

            if (stripeCharge.Status == "succeeded")
            {
                result.NewPaymentStatus = PaymentStatus.Paid;
            }
            else
            {
                result.NewPaymentStatus = PaymentStatus.Voided;
                result.AddError(stripeCharge.FailureMessage);
            }
            return(result);
        }
        /// <summary>
        /// Process a payment
        /// </summary>
        /// <param name="processPaymentRequest">Payment info required for an order processing</param>
        /// <returns>Process payment result</returns>
        public ProcessPaymentResult ProcessPayment(ProcessPaymentRequest processPaymentRequest)
        {
            var result = new ProcessPaymentResult();

            var customer = _customerService.GetCustomerById(processPaymentRequest.CustomerId);

            var webClient = new WebClient();
            var form = new NameValueCollection();
            form.Add("x_login", _authorizeNetPaymentSettings.LoginId);
            form.Add("x_tran_key", _authorizeNetPaymentSettings.TransactionKey);

            //we should not send "x_test_request" parameter. otherwise, the transaction won't be logged in the sandbox
            //if (_authorizeNetPaymentSettings.UseSandbox)
            //    form.Add("x_test_request", "TRUE");
            //else
            //    form.Add("x_test_request", "FALSE");

            form.Add("x_delim_data", "TRUE");
            form.Add("x_delim_char", "|");
            form.Add("x_encap_char", "");
            form.Add("x_version", GetApiVersion());
            form.Add("x_relay_response", "FALSE");
            form.Add("x_method", "CC");
            form.Add("x_currency_code", _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId).CurrencyCode);
            if (_authorizeNetPaymentSettings.TransactMode == TransactMode.Authorize)
                form.Add("x_type", "AUTH_ONLY");
            else if (_authorizeNetPaymentSettings.TransactMode == TransactMode.AuthorizeAndCapture)
                form.Add("x_type", "AUTH_CAPTURE");
            else
                throw new NasException("Not supported transaction mode");

            var orderTotal = Math.Round(processPaymentRequest.OrderTotal, 2);
            form.Add("x_amount", orderTotal.ToString("0.00", CultureInfo.InvariantCulture));
            form.Add("x_card_num", processPaymentRequest.CreditCardNumber);
            form.Add("x_exp_date", processPaymentRequest.CreditCardExpireMonth.ToString("D2") + processPaymentRequest.CreditCardExpireYear.ToString());
            form.Add("x_card_code", processPaymentRequest.CreditCardCvv2);
            form.Add("x_first_name", customer.BillingAddress.FirstName);
            form.Add("x_last_name", customer.BillingAddress.LastName);
            if (!string.IsNullOrEmpty(customer.BillingAddress.Company))
                form.Add("x_company", customer.BillingAddress.Company);
            form.Add("x_address", customer.BillingAddress.Address1);
            form.Add("x_city", customer.BillingAddress.City);
            if (customer.BillingAddress.StateProvince != null)
                form.Add("x_state", customer.BillingAddress.StateProvince.Abbreviation);
            form.Add("x_zip", customer.BillingAddress.ZipPostalCode);
            if (customer.BillingAddress.Country != null)
                form.Add("x_country", customer.BillingAddress.Country.TwoLetterIsoCode);
            //20 chars maximum
            form.Add("x_invoice_num", processPaymentRequest.OrderGuid.ToString().Substring(0, 20));
            form.Add("x_customer_ip", _webHelper.GetCurrentIpAddress());

            string reply = null;
            Byte[] responseData = webClient.UploadValues(GetAuthorizeNETUrl(), form);
            reply = Encoding.ASCII.GetString(responseData);

            if (!String.IsNullOrEmpty(reply))
            {
                string[] responseFields = reply.Split('|');
                switch (responseFields[0])
                {
                    case "1":
                        result.AuthorizationTransactionCode = string.Format("{0},{1}", responseFields[6], responseFields[4]);
                        result.AuthorizationTransactionResult = string.Format("Approved ({0}: {1})", responseFields[2], responseFields[3]);
                        result.AvsResult = responseFields[5];
                        //responseFields[38];
                        if (_authorizeNetPaymentSettings.TransactMode == TransactMode.Authorize)
                        {
                            result.NewPaymentStatus = PaymentStatus.Authorized;
                        }
                        else
                        {
                            result.NewPaymentStatus = PaymentStatus.Paid;
                        }
                        break;
                    case "2":
                        result.AddError(string.Format("Declined ({0}: {1})", responseFields[2], responseFields[3]));
                        break;
                    case "3":
                        result.AddError(string.Format("Error: {0}", reply));
                        break;

                }
            }
            else
            {
                result.AddError("Authorize.NET unknown error");
            }

            return result;
        }
 /// <summary>
 /// Process recurring payment
 /// </summary>
 /// <param name="processPaymentRequest">Payment info required for an order processing</param>
 /// <returns>Process payment result</returns>
 public ProcessPaymentResult ProcessRecurringPayment(ProcessPaymentRequest processPaymentRequest)
 {
     var result = new ProcessPaymentResult();
     result.AddError("Recurring payment not supported");
     return result;
 }
        protected ProcessPaymentResult AuthorizeOrSale(ProcessPaymentRequest processPaymentRequest, bool authorizeOnly)
        {
            var result = new ProcessPaymentResult();

            var customer = _customerService.GetCustomerById(processPaymentRequest.CustomerId);
            if (customer == null)
                throw new Exception("Customer cannot be loaded");

            var req = new DoDirectPaymentReq();
            req.DoDirectPaymentRequest = new DoDirectPaymentRequestType();
            req.DoDirectPaymentRequest.Version = GetApiVersion();
            var details = new DoDirectPaymentRequestDetailsType();
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails = details;
            details.IPAddress = _webHelper.GetCurrentIpAddress();
            if (authorizeOnly)
                details.PaymentAction = PaymentActionCodeType.Authorization;
            else
                details.PaymentAction = PaymentActionCodeType.Sale;
            //credit card
            details.CreditCard = new CreditCardDetailsType();
            details.CreditCard.CreditCardNumber = processPaymentRequest.CreditCardNumber;
            details.CreditCard.CreditCardType = GetPaypalCreditCardType(processPaymentRequest.CreditCardType);
            details.CreditCard.ExpMonthSpecified = true;
            details.CreditCard.ExpMonth = processPaymentRequest.CreditCardExpireMonth;
            details.CreditCard.ExpYearSpecified = true;
            details.CreditCard.ExpYear = processPaymentRequest.CreditCardExpireYear;
            details.CreditCard.CVV2 = processPaymentRequest.CreditCardCvv2;
            details.CreditCard.CardOwner = new PayerInfoType();
            details.CreditCard.CardOwner.PayerCountry = GetPaypalCountryCodeType(customer.BillingAddress.Country);
            details.CreditCard.CreditCardTypeSpecified = true;
            //billing address
            details.CreditCard.CardOwner.Address = new AddressType();
            details.CreditCard.CardOwner.Address.CountrySpecified = true;
            details.CreditCard.CardOwner.Address.Street1 = customer.BillingAddress.Address1;
            details.CreditCard.CardOwner.Address.Street2 = customer.BillingAddress.Address2;
            details.CreditCard.CardOwner.Address.CityName = customer.BillingAddress.City;
            if (customer.BillingAddress.StateProvince != null)
                details.CreditCard.CardOwner.Address.StateOrProvince = customer.BillingAddress.StateProvince.Abbreviation;
            else
                details.CreditCard.CardOwner.Address.StateOrProvince = "CA";
            details.CreditCard.CardOwner.Address.Country = GetPaypalCountryCodeType(customer.BillingAddress.Country);
            details.CreditCard.CardOwner.Address.PostalCode = customer.BillingAddress.ZipPostalCode;
            details.CreditCard.CardOwner.Payer = customer.BillingAddress.Email;
            details.CreditCard.CardOwner.PayerName = new PersonNameType();
            details.CreditCard.CardOwner.PayerName.FirstName = customer.BillingAddress.FirstName;
            details.CreditCard.CardOwner.PayerName.LastName = customer.BillingAddress.LastName;
            //order totals
            var payPalCurrency = PaypalHelper.GetPaypalCurrency(_currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId));
            details.PaymentDetails = new PaymentDetailsType();
            details.PaymentDetails.OrderTotal = new BasicAmountType();
            details.PaymentDetails.OrderTotal.Value = Math.Round(processPaymentRequest.OrderTotal, 2).ToString("N", new CultureInfo("en-us"));
            details.PaymentDetails.OrderTotal.currencyID = payPalCurrency;
            details.PaymentDetails.Custom = processPaymentRequest.OrderGuid.ToString();
            details.PaymentDetails.ButtonSource = "NasCommerceCart";
            //pass product names and totals to PayPal
            //if (_paypalDirectPaymentSettings.PassProductNamesAndTotals)
            //{
            //    //individual items
                //var cart = customer.ShoppingCartItems
                //    .Where(x=>x.ShoppingCartType == ShoppingCartType.ShoppingCart)
                //    .Where(x=>x.StoreId == processPaymentRequest.StoreId)
                //    .ToList();
            //    var cartItems = new PaymentDetailsItemType[cart.Count];
            //    for (int i = 0; i < cart.Count; i++)
            //    {
            //        var sc = cart[i];
            //        decimal taxRate = decimal.Zero;
            //        var customer = processPaymentRequest.Customer;
            //        decimal scUnitPrice = _priceCalculationService.GetUnitPrice(sc, true);
            //        decimal scSubTotal = _priceCalculationService.GetSubTotal(sc, true);
            //        decimal scUnitPriceInclTax = _taxService.GetProductPrice(sc.ProductVariant, scUnitPrice, true, customer, out taxRate);
            //        decimal scUnitPriceExclTax = _taxService.GetProductPrice(sc.ProductVariant, scUnitPrice, false, customer, out taxRate);
            //        //decimal scSubTotalInclTax = _taxService.GetProductPrice(sc.ProductVariant, scSubTotal, true, customer, out taxRate);
            //        //decimal scSubTotalExclTax = _taxService.GetProductPrice(sc.ProductVariant, scSubTotal, false, customer, out taxRate);
            //        cartItems[i] = new PaymentDetailsItemType()
            //        {
            //            Name = sc.ProductVariant.FullProductName,
            //            Number = sc.ProductVariant.Id.ToString(),
            //            Quantity = sc.Quantity.ToString(),
            //            Amount = new BasicAmountType()
            //            {
            //                currencyID = payPalCurrency,
            //                Value = scUnitPriceExclTax.ToString("N", new CultureInfo("en-us")),
            //            },
            //            Tax = new BasicAmountType()
            //            {
            //                currencyID = payPalCurrency,
            //                Value = (scUnitPriceInclTax - scUnitPriceExclTax).ToString("N", new CultureInfo("en-us")),
            //            },
            //        };
            //    };
            //    details.PaymentDetails.PaymentDetailsItem = cartItems;
            //    //other totals (undone)
            //    details.PaymentDetails.ItemTotal = null;
            //    details.PaymentDetails.ShippingTotal = null;
            //    details.PaymentDetails.TaxTotal = null;
            //    details.PaymentDetails.HandlingTotal = null;
            //}
            //shipping
            if (customer.ShippingAddress != null)
            {
                if (customer.ShippingAddress.StateProvince != null && customer.ShippingAddress.Country != null)
                {
                    var shippingAddress = new AddressType();
                    shippingAddress.Name = customer.ShippingAddress.FirstName + " " + customer.ShippingAddress.LastName;
                    shippingAddress.Street1 = customer.ShippingAddress.Address1;
                    shippingAddress.CityName = customer.ShippingAddress.City;
                    shippingAddress.StateOrProvince = customer.ShippingAddress.StateProvince.Abbreviation;
                    shippingAddress.PostalCode = customer.ShippingAddress.ZipPostalCode;
                    shippingAddress.Country = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), customer.ShippingAddress.Country.TwoLetterIsoCode, true);
                    shippingAddress.CountrySpecified = true;
                    details.PaymentDetails.ShipToAddress = shippingAddress;
                }
            }

            //send request
            using (var service2 = new PayPalAPIAASoapBinding())
            {
                if (!_paypalDirectPaymentSettings.UseSandbox)
                    service2.Url = "https://api-3t.paypal.com/2.0/";
                else
                    service2.Url = "https://api-3t.sandbox.paypal.com/2.0/";

                service2.RequesterCredentials = new CustomSecurityHeaderType();
                service2.RequesterCredentials.Credentials = new UserIdPasswordType();
                service2.RequesterCredentials.Credentials.Username = _paypalDirectPaymentSettings.ApiAccountName;
                service2.RequesterCredentials.Credentials.Password = _paypalDirectPaymentSettings.ApiAccountPassword;
                service2.RequesterCredentials.Credentials.Signature = _paypalDirectPaymentSettings.Signature;
                service2.RequesterCredentials.Credentials.Subject = "";

                DoDirectPaymentResponseType response = service2.DoDirectPayment(req);

                string error = "";
                bool success = PaypalHelper.CheckSuccess(response, out error);
                if (success)
                {
                    result.AvsResult = response.AVSCode;
                    result.AuthorizationTransactionCode = response.CVV2Code;
                    if (authorizeOnly)
                    {
                        result.AuthorizationTransactionId = response.TransactionID;
                        result.AuthorizationTransactionResult = response.Ack.ToString();

                        result.NewPaymentStatus = PaymentStatus.Authorized;
                    }
                    else
                    {
                        result.CaptureTransactionId = response.TransactionID;
                        result.CaptureTransactionResult = response.Ack.ToString();

                        result.NewPaymentStatus = PaymentStatus.Paid;
                    }
                }
                else
                {
                    result.AddError(error);
                }
            }
            return result;
        }
        /// <summary>
        /// Process recurring payment
        /// </summary>
        /// <param name="processPaymentRequest">Payment info required for an order processing</param>
        /// <returns>Process payment result</returns>
        public ProcessPaymentResult ProcessRecurringPayment(ProcessPaymentRequest processPaymentRequest)
        {
            var result = new ProcessPaymentResult();

            result.AllowStoringCreditCardNumber = true;
            switch (_manualPaymentSettings.TransactMode)
            {
                case TransactMode.Pending:
                    result.NewPaymentStatus = PaymentStatus.Pending;
                    break;
                case TransactMode.Authorize:
                    result.NewPaymentStatus = PaymentStatus.Authorized;
                    break;
                case TransactMode.AuthorizeAndCapture:
                    result.NewPaymentStatus = PaymentStatus.Paid;
                    break;
                default:
                    {
                        result.AddError("Not supported transaction type");
                        return result;
                    }
            }

            return result;
        }
        /// <summary>
        /// Process recurring payment
        /// </summary>
        /// <param name="processPaymentRequest">Payment info required for an order processing</param>
        /// <returns>Process payment result</returns>
        public ProcessPaymentResult ProcessRecurringPayment(ProcessPaymentRequest processPaymentRequest)
        {
            var result = new ProcessPaymentResult();

            var customer = _customerService.GetCustomerById(processPaymentRequest.CustomerId);

            var req = new CreateRecurringPaymentsProfileReq();
            req.CreateRecurringPaymentsProfileRequest = new CreateRecurringPaymentsProfileRequestType();
            req.CreateRecurringPaymentsProfileRequest.Version = GetApiVersion();
            var details = new CreateRecurringPaymentsProfileRequestDetailsType();
            req.CreateRecurringPaymentsProfileRequest.CreateRecurringPaymentsProfileRequestDetails = details;

            details.CreditCard = new CreditCardDetailsType();
            details.CreditCard.CreditCardNumber = processPaymentRequest.CreditCardNumber;
            details.CreditCard.CreditCardType = GetPaypalCreditCardType(processPaymentRequest.CreditCardType);
            details.CreditCard.ExpMonthSpecified = true;
            details.CreditCard.ExpMonth = processPaymentRequest.CreditCardExpireMonth;
            details.CreditCard.ExpYearSpecified = true;
            details.CreditCard.ExpYear = processPaymentRequest.CreditCardExpireYear;
            details.CreditCard.CVV2 = processPaymentRequest.CreditCardCvv2;
            details.CreditCard.CardOwner = new PayerInfoType();
            details.CreditCard.CardOwner.PayerCountry = GetPaypalCountryCodeType(customer.BillingAddress.Country);
            details.CreditCard.CreditCardTypeSpecified = true;

            details.CreditCard.CardOwner.Address = new AddressType();
            details.CreditCard.CardOwner.Address.CountrySpecified = true;
            details.CreditCard.CardOwner.Address.Street1 = customer.BillingAddress.Address1;
            details.CreditCard.CardOwner.Address.Street2 = customer.BillingAddress.Address2;
            details.CreditCard.CardOwner.Address.CityName = customer.BillingAddress.City;
            if (customer.BillingAddress.StateProvince != null)
                details.CreditCard.CardOwner.Address.StateOrProvince = customer.BillingAddress.StateProvince.Abbreviation;
            else
                details.CreditCard.CardOwner.Address.StateOrProvince = "CA";
            details.CreditCard.CardOwner.Address.Country = GetPaypalCountryCodeType(customer.BillingAddress.Country);
            details.CreditCard.CardOwner.Address.PostalCode = customer.BillingAddress.ZipPostalCode;
            details.CreditCard.CardOwner.Payer = customer.BillingAddress.Email;
            details.CreditCard.CardOwner.PayerName = new PersonNameType();
            details.CreditCard.CardOwner.PayerName.FirstName = customer.BillingAddress.FirstName;
            details.CreditCard.CardOwner.PayerName.LastName = customer.BillingAddress.LastName;

            //start date
            details.RecurringPaymentsProfileDetails = new RecurringPaymentsProfileDetailsType();
            details.RecurringPaymentsProfileDetails.BillingStartDate = DateTime.UtcNow;
            details.RecurringPaymentsProfileDetails.ProfileReference = processPaymentRequest.OrderGuid.ToString();

            //schedule
            details.ScheduleDetails = new ScheduleDetailsType();
            details.ScheduleDetails.Description = "Recurring payment";
            details.ScheduleDetails.PaymentPeriod = new BillingPeriodDetailsType();
            details.ScheduleDetails.PaymentPeriod.Amount = new BasicAmountType();
            details.ScheduleDetails.PaymentPeriod.Amount.Value = Math.Round(processPaymentRequest.OrderTotal, 2).ToString("N", new CultureInfo("en-us"));
            details.ScheduleDetails.PaymentPeriod.Amount.currencyID = PaypalHelper.GetPaypalCurrency(_currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId));
            details.ScheduleDetails.PaymentPeriod.BillingFrequency = processPaymentRequest.RecurringCycleLength;
            switch (processPaymentRequest.RecurringCyclePeriod)
            {
                case RecurringProductCyclePeriod.Days:
                    details.ScheduleDetails.PaymentPeriod.BillingPeriod = BillingPeriodType.Day;
                    break;
                case RecurringProductCyclePeriod.Weeks:
                    details.ScheduleDetails.PaymentPeriod.BillingPeriod = BillingPeriodType.Week;
                    break;
                case RecurringProductCyclePeriod.Months:
                    details.ScheduleDetails.PaymentPeriod.BillingPeriod = BillingPeriodType.Month;
                    break;
                case RecurringProductCyclePeriod.Years:
                    details.ScheduleDetails.PaymentPeriod.BillingPeriod = BillingPeriodType.Year;
                    break;
                default:
                    throw new NasException("Not supported cycle period");
            }
            details.ScheduleDetails.PaymentPeriod.TotalBillingCycles = processPaymentRequest.RecurringTotalCycles;
            details.ScheduleDetails.PaymentPeriod.TotalBillingCyclesSpecified = true;

            using (var service2 = new PayPalAPIAASoapBinding())
            {
                if (!_paypalDirectPaymentSettings.UseSandbox)
                    service2.Url = "https://api-3t.paypal.com/2.0/";
                else
                    service2.Url = "https://api-3t.sandbox.paypal.com/2.0/";

                service2.RequesterCredentials = new CustomSecurityHeaderType();
                service2.RequesterCredentials.Credentials = new UserIdPasswordType();
                service2.RequesterCredentials.Credentials.Username = _paypalDirectPaymentSettings.ApiAccountName;
                service2.RequesterCredentials.Credentials.Password = _paypalDirectPaymentSettings.ApiAccountPassword;
                service2.RequesterCredentials.Credentials.Signature = _paypalDirectPaymentSettings.Signature;
                service2.RequesterCredentials.Credentials.Subject = "";

                CreateRecurringPaymentsProfileResponseType response = service2.CreateRecurringPaymentsProfile(req);

                string error = "";
                bool success = PaypalHelper.CheckSuccess(response, out error);
                if (success)
                {
                    result.NewPaymentStatus = PaymentStatus.Pending;
                    if (response.CreateRecurringPaymentsProfileResponseDetails != null)
                    {
                        result.SubscriptionTransactionId = response.CreateRecurringPaymentsProfileResponseDetails.ProfileID;
                    }
                }
                else
                {
                    result.AddError(error);
                }
            }

            return result;
        }
        /// <summary>
        /// Process recurring payment
        /// </summary>
        /// <param name="processPaymentRequest">Payment info required for an order processing</param>
        /// <returns>Process payment result</returns>
        public ProcessPaymentResult ProcessRecurringPayment(ProcessPaymentRequest processPaymentRequest)
        {
            var result = new ProcessPaymentResult();

            var authentication = PopulateMerchantAuthentication();
            if (!processPaymentRequest.IsRecurringPayment)
            {
                var customer = _customerService.GetCustomerById(processPaymentRequest.CustomerId);

                var subscription = new ARBSubscriptionType();
                var creditCard = new net.authorize.api.CreditCardType();

                subscription.name = processPaymentRequest.OrderGuid.ToString();

                creditCard.cardNumber = processPaymentRequest.CreditCardNumber;
                creditCard.expirationDate = processPaymentRequest.CreditCardExpireYear + "-" + processPaymentRequest.CreditCardExpireMonth; // required format for API is YYYY-MM
                creditCard.cardCode = processPaymentRequest.CreditCardCvv2;

                subscription.payment = new PaymentType();
                subscription.payment.Item = creditCard;

                subscription.billTo = new NameAndAddressType();
                subscription.billTo.firstName = customer.BillingAddress.FirstName;
                subscription.billTo.lastName = customer.BillingAddress.LastName;
                subscription.billTo.address = customer.BillingAddress.Address1 + " " + customer.BillingAddress.Address2;
                subscription.billTo.city = customer.BillingAddress.City;
                if (customer.BillingAddress.StateProvince != null)
                {
                    subscription.billTo.state = customer.BillingAddress.StateProvince.Abbreviation;
                }
                subscription.billTo.zip = customer.BillingAddress.ZipPostalCode;

                if (customer.ShippingAddress != null)
                {
                    subscription.shipTo = new NameAndAddressType();
                    subscription.shipTo.firstName = customer.ShippingAddress.FirstName;
                    subscription.shipTo.lastName = customer.ShippingAddress.LastName;
                    subscription.shipTo.address = customer.ShippingAddress.Address1 + " " + customer.ShippingAddress.Address2;
                    subscription.shipTo.city = customer.ShippingAddress.City;
                    if (customer.ShippingAddress.StateProvince != null)
                    {
                        subscription.shipTo.state = customer.ShippingAddress.StateProvince.Abbreviation;
                    }
                    subscription.shipTo.zip = customer.ShippingAddress.ZipPostalCode;

                }

                subscription.customer = new CustomerType();
                subscription.customer.email = customer.BillingAddress.Email;
                subscription.customer.phoneNumber = customer.BillingAddress.PhoneNumber;

                subscription.order = new OrderType();
                subscription.order.description = "Recurring payment";

                // Create a subscription that is leng of specified occurrences and interval is amount of days ad runs

                subscription.paymentSchedule = new PaymentScheduleType();
                DateTime dtNow = DateTime.UtcNow;
                subscription.paymentSchedule.startDate = new DateTime(dtNow.Year, dtNow.Month, dtNow.Day);
                subscription.paymentSchedule.startDateSpecified = true;

                subscription.paymentSchedule.totalOccurrences = Convert.ToInt16(processPaymentRequest.RecurringTotalCycles);
                subscription.paymentSchedule.totalOccurrencesSpecified = true;

                var orderTotal = Math.Round(processPaymentRequest.OrderTotal, 2);
                subscription.amount = orderTotal;
                subscription.amountSpecified = true;

                // Interval can't be updated once a subscription is created.
                subscription.paymentSchedule.interval = new PaymentScheduleTypeInterval();
                switch (processPaymentRequest.RecurringCyclePeriod)
                {
                    case RecurringProductCyclePeriod.Days:
                        subscription.paymentSchedule.interval.length = Convert.ToInt16(processPaymentRequest.RecurringCycleLength);
                        subscription.paymentSchedule.interval.unit = ARBSubscriptionUnitEnum.days;
                        break;
                    case RecurringProductCyclePeriod.Weeks:
                        subscription.paymentSchedule.interval.length = Convert.ToInt16(processPaymentRequest.RecurringCycleLength * 7);
                        subscription.paymentSchedule.interval.unit = ARBSubscriptionUnitEnum.days;
                        break;
                    case RecurringProductCyclePeriod.Months:
                        subscription.paymentSchedule.interval.length = Convert.ToInt16(processPaymentRequest.RecurringCycleLength);
                        subscription.paymentSchedule.interval.unit = ARBSubscriptionUnitEnum.months;
                        break;
                    case RecurringProductCyclePeriod.Years:
                        subscription.paymentSchedule.interval.length = Convert.ToInt16(processPaymentRequest.RecurringCycleLength * 12);
                        subscription.paymentSchedule.interval.unit = ARBSubscriptionUnitEnum.months;
                        break;
                    default:
                        throw new NasException("Not supported cycle period");
                }

                using (var webService = new net.authorize.api.Service())
                {
                    if (_authorizeNetPaymentSettings.UseSandbox)
                        webService.Url = "https://apitest.authorize.net/soap/v1/Service.asmx";
                    else
                        webService.Url = "https://api.authorize.net/soap/v1/Service.asmx";

                    var response = webService.ARBCreateSubscription(authentication, subscription);

                    if (response.resultCode == MessageTypeEnum.Ok)
                    {
                        result.SubscriptionTransactionId = response.subscriptionId.ToString();
                        result.AuthorizationTransactionCode = response.resultCode.ToString();
                        result.AuthorizationTransactionResult = string.Format("Approved ({0}: {1})", response.resultCode.ToString(), response.subscriptionId.ToString());

                        if (_authorizeNetPaymentSettings.TransactMode == TransactMode.Authorize)
                        {
                            result.NewPaymentStatus = PaymentStatus.Authorized;
                        }
                        else
                        {
                            result.NewPaymentStatus = PaymentStatus.Paid;
                        }
                    }
                    else
                    {
                        result.AddError(string.Format("Error processing recurring payment. {0}", GetErrors(response)));
                    }
                }
            }

            return result;
        }