本文共 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.
在本文中,我们将研究使用创建一个基本的捐赠应用程序,我们可以在其中创建客户并提交付款。
Understanding basic and how to set up an are necessary.
必须了解基本以及如何设置 。
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 key
和Secret Key
。 这些就是我们以后需要访问数据所需要的。 您首先需要使用测试键。
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
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文件夹。
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密钥直接放入代码中。 无论您使用哪种托管服务,请记住来传递安全信息。 您可能希望立即设置环境变量,以使您的秘密密钥不会提交给可能意外暴露其代码的存储库。
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-element
和card-error
的ID,以便Stripe显示其Card输入和错误消息。
Donation App
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中,以便将其呈现在前端。
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.
我们只是创建输入,保护传递到其中的数据,然后将加密的数据添加到表单中,然后再将其提交到服务器。
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); })})
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); }});
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
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为我们提供了列表。 在我们的仪表板上,我们可以查看所有测试付款的详细信息。
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/