public static ProcessorArgumentCollection AsProcessorArgumentCollection(this CreditCardFormData creditCard)
 {
     return(new ProcessorArgumentCollection()
     {
         { "creditCardType", creditCard.CreditCardType },
         { "cardholderName", creditCard.CardholderName },
         { "cardNumber", creditCard.CardNumber },
         { "expireMonth", creditCard.ExpireMonth },
         { "expireYear", creditCard.ExpireYear },
         { "cardCode", creditCard.CardCode }
     });
 }
        /// <summary>
        /// Gets a single use token that can be used in place of a credit card details. 
        /// The token can be used once for creating a new charge. 
        /// </summary>
        /// <param name="creditCard"></param>
        /// <param name="address"></param>
        /// <param name="settings"></param>
        /// <returns></returns>
        public static string GetCardToken(CreditCardFormData creditCard, IAddress address, StripeProcessorSettings settings)
        {
            var requestParams = new NameValueCollection();
            requestParams.Add("card[number]", creditCard.CardNumber);
            requestParams.Add("card[exp_month]", creditCard.ExpireMonth);
            requestParams.Add("card[exp_year]", creditCard.ExpireYear);
            requestParams.Add("card[cvc]", creditCard.CardCode);
            requestParams.Add("card[name]", creditCard.CardholderName);

            if (address != null)
            {
                requestParams.Add("card[address_line1]", address.Address1);
                requestParams.Add("card[address_line2]", address.Address2);
                requestParams.Add("card[address_city]", address.Locality);
                if (!string.IsNullOrEmpty(address.Region))
                    requestParams.Add("card[address_state]", address.Region);
                requestParams.Add("card[address_zip]", address.PostalCode);
                if (!string.IsNullOrEmpty(address.CountryCode))
                    requestParams.Add("card[address_country]", address.CountryCode);
            }

            string postData =
                requestParams.AllKeys.Aggregate("",
                    (current, key) => current + (key + "=" + HttpUtility.UrlEncode(requestParams[key]) + "&"))
                    .TrimEnd('&');

            // https://stripe.com/docs/api#create_card_token
            var response = StripeHelper.MakeStripeApiRequest("https://api.stripe.com/v1/tokens", "POST", requestParams, settings);
            string apiResponse = null;
            using (var reader = new StreamReader(response.GetResponseStream()))
            {
                apiResponse = reader.ReadToEnd();
            }
            JObject responseJson = JObject.Parse(apiResponse);
            switch (response.StatusCode)
            {
                case HttpStatusCode.OK: // 200
                    return (string) responseJson["id"];

                default:

                    throw new Exception("Stripe error");
            }
        }
        /// <summary>
        ///     Processes the Authorize and AuthorizeAndCapture transactions
        /// </summary>
        /// <param name="invoice">The <see cref="IInvoice" /> to be paid</param>
        /// <param name="payment">The <see cref="IPayment" /> record</param>
        /// <param name="transactionMode">Authorize or AuthorizeAndCapture</param>
        /// <param name="amount">The money amount to be processed</param>
        /// <param name="creditCard">The <see cref="CreditCardFormData" /></param>
        /// <returns>The <see cref="IPaymentResult" /></returns>
        public IPaymentResult ProcessPayment(IInvoice invoice, IPayment payment, TransactionMode transactionMode,
            decimal amount, CreditCardFormData creditCard)
        {
            if (!IsValidCurrencyCode(invoice.CurrencyCode()))
                return new PaymentResult(Attempt<IPayment>.Fail(payment, new Exception("Invalid currency")), invoice,
                    false);

            // The minimum amount is $0.50 (or equivalent in charge currency).
            // Test that the payment meets the minimum amount (for USD only).
            if (invoice.CurrencyCode() == "USD")
            {
                if (amount < 0.5m)
                    return
                        new PaymentResult(
                            Attempt<IPayment>.Fail(payment, new Exception("Invalid amount (less than 0.50 USD)")),
                            invoice, false);
            }
            else
            {
                if (amount < 1)
                    return
                        new PaymentResult(
                            Attempt<IPayment>.Fail(payment,
                                new Exception("Invalid amount (less than 1 " + invoice.CurrencyCode() + ")")),
                            invoice, false);
            }

            var requestParams = StripeHelper.PreparePostDataForProcessPayment(invoice.GetBillingAddress(), transactionMode,
                ConvertAmount(invoice, amount), invoice.CurrencyCode(), creditCard, invoice.PrefixedInvoiceNumber(),
                string.Format("Full invoice #{0}", invoice.PrefixedInvoiceNumber()));

            // https://stripe.com/docs/api#create_charge
            try
            {
                var response = StripeHelper.MakeStripeApiRequest("https://api.stripe.com/v1/charges", "POST", requestParams, _settings);
                return GetProcessPaymentResult(invoice, payment, response);
            }
            catch (WebException ex)
            {
                return GetProcessPaymentResult(invoice, payment, (HttpWebResponse) ex.Response);
            }
        }
        /// <summary>
        ///     Processes the Authorize and AuthorizeAndCapture transactions
        /// </summary>
        /// <param name="invoice">The <see cref="IInvoice" /> to be paid</param>
        /// <param name="payment">The <see cref="IPayment" /> record</param>
        /// <param name="transactionMode">Authorize or AuthorizeAndCapture</param>
        /// <param name="amount">The money amount to be processed</param>
        /// <param name="creditCard">The <see cref="CreditCardFormData" /></param>
        /// <returns>The <see cref="IPaymentResult" /></returns>
        public IPaymentResult ProcessPayment(IInvoice invoice, IPayment payment, TransactionMode transactionMode,
            decimal amount, CreditCardFormData creditCard)
        {
            if (!IsValidCurrencyCode(invoice.CurrencyCode()))
                return new PaymentResult(Attempt<IPayment>.Fail(payment, new Exception("Invalid currency")), invoice,
                    false);

            // The minimum amount is $0.50 (or equivalent in charge currency). 
            // Test that the payment meets the minimum amount (for USD only).
            if (invoice.CurrencyCode() == "USD")
            {
                if (amount < 0.5m)
                    return
                        new PaymentResult(
                            Attempt<IPayment>.Fail(payment, new Exception("Invalid amount (less than 0.50 USD)")),
                            invoice, false);
            }
            else
            {
                if (amount < 1)
                    return
                        new PaymentResult(
                            Attempt<IPayment>.Fail(payment,
                                new Exception("Invalid amount (less than 1 " + invoice.CurrencyCode() + ")")),
                            invoice, false);
            }

            var requestParams = new NameValueCollection();
            requestParams.Add("amount", ConvertAmount(invoice, amount));
            requestParams.Add("currency", invoice.CurrencyCode());
            if (transactionMode == TransactionMode.Authorize)
                requestParams.Add("capture", "false");
            requestParams.Add("card[number]", creditCard.CardNumber);
            requestParams.Add("card[exp_month]", creditCard.ExpireMonth);
            requestParams.Add("card[exp_year]", creditCard.ExpireYear);
            requestParams.Add("card[cvc]", creditCard.CardCode);
            requestParams.Add("card[name]", creditCard.CardholderName);

            // Billing address
            IAddress address = invoice.GetBillingAddress();
            //requestParams.Add("receipt_email", address.Email); // note: this will send receipt email - maybe there should be a setting controlling if this is passed or not. Email could also be added to metadata
            requestParams.Add("card[address_line1]", address.Address1);
            requestParams.Add("card[address_line2]", address.Address2);
            requestParams.Add("card[address_city]", address.Locality);
            if (!string.IsNullOrEmpty(address.Region)) requestParams.Add("card[address_state]", address.Region);
            requestParams.Add("card[address_zip]", address.PostalCode);
            if (!string.IsNullOrEmpty(address.CountryCode))
                requestParams.Add("card[address_country]", address.CountryCode);
            requestParams.Add("metadata[invoice_number]", invoice.PrefixedInvoiceNumber());
            requestParams.Add("description", string.Format("Full invoice #{0}", invoice.PrefixedInvoiceNumber()));

            string postData =
                requestParams.AllKeys.Aggregate("",
                    (current, key) => current + (key + "=" + HttpUtility.UrlEncode(requestParams[key]) + "&"))
                    .TrimEnd('&');

            // https://stripe.com/docs/api#create_charge
            try
            {
                var response = MakeStripeApiRequest("https://api.stripe.com/v1/charges", "POST", requestParams);
                return GetProcessPaymentResult(invoice, payment, response);
            }
            catch (WebException ex)
            {
                return GetProcessPaymentResult(invoice, payment, (HttpWebResponse) ex.Response);
            }
        }
