我正在尝试将 paypal 付款集成到 JavaScript 应用程序中,但我无法测试订单处理,因为当我在 createOrder 函数中发送发布请求时,出现以下错误:
Access to fetch at 'https://api-m.sandbox.paypal.com/create-paypal-order' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
这是很多代码:
createOrder(data, actions) {
// Order is created on the server and the order id is returned
return fetch("https://api-m.sandbox.paypal.com/create-paypal-order", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
// use the "body" param to optionally pass additional order information
// like product skus and quantities
body: JSON.stringify({
orderID: data.orderID
}),
})
.then((response) => response.json())
.then((order) => order.id);
}
请问有什么帮助吗?
return fetch("https://api-m.sandbox.paypal.com/create-paypal-order", {
提取需要到您自己的后端服务器,而不是 PayPal API。例如
https://your-website-here.com/api/create-paypal-order
或类似。它可以是相对路径。
该后端服务器路由将依次与 PayPal API 进行通信,并且它应该仅返回/输出 JSON(绝不是任何 HTML 或其他调试文本),因为这是公共客户端代码期望解析为响应的内容。
与此相关的是,API 凭证(客户端密钥和它们获得的临时 access_token)永远不应该在客户端代码中使用。因此,本质上您必须创建一个后端路由,它充当 PayPal API 请求的代理,尽管它可能还会执行其他操作作为其工作的一部分(例如将成功捕获的 txn ID 与订单记录的其余部分一起存储在数据库中)