首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >React (前端)+ Express (后端)+ Stripe集成

React (前端)+ Express (后端)+ Stripe集成
EN

Stack Overflow用户
提问于 2022-09-24 15:16:09
回答 2查看 72关注 0票数 0

我正在尝试实现我的网页应用程序的条纹。我已经集成了条形结帐,它可以工作,但是我需要处理一些前面的逻辑。我已经用上一个版本的Stripe做了,但现在似乎已经被废弃了。

基本上,我需要的是,如果支付成功,做一些其他的事情不要做它。(我知道如何实现这个逻辑)

我不知道的是如何在成功支付后从后端发送回复到前端。

我读过关于网络套接字之类的东西,但我并不太熟悉,而且时间也很有限。如果可能的话,我宁愿避开他们。

这是我为不推荐的版本所做的,但是现在我不能用最新的条签出版本来完成它。

如果还不清楚,我很抱歉。

谢谢

代码语言:javascript
运行
复制
async function handleToken(token, addresses) {
    const response = await axios.post(
        "https://btycwse.codesandbox.io/checkout",
      { token, product }
    );
    const { status } = response.data;
    
    console.log("Response:", response.data);
    if (status === "success") {
      console.log("Success! Check email for details");
      handleSubmit();
    } else {
      console.log("Something went wrong");
    }
  }

后端(express.js)

代码语言:javascript
运行
复制
// This is your test secret API key.
const stripe = require('stripe')('sk_test');
const express = require('express');
const app = express();

app.use(express.json())

const cors = require("cors")
app.use(
  cors({
    origin: "http://localhost:3000",
    
  })
)

const storeItems = new Map([
  [1, { priceInCents: 10000, name: "JavaScript Tutorial" }],
  [2, { priceInCents: 15000, name: "Ultimate CSS tutorial" }],
])

app.get("/", (req, res) => {
  res.send("Add your Stripe Secret Key to the .require('stripe') statement!");
});

app.post("/checkout", async (req, res) => {
  try {
    // Create a checkout session with Stripe
    const session = await stripe.checkout.sessions.create({
      payment_method_types: ["card"],
      mode: "payment",
      // For each item use the id to get it's details
      // Take that information and convert it to Stripe's format
      line_items: req.body.items.map(({ id, quantity }) => {
        const storeItem = storeItems.get(id)
        return {
            price_data: {
            currency: "usd",
            product_data: {
              name: storeItem.name,
            },
            unit_amount: storeItem.priceInCents,
          },
          quantity: quantity,
        }
      }),
      // Set a success and cancel URL we will send customers to
      // They are complete urls
      success_url: "http://localhost:3000/success.html",
      cancel_url: "http://localhost:3000//cancel.html",
    })

    res.json({ url: session.url })

  } catch (e) {
    // If there is an error send it to the client
    res.status(500).json({ error: e.message })
   
  }
})

const bodyParser = require('body-parser');

app.post('/webhook', bodyParser.raw({type: 'application/json'}), (request, response) => {
  const event = request.body;

  // Handle the event
  switch (event.type) {
    case 'payment_intent.succeeded':
      const paymentIntent = event.data.object;
      // Then define and call a method to handle the successful payment intent.
      // handlePaymentIntentSucceeded(paymentIntent);
      break;
    case 'payment_method.attached':
      const paymentMethod = event.data.object;
      // Then define and call a method to handle the successful attachment of a PaymentMethod.
      // handlePaymentMethodAttached(paymentMethod);
      break;
    // ... handle other event types
    default:
      console.log(`Unhandled event type ${event.type}`);
  }

  // Return a response to acknowledge receipt of the event
  response.json({received: true});
});


app.listen(4242, () => console.log('Running on port 4242'));

前端(ReactJS)

代码语言:javascript
运行
复制
import React from "react";
import "./App.css";


export default function App() {



const handleCheckout = () => {
  fetch("http://localhost:4242/checkout", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    // Send along all the information about the items
    body: JSON.stringify({
      items: [
        {
          id: 1,
          quantity: 5,
        },
        {
          id: 2,
          quantity: 2,
        },
      ],
    }),
  })
   .then(res => {
      if (res.ok) return res.json()
      // If there is an error then make sure we catch that
      return res.json().then(json => Promise.reject
        (json))
    })
    .then(({ url }) => {
    
      // On success redirect the customer to the returned URL
      window.location = url
    })
    .catch(e => {
      console.log(e.error)
      
    })
  }

  return (
    <>
    
     <button type="submit" onClick={handleCheckout}>Checkout</button>
 
    </>

  );
}

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-09-26 01:35:23

我的建议是实现web钩子这里

in php

代码语言:javascript
运行
复制
switch($payload){
  case 'invoice.paid':

  $a = $event->data->object;
    // do stuff e.g. 'talk' to your db, emails
  break;
  default:
       $body['eventDefaulted'] = 'Received unknown event type ' . $event->type;
  break;
 }

add (确保它不超时,条带将在脚本开头抛出一个错误)

代码语言:javascript
运行
复制
// respond to stripe otherwise timeout
// Buffer all upcoming output...

// Send your response.

echo "recieved $event->type";

// // Get the size of the output.

$size = ob_get_length();

// // // Disable compression (in case content length is compressed).

header("Content-Encoding: none");

// // Set the content length of the response.

header("Content-Length: {$size}");
header($_SERVER["SERVER_PROTOCOL"] . " 200 OK");
header("HTTP/1.1 200 OK");
http_response_code(200);

// // Close the connection.

header("Connection: close");

// // // Flush all output.

ob_end_flush();
ob_flush();
flush();

请参阅api文档

然后用api与您联系获取发票详细信息。

票数 0
EN

Stack Overflow用户

发布于 2022-09-26 01:15:52

根据您的假设,除非您使用一些WebSocket,否则无法将请求从后端发送到前端。最封闭的办法是:

  1. 实现web钩子来监听Stripe的最新事件(您已经在这么做了)并将它们保存到数据库中。
  2. 在重定向的sucess_url (http://localhost:3000/success.html)中,从前端发送AJAX请求到后端,并在步骤1中从数据库中检索最新数据。
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73838345

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档