博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
使用Express在Node.js中进行条带支付简介
阅读量:2507 次
发布时间:2019-05-11

本文共 8119 字,大约阅读时间需要 27 分钟。

In this article we’ll be looking into using to make a basic donation app where we can create customers and submit payments.

在本文中,我们将研究使用创建一个基本的捐赠应用程序,我们可以在其中创建客户并提交付款。

先决条件 (Prerequisites)

Understanding basic and how to set up an are necessary.

必须了解基本以及如何设置 。

安装 (Installation)

We’re going to need quite a few things to get this set up. Body-parser will allow us to convert our form data into something more useful, ejs will let us render our success page from our server, express for the server itself, nodemon to reload our server on save, and finally stripe to give us access to all the more interesting functionality we want with the Stripe API.

我们将需要很多事情来进行此设置。 Body-parser将使我们能够将表单数据转换为更有用的东西, ejs将使我们能够从服务器呈现成功页面, express服务器本身, nodemon在保存时重新加载服务器,最后进行stripe以使我们能够访问Stripe API所需要的所有更有趣的功能。

$ npm i body-parser ejs express nodemon stripe

Now over on the you’ll need to create an account. When on the Dashboard, the API Keys under Developers, you’ll find both a Publishable key and a Secret Key. Those are what we’ll need to have access the data later. You’ll want to use the test keys at first.

现在,在您需要创建一个帐户。 在控制台上的Developers下的API Keys ,您会同时找到可Publishable keySecret Key 。 这些就是我们以后需要访问数据所需要的。 您首先需要使用测试键。

文件和目录设置 (File and Directory Setup)

Here’s how the files for our simple project will be organized:

这是我们简单项目的文件的组织方式:

* views 📂  - Handles our front-end code, must be named views for `ejs` to work.  * card.js   * completed.html  * index.html* server.js

服务器设置 (Server Setup)

Just a basic Express server, we’ll require everything we installed, add our Stripe Secret Key when requiring stripe, and we’ll use express.static to render our views folder.

只是一个基本的Express服务器,我们需要安装的所有东西,在需要stripe时添加我们的Stripe Secret Key ,并且我们将使用express.static来呈现我们的views文件夹。

server.js
server.js
const express = require('express');const bodyParser = require('body-parser');const path = require('path');const stripe = require('stripe')('SECRET_KEY'); // Add your Secret Key Hereconst app = express();// This will make our form data much more usefulapp.use(bodyParser.urlencoded({ extended: true }));// This will set express to render our views folder, then to render the files as normal htmlapp.set('view engine', 'ejs');app.engine('html', require('ejs').renderFile);app.use(express.static(path.join(__dirname, './views')));// Future Code Goes Hereconst port = process.env.PORT || 3000;app.listen(port, () => console.log('Server is running...'));

When moving any app to production never put your API keys directly into the code. With whatever hosting service your using, remember to for secure information passing instead. You’ll likely want to setup environment variables right away, so that your secret keys don’t get committed to a repo who’s code could be exposed accidentally.

将任何应用程序投入生产时,切勿将您的API密钥直接放入代码中。 无论您使用哪种托管服务,请记住来传递安全信息。 您可能希望立即设置环境变量,以使您的秘密密钥不会提交给可能意外暴露其代码的存储库。

UI设置 (UI Setup)

For our UI and front-end, I’ll be using and we’ll also need to get the front-end script from Stripe just before our own front-end code.

对于我们的UI和前端,我将使用 ,我们还需要在自己的前端代码之前从Stripe获取前端脚本。

At the very bottom of our form we need two empty div’s with the id’s of card-element and card-error for Stripe to display its card inputs and error messages.

在表单的最底部,我们需要两个空的div ,分别具有card-elementcard-error的ID,以便Stripe显示其Card输入和错误消息。

index.html
index.html
  
Donation App

前端代码 (Front-End Code)

First, we need to set up our card inputs and validation. Luckily for us, Stripe will help us with that too. This is going to look a bit complicated so let’s break it down a bit.

首先,我们需要设置卡输入和验证。 对我们来说幸运的是,Stripe也将帮助我们。 这看起来有点复杂,所以让我们分解一下。

  • We need to create our card inputs using , adding some styles to match the rest of the app, and adding it to our card-element id so it’ll be rendered on our front-end.

    我们需要使用创建卡片输入,添加一些样式以匹配应用程序的其余部分,并将其添加到card-element ID中,以便将其呈现在前端。

  • Create a function that will add an invisible input to our form with the value of our argument just before the form is submitted.

    创建一个函数,该函数将在表单提交之前使用参数的值向表单添加不可见的输入。
  • Add an on submit event listener to our form to create a new Stripe token, which will encrypt our user’s card data, and pass it to our function so it’s submitted in our hidden input.

    在我们的表单上添加一个on Submit事件侦听器,以创建一个新的Stripe令牌,该令牌将对用户的卡数据进行加密,并将其传递给我们的函数,以便将其提交到我们的隐藏输入中。