Beispiel #5
0
        public void Can_Authorize_A_Payment()
        {
            //// Arrange
            var creditCardMethod = Provider.GetPaymentGatewayMethodByPaymentCode("CreditCard");
            Assert.NotNull(creditCardMethod);

            var ccEntry = new CreditCardFormData()
            {
                CreditCardType = "VISA",
                CardholderName = "Alex Lindgren",
                CardNumber = "4012888888881881",
                CardCode = "111",
                ExpireMonth = "09",
                ExpireYear = "15"
            };

            //// Act
            var result = creditCardMethod.AuthorizePayment(_invoice, ccEntry.AsProcessorArgumentCollection());

            //// Assert
            Assert.NotNull(result);
            Assert.IsTrue(result.Payment.Success);
            var payment = result.Payment.Result;
        }
Beispiel #6
0
        public void Can_Authorize_And_Then_Later_Capture_A_Payment()
        {
            var creditCardMethod = Provider.GetPaymentGatewayMethodByPaymentCode("CreditCard");
            Assert.NotNull(creditCardMethod);

            var ccEntry = new CreditCardFormData()
            {
                CreditCardType = "VISA",
                CardholderName = "Alex Lindgren",
                CardNumber = "4012888888881881",
                CardCode = "111",
                ExpireMonth = "09",
                ExpireYear = "15"
            };

            var authorizes = creditCardMethod.AuthorizePayment(_invoice, ccEntry.AsProcessorArgumentCollection());
            Assert.IsTrue(authorizes.Payment.Success, "authorize call failed");
            Assert.AreNotEqual(Core.Constants.DefaultKeys.InvoiceStatus.Paid, _invoice.InvoiceStatusKey, "invoice is marked as paid and is only authorized");

            //// Act
            var authorizedPayment = authorizes.Payment.Result;

            var result = creditCardMethod.CapturePayment(_invoice, authorizedPayment, _invoice.Total, new ProcessorArgumentCollection());


            //// Assert
            Assert.NotNull(result);
            Assert.IsTrue(result.Payment.Success);
            var payment = result.Payment.Result;

            Assert.IsFalse(_invoice.IsDirty());
            Assert.AreEqual(Core.Constants.DefaultKeys.InvoiceStatus.Paid, _invoice.InvoiceStatusKey);
        }
