在本文中,我们将研究使用 Stripe’s Charges API来创建一个基本的捐赠应用程序,我们可以创建客户并提交付款。
前提条件
了解基本(承诺)(LINK0)和如何设置(Express Server)(LINK1)是必要的。
安装
Body-parser
将允许我们将我们的表单数据转换成更有用的东西,ejs
将允许我们从我们的服务器上渲染我们的成功页面,为服务器本身表达
,nodemon
重新加载我们的服务器在保存时,最后stripe
为我们提供所有我们想要的 Stripe API 更有趣的功能。
1$ npm i body-parser ejs express nodemon stripe
现在,在 Stripe 网站上,您需要创建一个帐户。当在仪表板上,在开发人员
下的API 密钥
中,您将发现一个可发布密钥
和一个秘密密密钥
。
文件和目录设置
以下是我们的简单项目的文件将如何组织:
1* views 📂 - Handles our front-end code, must be named views for `ejs` to work.
2 * card.js
3 * completed.html
4 * index.html
5* server.js
服务器设置
只是一个基本的快递服务器,我们将需要我们安装的所有东西,在需要快递
时添加我们的秘密密密钥
,我们将使用express.static
来渲染我们的视图文件夹。
1[label server.js]
2const express = require('express');
3const bodyParser = require('body-parser');
4const path = require('path');
5const stripe = require('stripe')('SECRET_KEY'); // Add your Secret Key Here
6
7const app = express();
8
9// This will make our form data much more useful
10app.use(bodyParser.urlencoded({ extended: true }));
11
12// This will set express to render our views folder, then to render the files as normal html
13app.set('view engine', 'ejs');
14app.engine('html', require('ejs').renderFile);
15
16app.use(express.static(path.join(__dirname, './views')));
17
18// Future Code Goes Here
19
20const port = process.env.PORT || 3000;
21app.listen(port, () => console.log('Server is running...'));
<$>[警告]在将任何应用程序移动到生产时,永远不要将 API 密钥直接放入代码中. 使用任何您使用的托管服务,请记住 设置环境变量以便安全地传递信息。
UI 设置
对于我们的用户界面和前端,我将使用Tailwind CSS(https://tailwindcss.com/),我们还需要从Stripe获得前端脚本,就在我们自己的前端代码之前。
在我们的表单的底部,我们需要两个空的div
与卡片元素
和卡片错误
的ID,以便Stripe显示其卡片输入和错误消息。
1[label index.html]
2<!DOCTYPE html>
3<html lang="en">
4
5<head>
6 <meta charset="UTF-8">
7 <meta name="viewport" content="width=device-width, initial-scale=1.0">
8 <meta http-equiv="X-UA-Compatible" content="ie=edge">
9 <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet">
10 <title>Donation App</title>
11</head>
12
13<body class="bg-gray-900">
14 <nav class="bg-purple-900 h-20 flex justify-center">
15 <h1 class="text-white text-5xl">Donation App</h1>
16 </nav>
17
18 <div class="flex justify-center mt-32">
19 <form action="/charge" method="POST" class="flex flex-col w-1/3">
20 <input class="bg-transparent text-white p-2 h-10 mb-4" type="text" name="name" placeholder="Name">
21 <input type="email" class="bg-transparent text-white p-2 h-10 mb-4" name="email" placeholder="Email">
22 <input class="bg-transparent text-white p-2 h-10 mb-4" type="text" name="amount" placeholder="Amount">
23
24 <div id="card-element" class="bg-transparent text-white p-2 h-10 mb-4"></div>
25 <div id="card-errors" role="alert"></div>
26 <button class="text-white bg-purple-900 p-4 rounded">Submit Payment</button>
27 </form>
28 </div>
29</body>
30
31<script src="https://js.stripe.com/v3/"></script>
32<script src="card.js"></script>
33
34</html>
前端代码
首先,我们需要设置我们的卡入口和验证。幸运的是,对于我们来说,Stripe也会帮助我们。
- 我们需要使用 Stripe的元素函数创建我们的卡输入,添加一些样式以匹配其他应用程序,并将其添加到我们的
卡元素
ID,以便在我们的前端进行渲染 *创建一个函数,将添加一个看不见的输入到我们的表单中,以我们的论点的值,就在表单提交之前 *添加到我们的表单上提交事件倾听器,以创建一个新的Stripe代币,这将加密我们的用户卡数据,并将其传输到我们的函数,以便在我们的隐藏输入中提交
我们只是创建我们的输入,确保传入的数据,并在将其提交到我们的服务器之前将加密数据添加到我们的表单中。
1[label card.js]
2const stripe = Stripe('PUBLISHABLE_KEY'); // Your Publishable Key
3const elements = stripe.elements();
4
5// Create our card inputs
6var style = {
7 base: {
8 color: "#fff"
9 }
10};
11
12const card = elements.create('card', { style });
13card.mount('#card-element');
14
15const form = document.querySelector('form');
16const errorEl = document.querySelector('#card-errors');
17
18// Give our token to our form
19const stripeTokenHandler = token => {
20 const hiddenInput = document.createElement('input');
21 hiddenInput.setAttribute('type', 'hidden');
22 hiddenInput.setAttribute('name', 'stripeToken');
23 hiddenInput.setAttribute('value', token.id);
24 form.appendChild(hiddenInput);
25
26 form.submit();
27}
28
29// Create token from card data
30form.addEventListener('submit', e => {
31 e.preventDefault();
32
33 stripe.createToken(card).then(res => {
34 if (res.error) errorEl.textContent = res.error.message;
35 else stripeTokenHandler(res.token);
36 })
37})
基本费用
现在,在我们的服务器方面,我们将创建一个新的POST API终端为/charge
。我们只是做出一个承诺,用我们的基本信息创建客户(您可以玩所有的选项 在这里,最重要的是,我们从卡输入中创建的代币。
随着我们的新客户,我们将为他们的卡创建一个新的收费,以美分传递的金额. 如果一切顺利,我们将渲染我们的完成.html
页面。
1app.post("/charge", (req, res) => {
2 try {
3 stripe.customers
4 .create({
5 name: req.body.name,
6 email: req.body.email,
7 source: req.body.stripeToken
8 })
9 .then(customer =>
10 stripe.charges.create({
11 amount: req.body.amount * 100,
12 currency: "usd",
13 customer: customer.id
14 })
15 )
16 .then(() => res.render("completed.html"))
17 .catch(err => console.log(err));
18 } catch (err) {
19 res.send(err);
20 }
21});
完整页面
当我们成功发送捐款时,我们可以将另一个页面带有感谢消息和按钮返回我们的主页:
1<!DOCTYPE html>
2<html lang="en">
3
4<head>
5 <meta charset="UTF-8">
6 <meta name="viewport" content="width=device-width, initial-scale=1.0">
7 <meta http-equiv="X-UA-Compatible" content="ie=edge">
8 <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet">
9 <title>Donation Completed</title>
10</head>
11
12<body class="bg-gray-900">
13 <nav class="bg-purple-900 h-20 flex justify-center">
14 <h1 class="text-white text-5xl">Donation App</h1>
15 </nav>
16 <div class="flex flex-col items-center mt-32 text-white text-2xl">
17 <p>Thank you for your generous donation.</p>
18 <p>Your payment has been received.</p>
19 <a href="/"><button class="bg-blue-700 rounded p-4 mt-3">Return</button></a>
20 </div>
21</body>
22
23</html>
现在在Localhost:3000
上尝试一下,Stripe给了我们一个测试卡号码(https://stripe.com/docs/testing)的列表。
结论
显然,这篇文章只会撕裂表面,并且更复杂的使用案例将需要你挖掘出优秀的 Stripe 文档。一个更强大的支付系统也会处理错误处理和避免重复费用,如果用户意外地试图连续两次处理收费。
希望这个简短的介绍有助于简化您如何使用 Stripe 和 Node.js 在线处理付款的方式。