【发布时间】:2021-01-17 16:44:39
【问题描述】:
我刚刚观看了一个 youtube,它使用 Stripe API、react 和 node.js 创建了一个支付系统。我不确定 webhook 是什么以及这个 Stirpe api 的目的。这段代码已经检查了错误,但为什么需要 webhook 以及它是如何工作的?我看到了一堆 node.js 条纹 webhook 示例,但仍然无法理解。我是超级初学者
这是我的代码
反应(index.html)
import React, {useState} from 'react';
import logo from './logo.svg';
import './App.css';
import StripeCheckout from "react-stripe-checkout"
function App() {
const [product, setstate] = useState({
name: "React from FB",
price: 10,
productBy:"facebook"
})
const makePayment = token => {
const body = {
token,
product
}
const headers = {
"Content-Type": "application/json"
}
return fetch('http://localhost:8282/payment', {
method: "POST",
headers,
body: JSON.stringify(body)
}).then(response =>{
console.log("RESPONSE", response)
const{status} = response;
console.log("STATUS", status)
})
.catch(error => {
console.log(error);
})
}
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<a
className="App-link"
href="#"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
<StripeCheckout
stripeKey="KEY"
token={makePayment}
name="Buy React"
amount = {product.price * 100}>
<button className="btn-large pink"> buy react is just {product.price}$</button>
</StripeCheckout>
</header>
</div>
);
}
export default App;
Node.js (index.js)
const cors = require('cors');
const express = require('express');
const stripe = require('stripe')("KEY");
const uuid = require("uuid");
const app = express();
//middleware
app.use(express.json());
app.use(cors());
//routes
app.get("/", (req,res)=>{
res.send("It works!!!")
});
app.post("/payment", (req,res)=>{
const{product, token} = req.body;
console.log("PRODUCT", product);
console.log("PRICE", product.price);
const idempontencyKey = uuid();
return stripe.customers.create({
email: token.email,
source: token.id
}).then(customer => {
stripe.charges.create({
amount: product.price * 100,
currency: 'usd',
customer: customer.id,
receipt_email: token.email,
description: product.name,
shipping: {
name: token.card.name,
address: {
country: token.card.address_country
}
}
}, {idempontencyKey})
})
.then(result => res.status(200).json(result))
.catch(err => console.log(err));
})
//listen
app.listen(8282, () =>{
console.log("Listening at PORT 8282");
});
【问题讨论】:
标签: node.js reactjs stripe-payments webhooks