Beispiel #7
0
        public void Can_AuthorizeAndCapture_A_Payment()
        {
            //// Arrange
            var creditCardMethod = Provider.GetPaymentGatewayMethodByPaymentCode("CreditCard");
            Assert.NotNull(creditCardMethod);

            var ccEntry = new CreditCardFormData()
            {
                CreditCardType = "VISA",
                CardholderName = "Alex Lindgren",
                CardNumber = "4012888888881881",
                CardCode = "111",
                ExpireMonth = "09",
                ExpireYear = "15"
            };

            //// Act
            var result = creditCardMethod.AuthorizeCapturePayment(_invoice, _invoice.Total, ccEntry.AsProcessorArgumentCollection());

            //// Assert
            Assert.NotNull(result);
            Assert.IsTrue(result.Payment.Success);
            var payment = result.Payment.Result;

            Assert.IsFalse(_invoice.IsDirty());
            Assert.AreEqual(Core.Constants.DefaultKeys.InvoiceStatus.Paid, _invoice.InvoiceStatusKey);
        }
        public static NameValueCollection PreparePostDataForProcessPayment(IAddress billingAddress,
            TransactionMode transactionMode,
            string amount, string currency, CreditCardFormData creditCard, string invoiceNumber, string description)
        {
            var requestParams = new NameValueCollection();
            requestParams.Add("amount", amount);
            requestParams.Add("currency", currency);
            if (transactionMode == TransactionMode.Authorize)
                requestParams.Add("capture", "false");

            if (!String.IsNullOrEmpty(creditCard.StripeCustomerId))
            {
                requestParams.Add("customer", creditCard.StripeCustomerId);
                if (!String.IsNullOrEmpty(creditCard.StripeCardId))
                    requestParams.Add("card", creditCard.StripeCardId);
            }
            else
            {
                if (!String.IsNullOrEmpty(creditCard.StripeCardToken))
                {
                    requestParams.Add("card", creditCard.StripeCardToken);
                }
                else
                {
                    requestParams.Add("card[number]", creditCard.CardNumber);
                    requestParams.Add("card[exp_month]", creditCard.ExpireMonth);
                    requestParams.Add("card[exp_year]", creditCard.ExpireYear);
                    requestParams.Add("card[cvc]", creditCard.CardCode);
                    requestParams.Add("card[name]", creditCard.CardholderName);

                    //requestParams.Add("receipt_email", address.Email); // note: this will send receipt email - maybe there should be a setting controlling if this is passed or not. Email could also be added to metadata
                    requestParams.Add("card[address_line1]", billingAddress.Address1);
                    requestParams.Add("card[address_line2]", billingAddress.Address2);
                    requestParams.Add("card[address_city]", billingAddress.Locality);
                    if (!string.IsNullOrEmpty(billingAddress.Region))
                        requestParams.Add("card[address_state]", billingAddress.Region);
                    requestParams.Add("card[address_zip]", billingAddress.PostalCode);
                    if (!string.IsNullOrEmpty(billingAddress.CountryCode))
                        requestParams.Add("card[address_country]", billingAddress.CountryCode);
                }
            }

            requestParams.Add("metadata[invoice_number]", invoiceNumber);
            requestParams.Add("description", description);

            string postData =
                requestParams.AllKeys.Aggregate("",
                    (current, key) => current + (key + "=" + HttpUtility.UrlEncode(requestParams[key]) + "&"))
                    .TrimEnd('&');
            return requestParams;
        }
Beispiel #9
0
        public void Can_AuthFail_A_Payment()
        {
            //// Arrange
            var creditCardMethod = Provider.GetPaymentGatewayMethodByPaymentCode("CreditCard");
            Assert.NotNull(creditCardMethod);

            var ccEntry = new CreditCardFormData()
            {
                CreditCardType = "VISA",
                CardholderName = "Alex Lindgren",
                CardNumber = "1234123412341234",
                CardCode = "111",
                ExpireMonth = "09",
                ExpireYear = "15"
            };

            //// Act
            var result = creditCardMethod.AuthorizePayment(_invoice, ccEntry.AsProcessorArgumentCollection());

            //// Assert
            Assert.NotNull(result);
            Assert.IsFalse(result.Payment.Success);
            Assert.IsTrue(result.Payment.Exception.Message == "Your card number is incorrect.");
            
        }