We’re just creating our inputs, securing the data passed into it, and adding that encrypted data to our form before submitting it to our server.

我们只是创建输入,保护传递到其中的数据,然后将加密的数据添加到表单中,然后再将其提交到服务器。

card.js
card.js
const stripe = Stripe('PUBLISHABLE_KEY'); // Your Publishable Keyconst elements = stripe.elements();// Create our card inputsvar style = {  base: {    color: "#fff"  }};const card = elements.create('card', { style });card.mount('#card-element');const form = document.querySelector('form');const errorEl = document.querySelector('#card-errors');// Give our token to our formconst stripeTokenHandler = token => {  const hiddenInput = document.createElement('input');  hiddenInput.setAttribute('type', 'hidden');  hiddenInput.setAttribute('name', 'stripeToken');  hiddenInput.setAttribute('value', token.id);  form.appendChild(hiddenInput);  form.submit();}// Create token from card dataform.addEventListener('submit', e => {  e.preventDefault();  stripe.createToken(card).then(res => {    if (res.error) errorEl.textContent = res.error.message;    else stripeTokenHandler(res.token);  })})

基本费用 (Basic Charges)

Now over on our server side we’re going to create a new POST API endpoint for /charge. We’re just making a promise that creates a customer with our basic information (you can play with all the options ), most importantly, the token we created from the card input.

现在,在服务器端,我们将为/charge创建一个新的POST API端点。 我们只是在作出承诺,以使用我们的基本信息(您可以在使用所有选项)创建客户,最重要的是,我们是根据卡输入创建的令牌。

With our new customer, we’ll create a new charge to their card, passing in the amount in cents. If everything went well, we’ll render our completed.html page.

与新客户一起,我们将为他们的卡创建新的费用,以美分计入。 如果一切顺利,我们将呈现completed.html页面。

app.post("/charge", (req, res) => {  try {    stripe.customers      .create({        name: req.body.name,        email: req.body.email,        source: req.body.stripeToken      })      .then(customer =>        stripe.charges.create({          amount: req.body.amount * 100,          currency: "usd",          customer: customer.id        })      )      .then(() => res.render("completed.html"))      .catch(err => console.log(err));  } catch (err) {    res.send(err);  }});

完成页面 (Completed Page)

When we have successfully sent the donation we can render another page with a thank you message and a button back to our homepage:

成功发送捐赠后,我们可以渲染另一个页面,其中包含感谢消息和返回首页的按钮:

  
Donation Completed

Thank you for your generous donation.

Your payment has been received.

Now on localhost:3000 try it out, Stripe gives us a list of . Over on our Dashboard we can see the details of any test payments.

现在在localhost:3000尝试一下,Stripe为我们提供了列表。 在我们的仪表板上,我们可以查看所有测试付款的详细信息。

结论 (Conclusion)

Obviously this post only scratched the surface and more complex use cases will require that you dig into the excellent . A more robust payment system would also take care of things like error handling and avoiding duplicate charges if a user accidentally tries to process the charge twice in a row. However, as you saw, Stripe makes it really easy to create payment pages without ever having to deal with sensitive data like credits card numbers. They take care of handling the sensitive data for us.

显然,本文仅是从头开始,更复杂的用例将需要您深入研究卓越的 。 如果用户不小心连续尝试两次处理费用,那么功能更强大的支付系统还将处理错误处理和避免重复费用。 但是,正如您所看到的,Stripe使创建支付页面变得非常容易,而无需处理信用卡号等敏感数据。 他们负责为我们处理敏感数据。

Hopefully this short intro was helpful in easing your dive into how processing payments online using Stripe and Node.js works. If you had any problems implementing the code here, feel free to check out .

希望这个简短的介绍有助于您轻松了解使用Stripe和Node.js在线处理付款的方式。 如果您在执行代码时遇到任何问题,请随时查看 。

翻译自:

转载地址:http://sihgb.baihongyu.com/

你可能感兴趣的文章
找了一个api管理工具
查看>>
C++——string类和标准模板库
查看>>
zt C++ list 类学习笔记
查看>>
git常用命令
查看>>
探讨和比较Java和_NET的序列化_Serialization_框架
查看>>
1、jQuery概述
查看>>
数组比较大小的几种方法及math是方法
查看>>
FTP站点建立 普通电脑版&&服务器版
查看>>
js 给一段代码,给出运行后的最终结果的一些综合情况、
查看>>
webservice 详解
查看>>
js自动补全实例
查看>>
VS无法启动调试:“生成下面的模块时,启用了优化或没有调试信息“
查看>>
npm 安装 sass=-=-=
查看>>
WINFORM中加入WPF控件并绑定数据源实现跨线程自动更新
查看>>
C#类对象的事件定义
查看>>
各类程序员学习路线图
查看>>
HDU 5510 Bazinga KMP
查看>>
关于select @@IDENTITY的初识
查看>>
ASP.NET MVC ajax提交 防止CSRF攻击
查看>>
关于CSS伪类选择器
查看>>