如何开始使用条纹

2025-06-07

如何开始使用条纹

你好👋,

在本指南中,我们将学习如何使用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
Enter fullscreen mode Exit fullscreen mode

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.
Enter fullscreen mode Exit fullscreen mode

3.接下来,我们将从promiseloadStripe 函数返回的内容传递给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;
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

CardElement 看起来是这样的:
卡元素

5.现在我们要使用这两个强大的钩子:useStripeuseElements

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;
Enter fullscreen mode Exit fullscreen mode

现在要使用条纹完成付款,我们需要一个clientSecret对于每笔付款都是唯一的。

为此,我们必须paymentIntent通过提供金额和货币来创建一个。

该代码将位于后端,因此让我们转到我们的 Node.js 代码。

6.stripe首先,我们在后端进行安装

npm install stripe
Enter fullscreen mode Exit fullscreen mode

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
    });
  }
);
Enter fullscreen mode Exit fullscreen mode

😃哇!
如果你已经走到这里,那你已经走完了一大半的路程。只剩几步了🔥

已进行到一半

因此,我们编写了函数来获取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]);
Enter fullscreen mode Exit fullscreen mode

我们现在已经收到了我们的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;
Enter fullscreen mode Exit fullscreen mode

我们已成功使用条纹将支付网关集成到我们的网络应用程序中。

注意:您需要将test publishable key和更改test secret keylive publishable and secret key才能在生产环境中使用它。

这是我制作的带有一些样式的演示:

我把它叫做“带条纹的月亮”

终于完成了!

文章来源:https://dev.to/roopalisingh/how-to-start-with-stripe-3pip
PREV
CSS 变量、input[type="color"] 和表单动画
NEXT
我问招聘经理如何回答常见的行为问题