陈潇冰 react权威指南_React中条带化付款的分步指南

陈潇冰 react权威指南

This is an adapted from several excerpts from Scott Hasbrouck's book, "The Node.js Engineer's Guide to Stripe" - Available Now! with a 10% discount for David Walsh readers with code: WALSH10

这是从Scott Hasbrouck的书“ The Node.js Stripe Engineer's Guide to Stripe”的摘录中摘录的- 现在可以使用! 使用代码WALSH10的 David Walsh读者 可获得 10%的折扣

我们将涵盖的内容 (What We’ll Cover)

  • Replace Checkout.js with Stripe.js

    用Stripe.js替换Checkout.js
  • Removing the Checkout.js button

    删除Checkout.js按钮
  • Adding required Stripe fields

    添加必需的条带字段
  • Integration the form action with Stripe.js

    将表单动作与Stripe.js集成

When you first build a Stripe integration, the advantage of Checkout.js over Stripe.js is its ease of integration and speed to a working app. However, it does not allow adding any additional input fields. In many situations, you'll want to collect other values such as Quantity, a drop down of products, shipping address, etc, and submit it with the same form that collects payment details. Or perhaps, you really just want a uniform style with the rest of your app that doesn't require a modal dialog to popup. Stripe’s smaller frontend library, called Stripe.js, does not include any UI elements but has all of the client side API functionality of generating payment tokens. Customizing the payment form will require no changes to the backend functionality of your Node.js app, because the front end will still be generating the same payment token.

首次构建Stripe集成时,Checkout.js优于Stripe.js的优点是易于集成,并且可以加快运行中的应用程序的运行速度。 但是,它不允许添加任何其他输入字段。 在许多情况下,您需要收集其他值,例如数量,产品下拉列表,送货地址等,然后以收集付款明细的相同表格提交。 或者,也许您真的只想要与应用程序其余部分保持一致的样式,而无需弹出模态对话框。 Stripe的较小的前端库称为Stripe.js,它不包含任何UI元素,但具有生成支付令牌的所有客户端API功能。 自定义付款表格将不需要更改Node.js应用程序的后端功能,因为前端仍将生成相同的付款令牌。

Checkout.js功能的简要概述 (Brief Overview of Checkout.js Functionality)

If you've never integrated Stripe before, or it's been a while since you've done it, let's review just what the purpose is of the front end portion of Stripe! Stripe is an API as a Service, so your first question may be, "Why on earth does an API require the use of a front-end JavaScript library?" Great question! As you can imagine, handling your users' credit card information online is a potentially risky business - which is exactly why there is a security standard that you must adhere to in order to accept payments online. The Payment Card Industry Digital Security Standards (or PCI DSS, commonly just referred to as PCI for short), explicitly prohibits direct storing of credit card numbers by merchants - unless you are up to the task of "protecting stored cardholder data." Stripe's ingenuity was to build a simple front end mechanism that collects the cardholder payment data on your behalf so that it never even touches your server - making PCI-DSS compliance much easier. This is covered in more detail in my book, The Node.js Engineer's Guide to Stripe.

如果您以前从未集成过Stripe,或者自从完成以来已经有一段时间了,我们就来回顾一下Stripe前端部分的用途是什么! Stripe是一种API即服务,因此您的第一个问题可能是:“为什么API要求使用前端JavaScript库?” 好问题! 您可以想象,在线处理用户的信用卡信息是一项潜在的风险业务,这正是为什么要接受在线接受付款必须遵循安全标准的原因。 支付卡行业数字安全标准(或PCI DSS,通常简称为PCI)明确禁止商家直接存储信用卡号-除非您要“保护存储的持卡人数据”。 Stripe的独创性是建立了一个简单的前端机制,该机制可以代表您收集持卡人的付款数据,以便它甚至不会触及您的服务器, 从而使PCI-DSS的合规性更加容易 。 我的书《 Node.js条纹工程师指南》中对此进行了更详细的介绍。

Checkout.js bundles the cardholder data collection mechanism with a beautiful and easy to integrate modal popup form that collects that payment details from the user. This is a fantastic option for putting together a very quick Stripe integration, but will not seamlessly flow with the rest of your user interface. This is where Stripe.js come into play. The API still offers JavaScript methods for sending the payment details directly to Stripe, and receiving a payment token to represent the payment.

Checkout.js将持卡人数据收集机制与美观且易于集成的模式弹出式表格捆绑在一起,该表格可从用户那里收集付款细节。 这是将非常快速的Stripe集成在一起的绝佳选择,但不会与用户界面的其余部分无缝连接。 这就是Stripe.js发挥作用的地方。 该API仍提供JavaScript方法,用于将付款明细直接发送到Stripe,并接收代表付款的付款令牌。

安装Stripe.js (Installing Stripe.js)

The Stripe documentation lists provides a Script tag that loads Stripe.js with the latest version. It may be tempting to install the Script with Bower by running bower install --save stripe.js=https://js.stripe.com/v2/, but keep in mind doing this is not officially endorsed by Stripe. There is no mention as to how often they update the client side libraries, so something may break on you unexpectedly. So your first option is to simply load the library by placing the Stripe provided script tag in the HTML file that your React app is mounted in:

