将 Stripe 支付与 React 集成
我最近实现了一个在线支付系统的前端,出乎意料的是,它并没有我想象的那么复杂。我承认大部分工作都是由 Stripe 完成的。
前端
那么,让我们创建一个 React 应用程序并安装必要的依赖项。
// in a terminal
npx create-react-app react-stripe
cd react-stripe
yarn add @stripe/stripe-js @stripe/react-stripe-js axios
接下来,我们需要创建一个Stripe 帐户来获取可发布密钥,我们将使用该密钥将 Stripe 集成到我们的项目中。
注意:Stripe 有两种模式:用于开发的测试模式和用于生产的正式版上线模式。每种模式都有各自的密钥和可发布密钥。密钥用于后端代码,应始终保持私密。可发布密钥用于前端代码,其安全性不如密钥。
现在,要配置 Stripe,我们需要loadStripe
from @stripe/stripe-js
、Elements
from@stripe/react-stripe-js
和 a PaymentForm
。
// App.js
import { loadStripe } from "@stripe/stripe-js";
import { Elements } from "@stripe/react-stripe-js";
import PaymentForm from "./PaymentForm"; // not implemented yet
// when you toggle to live mode, you should add the live publishale key.
const stripePromise = loadStripe(STRIPE_PK_TEST);
function App() {
return (
<div className="App">
{/* Elements is the provider that lets us access the Stripe object.
It takes the promise that is returned from loadStripe*/}
<Elements stripe={stripePromise}>
<PaymentForm />
</Elements>
</div>
);
}
export default App;
其最简单的形式PaymentForm
可以是这样的:
// PaymentForm.js
import { CardElement } from "@stripe/react-stripe-js";
import axios from "axios";
const PaymentForm = () => {
const handleSubmit = async (e) => {
e.preventDefault();
// stripe code here
};
return (
<form onSubmit={handleSubmit}>
<CardElement />
<button>BUY</button>
</form>
);
};
export default PaymentForm;
现在,我们需要使用 Stripe 来提交表单。
//PaymentForm.js
import { CardElement, useStripe, useElements } from "@stripe/react-stripe-js";
import axios from "axios";
const PaymentForm = () => {
const stripe = useStripe();
const elements = useElements();
const handleSubmit = async (e) => {
e.preventDefault();
if (!stripe || !elements) {
// Stripe.js has not loaded yet. Make sure to disable
// form submission until Stripe.js has loaded.
return;
}
// Get a reference to a mounted CardElement. Elements knows how
// to find your CardElement because there can only ever be one of
// each type of element.
const cardElement = elements.getElement(CardElement);
// use stripe.createToken to get a unique token for the card
const { error, token } = await stripe.createToken(cardElement);
if (!error) {
// Backend is not implemented yet, but once there isn’t any errors,
// you can pass the token and payment data to the backend to complete
// the charge
axios
.post("http://localhost:5000/api/stripe/charge", {
token: token.id,
currency: "EGP",
price: 1000, // or 10 pounds (10*100). Stripe charges with the smallest price unit allowed
})
.then((resp) => {
alert("Your payment was successful");
})
.catch((err) => {
console.log(err);
});
} else {
console.log(error);
}
};
return (
<form onSubmit={handleSubmit}>
<CardElement />
<button>PAY</button>
</form>
);
};
export default PaymentForm;
注意:我<CardElement/>
在这里使用了,但您可以使用<CardNumberElement/>
,,<CardExpiryElement/>
和<CardCvcElement/>
,然后使用elements.getElement(CardNumberElement)
来访问卡号元素。
后端
对于后端,Stripe 支持多种语言,但在这里我使用的是 Node.js。
将 React 代码移动到.Runclient
内部的目录中,以便外部目录可以拥有后端代码,然后创建.stripe-react
yarn init
package.json
server.js
项目目录看起来应该是这样的:
- 反应条纹
- 客户端(保存所有 React 文件)。
- .gitignore
- 包.json
- 服务器.js
- yarn.lock
安装后端必要的依赖项:
yarn add express stripe dotenv cors
yarn add --dev concurrently nodmon
添加到外部package.json
:
"scripts": {
"client": "cd client && yarn start",
"server": "nodemon server.js",
"start": "node server.js",
"dev": "concurrently --kill-others-on-fail \"yarn server\" \"yarn client\""
},
现在,在中server.js
创建将从 FE 接收付款数据和 Stripe 令牌以完成收费的 post api/route。
require("dotenv").config();
const express = require("express");
const app = express();
const cors = require("cors");
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cors());
const PORT = process.env.PORT || 5000;
const stripe = require("stripe")(env.process.STRIPE_SECRET_KEY_TEST);
// same api we used in the frondend
app.post("/api/stripe/charge", async (req, resp) => {
const { token, currency, price } = req.body;
const charge = await stripe.charges.create({
amount: price,
currency,
source: token,
});
if (!charge) throw new Error("charge unsuccessful");
});
app.listen(PORT, () => {
console.log(`Server running on port: ${PORT}`);
});
最后,运行yarn dev
并使用其中一张测试卡来测试集成。
您应该会在 Stripe 控制面板的“付款”下看到所有付款。