如何开始使用条纹
你好👋,
在本指南中,我们将学习如何使用Stripe在我们的 Web 应用程序中集成支付网关。
我们用的React
是前端,Node
&Express
是后端。为了进行 API 调用,我们使用了axios
库。
为了简单起见,我们不会关注设计。
首先我们使用create-react-app
。
1.在我们的项目启动后create-react-app
,我们需要在 React 代码中添加两个依赖项。
npm install --save @stripe/react-stripe-js @stripe/stripe-js
2.现在在App.js
文件中,调用loadStripe
函数来传递您可以从条纹仪表板获取的条纹测试可发布密钥
。 (共享条纹可发布密钥是安全的,它们不是秘密)。
import { loadStripe } from "@stripe/stripe-js";
const stripePromise = loadStripe(STRIPE_PUBLISHABLE_KEY);
// Make sure to call `loadStripe` outside of a component’s render
// to avoid recreating the `Stripe` object on every render.
3.接下来,我们将从promise
loadStripe 函数返回的内容传递给Elements
提供程序,这是一个包装器,允许我们在任何嵌套组件中访问 Stripe 对象。
import { Elements } from "@stripe/react-stripe-js";
import { loadStripe } from "@stripe/stripe-js";
const stripePromise = loadStripe(STRIPE_PUBLISHABLE_KEY);
function App() {
return (
<Elements stripe={stripePromise}>
<CheckoutPage />
</Elements>
);
};
// Render an Elements provider at the root of your React app
// so that it is available everywhere you need it.
export default App;
4.在CheckoutPage
组件中,我们将添加CardElement
一个灵活的单行输入,用于收集所有必要的卡详细信息。
import { CardElement } from "@stripe/react-stripe-js";
function CheckoutPage() {
function paymentHandler() {
// We're going to make the function async in the next step
// handling the payment
}
return (
<div>
<Form onSubmit={paymentHandler}>
<CardElement />
<button>Pay Now</button>
</Form>
</div>
);
};
export default CheckoutPage;
5.现在我们要使用这两个强大的钩子:useStripe
和useElements
。
useElements用于将 Payment Element 收集的付款信息安全地传递给 Stripe API。useStripe
hook返回传递给 Elements 提供程序的 Stripe 实例的引用(我们将使用它来确认付款)。
import { CardElement, useElements, useStripe }
from "@stripe/react-stripe-js";
function CheckoutPage() {
const stripe = useStripe();
const elements = useElements();
async function paymentHandler() {
if (!stripe || !elements) {
// Stripe.js has not yet loaded.
// Make sure to disable form submission until Stripe.js has
// loaded.
return;
}
// hadling the payment
}
return (
<div>
<Form onSubmit={paymentHandler}>
<CardElement />
<button disabled={!stripe || !elements}>Pay Now</button>
</Form>
</div>
);
};
export default CheckoutPage;
现在要使用条纹完成付款,我们需要一个clientSecret
对于每笔付款都是唯一的。
为此,我们必须paymentIntent
通过提供金额和货币来创建一个。
该代码将位于后端,因此让我们转到我们的 Node.js 代码。
6.stripe
首先,我们在后端进行安装。
npm install stripe
7.在这一步,我们需要从仪表板获取条纹测试密钥。
▶️(请记住:您必须对您的秘密 API 密钥保密。不要将其放在任何版本控制平台上)
import express from "express";
import Stripe from "stripe";
const stripeSecret = new Stripe(STRIPE_SECRET_KEY);
///////////// Getting client secret /////////////
app.post(
"/api/payment/create", async (request, response) => {
const total = request.query.total;
const paymentIntent = await
stripeSecret.paymentIntents.create({
amount: total,
currency: "inr",
});
response.status(201).send({
clientSecret: paymentIntent.client_secret
});
}
);
😃哇!
如果你已经走到这里,那你已经走完了一大半的路程。只剩几步了🔥
因此,我们编写了函数来获取clientSecret
后端。
现在回到前端。
在组件中,我们需要在页面加载时立即CheckoutPage
向服务器发出请求来创建新的组件。paymentIntent
import React, { useEffect } from "react";
const [clientSecret, setClientSecret] = useState("");
const [errorMsg, setErrorMsg] = useState("");
useEffect(() => {
async function getClientSecret(total) {
try {
const { data } = await axios.post(
`/api/payment/create?total=${total * 100}`
);
// All API requests expect amounts to be provided
// in a currency’s smallest unit.
setClientSecret(data.clientSecret);
} catch (error) {
setErrorMsg(error.message);
}
}
getClientSecret(the_amount);
}, [the_amount]);
我们现在已经收到了我们的clientSecret
。
现在还有最后一步,完成付款处理程序功能并进行一些错误处理。
在CheckoutPage
组件中,我们将通过调用来检查付款是否完成stripe.confirmPayment()
。
import React, { useEffect, useState } from "react";
function CheckoutPage({ amount }) {
const [clientSecret, setClientSecret] = useState("");
const [errorMsg, setErrorMsg] = useState("");
const [processing, setProcessing] = useState(false);
const [success, setSuccess] = useState(false);
useEffect(() => {
.
.
.
getClientSecret(the_amount);
}, [the_amount]);
async function paymentHandler(e) {
e.preventDefault();
if (!stripe || !elements || errorMsg) {
return;
} else {
setProcessing(true);
await stripe.confirmCardPayment(clientSecret, {
payment_method: {
card: elements.getElement(CardElement),
},
})
.then(({ paymentIntent }) => {
setErrorMsg(false);
setProcessing(false);
setSuccess(true);
})
.catch((error) => {
setErrorMsg(error.message);
setProcessing(false);
setSuccess(false);
});
}
}
return (
<div>
<Form onSubmit={paymentHandler}>
<CardElement />
{errorMsg && <div className="errorMsg">{errorMsg}</div>}
<button disabled={
!stripe || !elements || processing || success
}>
Pay Now
</button>
</Form>
</div>
);
};
export default CheckoutPage;
我们已成功使用条纹将支付网关集成到我们的网络应用程序中。
注意:您需要将test publishable key
和更改test secret key
为live publishable and secret key
才能在生产环境中使用它。