Stripe文档列表提供了一个Script标记,用于以最新版本加载Stripe.js。 通过运行bower install --save stripe.js=https://js.stripe.com/v2/来使用Bower安装脚本可能很诱人,但请记住,这样做并不是Stripe正式认可的。 没有提到它们多久更新一次客户端库,因此可能会意外中断您的操作。 因此,您的第一个选择是通过将Stripe提供的脚本标签放置在安装了React应用程序HTML文件中来简单地加载库:

<html>
    <head>
               <script type="text/javascript" src="https://js.stripe.com/v2/"></script>
    </head>
    <body style="margin: 0px;">
        <div id="main"></div>
        <script src="react-bundle.js"></script>
    </body>
<html>


A much better option would be to dynamically load this script with ReactScriptLoader! Considering a React app is a Single Page App, there are likely huge chunks of your app that do not have a payment form. Why load Stripe.js for the entire page when we can simply load it for just the payment form component? Let's make an empty React component for our payment form and dynamically load Stripe.js (note, this method would work just as well for Checkout.js!):

一个更好的选择是动态加载这个脚本ReactScriptLoader! 考虑到React应用程序是单页应用程序,您的应用程序中可能有很大一部分没有付款表格。 当我们只需为付款表单组件简单地加载它时,为什么还要为整个页面加载Stripe.js? 让我们为付款表单制作一个空的React组件,并动态加载Stripe.js(注意,此方法对Checkout.js同样适用!):

var React = require('react');
var ReactScriptLoaderMixin = require('react-script-loader').ReactScriptLoaderMixin;

var PaymentForm = React.createClass({
  mixins: [ ReactScriptLoaderMixin ],

  getInitialState: function() {
    return {
      stripeLoading: true,
      stripeLoadingError: false
    };
  },

  getScriptURL: function() {
    return 'https://js.stripe.com/v2/';
  },

  onScriptLoaded: function() {
    if (!PaymentForm.getStripeToken) {

      // Put your publishable key here
      Stripe.setPublishableKey('pk_test_xxxx');
      this.setState({ stripeLoading: false, stripeLoadingError: false });
    }
  },

  onScriptError: function() {
    this.setState({ stripeLoading: false, stripeLoadingError: true });
  },

  render: function() {
    if (this.state.stripeLoading) {
      return <div>Loading</div>;
    }
    else if (this.state.stripeLoadingError) {
      return <div>Error</div>;
    }
    else {
      return <div>Loaded!</div>;
    }
  }
});

module.exports = PaymentForm;


The ReactScriptLoaderMixin begins loading the remote script, and upon successfully loading it, or reaching an error, will invoke one of two event listeners. Once the script is successfully loaded, we can set the public key for Stripe.js. This in turn, gives us a conditional in the render function for three states of loading, errored, or loaded! Note that this method can also be used to load Checkout.js.

ReactScriptLoaderMixin开始加载远程脚本,并在成功加载它或遇到错误后,将调用两个事件侦听器之一。 成功加载脚本后,我们可以为Stripe.js设置公钥。 反过来,这为我们在渲染函数中提供了一个条件,用于加载,错误或加载的三种状态! 请注意,此方法也可以用于加载Checkout.js。

建立表格 (Building the Form)

Now we have a React component with Stripe.js loaded, let's start building the custom payment form. At minimum, we need to collect four values for Stripe to generate a payment token for us: credit card number, expiration month, expiration year, and the cvc.

现在我们已经加载了一个Stripe.js的React组件,让我们开始构建自定义付款表单。 至少,我们需要为Stripe收集四个值以为我们生成一个支付令牌:信用卡号,到期月份,到期年份和cvc。

var React = require('react');
var ReactScriptLoaderMixin = require('react-script-loader').ReactScriptLoaderMixin;

var PaymentForm = React.createClass({
  mixins: [ ReactScriptLoaderMixin ],

  getInitialState: function() {
    return {
      stripeLoading: true,
      stripeLoadingError: false,
      submitDisabled: false,
      paymentError: null,
      paymentComplete: false,
      token: null
    };
  },

  getScriptURL: function() {
    return 'https://js.stripe.com/v2/';
  },

  onScriptLoaded: function() {
    if (!PaymentForm.getStripeToken) {
      // Put your publishable key here
      Stripe.setPublishableKey('pk_test_xxxx');

      this.setState({ stripeLoading: false, stripeLoadingError: false });
    }
  },

  onScriptError: function() {
    this.setState({ stripeLoading: false, stripeLoadingError: true });
  },

  onSubmit: function(event) {
    var self = this;
    event.preventDefault();
    this.setState({ submitDisabled: true, paymentError: null });
    // send form here
    Stripe.createToken(event.target, function(status, response) {
      if (response.error) {
        self.setState({ paymentError: response.error.message, submitDisabled: false });
      }
      else {
        self.setState({ paymentComplete: true, submitDisabled: false, token: response.id });
        // make request to your server here!
      }
    });
  },

  render: function() {
    if (this.state.stripeLoading) {
      return <div>Loading</div>;
    }
    else if (this.state.stripeLoadingError) {
      return <div>Error</div>;
    }
    else if (this.state.paymentComplete) {
      return <div>Payment Complete!</div>;
    }
    else {
      return (<form onSubmit={this.onSubmit} >
        <span>{ this.state.paymentError }</span><br />
        <input type='text' data-stripe='number' placeholder='credit card number' /><br />
        <input type='text' data-stripe='exp-month' placeholder='expiration month' /><br />
        <input type='text' data-stripe='exp-year' placeholder='expiration year' /><br />
        <input type='text' data-stripe='cvc' placeholder='cvc' /><br />
        <input disabled={this.state.submitDisabled} type='submit' value='Purchase' />
      </form>);
    }
  }
});

