我正在尝试向我的网站添加 PayPal 付款功能。目前,我正在使用react-paypal-js 和 PayPal API v2 中的 PayPalButtons
我正在尝试向我的网站添加 PayPal 付款功能。目前,我正在使用react-paypal-js 和 PayPal API v2 中的 PayPalButtons。我面临的问题是,创建订单后,我无法检索 orderId,即刚刚创建的用于捕获 API 的令牌。
import React, { useEffect, useState } from "react";
import { PayPalButtons } from "@paypal/react-paypal-js";
import useBoundStore from "@/store/store";
type onApproveData = {
token: string,
orderId: string
}
export const PayPalButton = () => {
const layout: "vertical" | "horizontal" = "vertical";
const style = { layout };
const base = process.env.NEXT_PUBLIC_PAYPAL_API_URL || 'https://api-m.sandbox.paypal.com'
const ordersPaypalApi = {
test: "https://api-m.sandbox.paypal.com/v2/checkout/orders",
prod: "https://api-m.paypal.com/v2/checkout/orders"
};
const totalPrice = useBoundStore((state) => state.calculateRoomPrice?.reservations_amount_price)
const [token, setToken] = useState("")
const [orderId, setOrderId] = useState("")
const [dataApprove, setDataApprove] = useState<onApproveData>({token:"", orderId:""})
useEffect(()=>{
setDataApprove({token:token, orderId:orderId})
},[token, orderId])
async function generateAccessToken() {
const auth = Buffer.from(process.env.NEXT_PUBLIC_PAYPAL_CLIENT_ID + ':' + process.env.NEXT_PUBLIC_PAYPAL_CLIENT_SECRET).toString(
'base64'
)
const response = await fetch(`${base}/v1/oauth2/token`, {
method: 'POST',
body: 'grant_type=client_credentials',
headers: {
Authorization: `Basic ${auth}`,
},
})
return response.json()
}
const createOrder =async () => {
const res = await generateAccessToken()
const accessToken = res.access_token
localStorage.setItem(accessToken,"PAYPAL_TOKEN")
setToken(accessToken)
const url = process.env.NEXT_ENV !== "production" ? ordersPaypalApi.test : ordersPaypalApi.prod
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${accessToken}`,
},
body: JSON.stringify({
intent: 'CAPTURE',
purchase_units: [
{
amount: {
currency_code: 'USD',
value: Math.round(totalPrice),
},
},
],
}),
}
)
const responseData = await response.json();
const id = responseData.id;
setOrderId(id);
return id;
}
const onApprove = async ()=> {
const url = process.env.NEXT_ENV !== "production" ? ordersPaypalApi.test : ordersPaypalApi.prod + `/${orderId}/capture`
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
}
);
const capture = await response.json();
console.log("capture", capture);
}
return (
<PayPalButtons
style={style}
createOrder={createOrder}
onApprove={onApprove}
/>
);
};
付款人批准后,将调用
onApprove
函数,并且 orderId 将在该函数的第一个参数内传递给它。
利用第一个参数访问 orderId 值,并使用它对后端进行提取调用。