Articles in this section
Category / Section

Processing Payment using Stripe and Syncfusion JS MaskEdit Component

6 mins read

Stripe is a quick and secure way to accept credit or debit card payments, over the internet. Integrate Stripe account into your website to accept payments. You can use the EJ components along with Stripe’s APIs in the payment form, to accept the card details for processing payments. 

You can start using Stripe by creating an account in the Stripe website. Create an account and get your API keys. Used here is a test Stripe account and test API keys to deal with the example. To start with you need JQuery Library and Stript.NET dll. You can download the attached project from the bottom and get the dll from the bin folder of Stript.NET dll, or it can be included using NuGet, Stripe.js and Syncfusion EJ Library. You can download EJ Library from here. Alternatively you can also use the CDN links of JQuery and Syncfusion.

Stripe.JS

Stripe.js makes a request to the stripe server in client-side and responds with a token that identifies your credit information. You need to include the following script file in the <head> section.

JavaScript

<script type="text/javascript" src="https://js.stripe.com/v2/"></script>

Set your Publishable key and Secret keys

In the page head, you can include the publishable key as follows:

Stripe.setPublishableKey('Your_Publishable_Key);

In the web.config file under <appsettings>, you need to set the secret key as follows:

<add key="StripeApiKey" value="Your_Secret_Key" />

Create your Payment form

While creating payment form, you can use the Syncfusion EJ components, such as MaskEdit and Button. MaskEdit can be used for specifying the credit card number and CVC number, while EJ Button can be used to submit the payment form. To include the Syncfusion components, you must add the necessary script and theme files in the <head> section. Refer the following code example.

HTML

   <!--latest CDN for theme file-->
    <link href="http://cdn.syncfusion.com/js/web/flat-azure/ej.web.all-latest.min.css" rel="stylesheet" type="text/css" />
    <!--CDN for JQuery script file-->
    <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.3/jquery.easing.min.js" type="text/javascript"></script>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/globalize/0.1.1/globalize.min.js"></script>
    <!--latest cdn for script file-->
    <script src="http://cdn.syncfusion.com/js/web/ej.web.all-latest.min.js"></script>
    <!--latest CDN for Unobtrusive JS file-->
    <script src="http://cdn.syncfusion.com/js/web/ej.unobtrusive-latest.min.js"></script>

Then, create the HTML elements with Stripe APIs, for the purpose of validation. Refer the following code example.

HTML

  <form action="demo.ASP" method="POST" id="payment-form">
    <span class="payment-errors"></span>
     <div class="form-row">
      <label>
        <span>Card Number</span>
        <!--Input element required to convert it as MaskEdit component which accepts the card number-->
        <input id="cardnumber" type="text" size="20" data-stripe="number"/>
      </label>
    </div>
     <div class="form-row">
      <label>
        <span>CVC</span>
        <input id="cvc" type="text" size="4" data-stripe="cvc"/>
      </label>
    </div>
     <div class="form-row">
      <label>
        <span>Expiration (MM/YYYY)</span>
        <input id="expmonth" type="text" size="2" data-stripe="exp-month"/>
      </label>
        <br />
      <input id="expyear" type="text" size="4" data-stripe="exp-year"/>
    </div>
 <br />
    <button id="submit" type="submit">Submit Payment</button>
  </form>

In the <script> section initialize the MaskEdit and Button controls, and write the definition for Stripe Response Handler as follows.

JavaScript

  <script type="text/javascript">
          $("#cardnumber").ejMaskEdit({ mask: "9999-9999-9999-9999" });
          $("#cvc").ejMaskEdit({ mask: "999" });
          $("#submit").ejButton({
              size: "normal",
              roundedCorner: true,
              enabled: true
          });
          // This identifies your website in the createToken call below
          Stripe.setPublishableKey('pk_test_gohVupMQCTMputdP5aOzT4jT');
          var stripeResponseHandler = function (status, response) {
              var $form = $('#payment-form');
              if (response.error) {
                  // Show the errors on the form
                  $form.find('.payment-errors').text(response.error.message);
                  $("#submit").ejButton("option", "enabled", false);
              } else {
                  // token contains id, last4, and card type
                  var token = response.id;
                  // Insert the token into the form so it gets submitted to the server
                  $form.append($('<input type="hidden" name="stripeToken" />').val(token));
                  // and re-submit
                  $form.submit()
              }
          };
          jQuery(function ($) {
              $('#payment-form').submit(function (e) {
                  var $form = $(this);
                  // Disable the submit button to prevent repeated clicks
                  $form.find('button').prop('disabled', true);
                  Stripe.card.createToken($form, stripeResponseHandler);
                  // Prevent the form from submitting with the default action
                  return false;
              });
          });
  </script>

Handle Payment Operations in server-side code

Stripe.Net needs you to identify your account in Stripe by setting your “secret key” that you have already specified in web.config file. Then, you have to write the post action that handles the form postback. Open PaymentController and add a new action. Name it "Buy" with [httpPost] attribute. The full definition of the Buy() action is as follows:

C#

[HttpPost]
        public ActionResult Buy(FormCollection paymentform)
        {
            var customerToken = paymentform["stripeToken"];
            // can create customer here
            var customerOptions = new StripeCustomerCreateOptions
            {
                TokenId = customerToken
            };
            var service = new StripeCustomerService();
            var customer = service.Create(customerOptions);
                        // create a charge for the added customer
            var myCharge = new StripeChargeCreateOptions
            {
                AmountInCents = 1000,
                Currency = "usd",
                CustomerId = customer.Id
            };
            var chargeService = new StripeChargeService();
            var stripeCharge = chargeService.Create(myCharge);
            return RedirectToAction("PaymentComplete", "Payment", new RouteValueDictionary {});
        }

As you can see, you get the “StripeToken” hidden field value to be used in your request. After getting the token, all you need to do is determine the amount to be charged and pass the added Token id to the StripeChargeCreateOptions initializer. Here $10 is specified as the amount to be charged.

var stripeCharge = chargeService.Create(myCharge);

Now, you can be able to see that the payment is received in the Payments page of your Stripe account. In this example, you are redirected to another page that informs you that the payment has been done successfully. You can download the complete sample from the following location.

Sample Location

Using PHP

Stripe payment process can also be handled using PHP. Embedding Syncfusion EJ components in the payment form creation process is the same as MVC. Only the payment handling process differs. You can download the PHP sample from the following location.

Stripe PHP sample



Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please sign in to leave a comment
Access denied
Access denied