module.exports = PaymentForm;


Once Stripe.js is loaded, our payment form component returns a form with the required input fields. We’ve added the required data-stripe attributes per the Stripe documentation. The form onSubmit event invokes a handler on our component which calls Stripe.createToken(). If an error is returned, we display that to our users by setting state.paymentError equal to the error message. Otherwise, we set the payment is complete with this.paymentComplete, and that is also the point where we would pass the token and required purchasing information to our server with a module such as superagent.

加载Stripe.js后,我们的付款表单组件将返回带有必需输入字段的表单。 我们已根据Stripe文档添加了必需的数据条带属性。 形式onSubmit事件会在我们的组件上调用一个处理程序,该处理程序调用Stripe.createToken()。 如果返回错误,我们通过将state.paymentError设置为等于错误消息来向用户显示该错误。 否则,我们将使用this.paymentComplete设置付款完成,这也是我们将令牌和所需的购买信息通过诸如superagent之类的模块传递给服务器的关键点。

摘要 (Summary)

As you can see, nixing Checkout.js for your own custom styled payment form is really not very difficult. By making this a component and loading Stripe.js dynamically, it also keeps the resources that must be loaded by the client to a minimum, and allows you to drop this into any place you need to complete a purchase in your React app. Once you have this boilerplate React component setup for interacting with Stripe.js, you can add other fields related to the product the user is purchasing, or even make collecting credit card information a seamless step of your signup process. Your users will never know that you are relying on Stripe to do this.

如您所见,为您自己的自定义样式的付款表格设置Checkout.js确实不是很困难。 通过使它成为一个组件并动态加载Stripe.js,它还可以使客户端必须加载的资源降至最低,并使您可以将其放到在React应用程序中完成购买所需的任何位置。 一旦有了用于与Stripe.js交互的样板React组件设置,就可以添加与用户购买的产品相关的其他字段,甚至可以使收集信用卡信息成为注册过程的无缝步骤。 您的用户永远不会知道您依靠Stripe来做到这一点。

Checkout.js does add a layer of perceived security by showing the Stripe brand, and recognizing the card type as you enter your credit card number. I would recommend putting some effort into showing visual clues of security for the user when building your own form, also. For example, this would be a great place to show your SSL certificate badge from Comodo or Network Solutions. To further comfort your users, integrating something similar to react-credit-card would be a great finishing touch. This component automatically detects credit card type, and shows the appropriate logo on a CSS generated credit card, along with the credit card number itself.

Checkout.js通过显示Stripe品牌并在您输入信用卡号时识别卡类型,确实增加了可感知的安全性。 我建议在构建自己的表单时也要花一些力气为用户显示安全性的视觉线索。 例如,这是一个显示Comodo或Network Solutions的SSL证书徽章的好地方。 为了进一步让您的用户满意,集成类似于react-credit-card的功能将是一个很好的画龙点睛。 该组件自动检测信用卡类型,并在CSS生成的信用卡上显示适当的徽标以及信用卡号本身。

Thankfully, integrating Stripe on your front end is fairly straightforward - it does not really get much more complicated than this! The real work (and fun!) begins on your server code, which can become complicated and buggy if you are doing more than accepting one-time payments for non-repeat users. Best of luck on your online payment endeavors with JavaScript, and if you want input on your own projects, or have feedback with how you've integrated Stripe with React please reach out or comment! The first five people to leave a comment about their favorite takeaway from this post or React tip and tweet the article will recieve a FREE copy of my book: The Node.js Engineer's Guide to Stripe! Just mention me in the tweet and I will DM you directions on how to claim your copy.

幸运的是,在您的前端上集成Stripe非常简单-并没有比这复杂得多! 真正的工作(很有趣!)始于您的服务器代码,如果您要做的不仅仅是接受非重复用户的一次性付款,这可能会变得很复杂且容易出错。 祝您使用JavaScript进行在线支付时万事如意,如果您想在自己的项目中输入信息,或者对将Stripe与React集成的方式有任何反馈,请联系或发表评论! 前五个对本文或React技巧中最喜欢的内容发表评论并在推特上发表评论的人将获得我的书的免费副本:Node.js Stripe工程师指南! 只需在推文中提及我,我将向您发送有关如何索取您的副本的指示。

翻译自: https://davidwalsh.name/step-step-guide-stripe-payments-react

陈潇冰 react权威指南

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值