Some time ago, Jason asked me to help integrate Stripe Payment into his personal website, which gave me a chance to get in touch with the development of payment system. Meanwhile, I did not find too many relevant documents in Chinese, so I made a summary for the convenience of students who need it in the future.

About Stripe Payments

I first heard about Stripe a few months ago in a news article that basically said that the president of the United States is using it and that it could be the next Paypal. What are the benefits of such a popular payment platform? I did a cursory search:

  • A code that allows your site to support cumbersome international payments. (Perfect for startups)
  • Expanding globally could be an opportunity for Stripe. Even in different payment currencies and methods, Stripe can open up its own channels to make global transactions unimpeded by payment.
  • With a market capitalization of more than $9 billion, it has partnerships with Tweeter,Lyft, Best Buy, Alipay and WeChat in China

Second point, what does that mean? It means that customers can pay in RMB, which is automatically converted to USD if the merchant is a US bank, or sterling if the bank is a UK bank! (Unfortunately, the merchants are not supported in China (but Stripe does offer a solution, using Atlas to create a U.S. agency).

And for our programmers, of course, the most concerned about the first, because his purpose is to develop minimalist, super friendly to developers! For how friendly, read on.

Simplest payment

<! DOCTYPE html> <html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Stripe Checkout</title>
</head>
<body>
   <form action="/your-server-side-code" method="POST">
  <script
    src="https://checkout.stripe.com/checkout.js" class="stripe-button"
    data-key="[Publishable key]"
    data-amount="999"
    data-name="troy yang"
    data-description="Widget"
    data-image="https://stripe.com/img/documentation/checkout/marketplace.png"
    data-locale="auto"
    data-zip-code="true"
    data-currency="eur">
  </script>
</form>
</body>
</html>
Copy the code

With just a few lines of code, we’ve implemented everything on the client side:

It’s super simple, but it’s based on a credit card interface that already covers half of all payment methods. For other three-party payments, like 3D Secure, Alipay, wechat, and even Bitcoin, Stripe offers other options, which I’ll use Alipay as an example in a moment.

Register a Stripe Account

It is the same as registering an Alipay account. First register an account and then bind your bank card. BUT, as mentioned above, it does not support China, so even if you register successfully, you cannot activate it and you cannot receive payment.

I can think of only a few ways to deal with Chinese businesses:

  • Oneself go supporting a country to deal with a piece of bank card
  • Use a foreign friend’s bank card
  • The use of the Atlas

For Jason, because he’s British, he can create his main account and then add my Stripe account to his list of Team Memeber accounts so THAT I have access to all the privileges that developers need under his account. After the invitation is successful, the Dashboard page is displayed

Two phases

Stripe has two modes: Test Mode and Live Mode. Money transactions generated in the Test Mode are only used for tests. When all tests pass, the Stripe switches to Live Mode. The only difference is the Publishable key and Secret key, which we will use in a moment.

Transaction process

Stripe has several concepts for the entire transaction phase and state:

Create the Source

Use your Publishable key to create a source (such as Cards, 3D Secure, Alipay, or even Bitcoin, etc.). When the source is created, You will get a Token for transaction or a redirect to another supported third-party payment platform (such as Alipay payment) page waiting for the user to pay. When the user completes the payment (or cancels the payment), it automatically redirects to the specified result page. After the user finishes the payment page, they may get three states:

  • Source. Chargeable user authorization (payment) has been successful
  • Source. failed User refuses authorization (payment)
  • Canceled

Create a Charge

When the payment is successful, the payment status at the Stripe end will be changed to source. Shipped, which means the authorization is successful. You can deduct the money on our Alipay platform. The official recommendation is to use Webhooks to capture state and complete the creation of Charge. When Charge completes, the entire payment is complete and a state of Charge. Succeeded is obtained.

Using webhooks

Webhooks provide dozens of states, all of which are registered in Stripe in a place called Webhooks. We can specify which events are triggered to forward data to a Web Api that we have built ourselves. (The picture below is our server End Point, because we don’t use a server, we use Amazon Lambda to make a Serverless)

Take alipay for example

Serverless

Take AWS’s Lambda + API Gateway for example, where the former is used to define apis and the latter is used to do routing.

Create Charge code:

'use strict';

const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
exports.handler = (event, context, callback) => {
    console.log("request: " + JSON.stringify(event));

    let stripeData = event.data.object;
    stripe.charges.create({
        amount: stripeData.amount,
        source: stripeData.id,
        currency: stripeData.currency || 'usd',
        description: 'My Englishtutor 30 days'| | -'Stripe payment ' + event.id),
    }, function(err, charge) {
        if (err && err.type === 'card_error') {
            context.fail(new Error(err.message));
        }
        else if (err) {
            context.fail(err);
        }
        else {
            context.succeed({ status: charge.status, success: true}); }}); };Copy the code

The client (Web)

Multiple implementations:

Checkout

At the beginning of the article

When developing Alipay, I found that I could directly use Checkout:

<form action="https://xxx.execute-api.eu-central-1.amazonaws.com/stripepayment/xxx" method="POST">
  <script
    src="https://checkout.stripe.com/checkout.js" class="stripe-button"
    data-key="pk_test_xxx"
    data-amount="30000"
    data-name="myenglishtutor.eu"
    data-label="Pay With Alipay"
    data-description="30 days"
    data-image="/images/logo.png"
    data-locale="auto"
    data-alipay="auto"
    data-currency="usd">
  </script>
</form>
Copy the code

But I always get this error:

Unrecognized request URL (POST: /v1/alipay/send_sms). Please see https://stripe.com/docs or we can help at https://support.stripe.com/.
Copy the code

For future expansion, Stripe no longer provides Alipay checkout, so we have no choice but to use the following method.

Stripe.js & Elements

Of course, if you feel that the Checkout approach is too integrated and inflexible, then strie.js is your best bet.

Strie. js is a core js library for the client, Elements is its UI library, and the above Checkout code is wrapped by Stripe to prevent us from directly accessing sensitive information, but it is essentially the same. Here’s the code for the client side:

var stripe = Stripe('pk_live_xxxx');

function alipay(amount) {
    showLoading();
    stripe.createSource({
        type: 'alipay',
        amount: parseInt(amount),
        currency: 'gbp', // usd, eur,
        redirect: {
            return_url: 'https://xxx.eu/pay/result.html'
        },
    }).then(function (response) {
        hideLoading();
        if (response.error) {
            alert(response.error.message);
        }
        else{ processStripeResponse(response.source); }}); }function processStripeResponse(source) {
    window.location.href = source.redirect.url;
}
Copy the code

A few things to note here:

  • Currency must be the currency where the Stripe account is located, which is where the bound bank card is located. Jason is British, so he must use GBP. (I made a common sense mistake here, thinking that the UK is also in the EU, so I used EUR.
  • Return_url refers to the page where the payment is completed after the user redirects to our common Alipay payment page. In this return page, since alipay has completed the payment synchronously, we can check the status of charge. Succeeded to determine whether the user has completed the payment.

When everything is OK, click the “pay” button, it will jump to the Alipay payment page (other supported third-party platforms are also available), as follows:

Originally adapted from troyyang.com/2018/01/21/…