Next.js集成Paystack报错Cookies未授权无法发送数据问题排查
报错根因
- 前端
axios.put参数顺序错误。axios的put方法签名为axios.put(url, requestData, config),当前代码将headers配置对象作为第二个参数(请求体位置)传入,实际没有向接口传递带用户token的Authorization请求头,后端isAuth鉴权中间件无法获取合法用户凭证,直接拦截请求触发权限类报错,是导致该提示的核心原因。 - Paystack运行环境配置不符合要求。Paystack弹窗要求当前访问域名必须提前加入后台允许域名列表,若本地调试使用非HTTPS服务、或浏览器开启了严格第三方Cookie拦截,也会直接抛出"Cookies are not authorized, we will not send any data."错误。
- 后端接口存在多处语法与逻辑错误,即使鉴权通过也无法正常执行:
- Sanity数据变更语法错误,使用了不存在的
paths字段,正确字段应为patch - 字段路径存在笔误,
"paymentResult..email_address"多写了一个点 - 支付结果字段映射完全颠倒,错误将id值赋值给邮箱字段、邮箱值赋值给id字段
- 缺少Sanity请求异常捕获,接口请求出错会直接返回500
- Sanity数据变更语法错误,使用了不存在的
- 前端状态更新action拼写错误,
"PAY SUCESS"缺少字母C,会导致支付成功后页面状态无法正常更新。
修复方案
1. 前端支付逻辑修复
调整axios参数顺序,接收Paystack回调返回的支付结果传入后端,修正action拼写:
const componentProps = { email: userInfo.email, amount: totalPrice * 100, metadata: { name: shippingAddress?.fullName, }, publicKey, text: "Pay Now", // 接收Paystack返回的支付结果参数 onSuccess: async (paymentResponse) => { try { dispatch({ type: "PAY_REQUEST" }); const { data } = await axios.put( `/api/orders/${order._id}/pay`, paymentResponse, // 支付结果作为请求体传给后端 // headers放在第三个配置参数位 { headers: { authorization: `Bearer ${userInfo.token}`, }, } ); dispatch({ type: "PAY_SUCCESS", payload: data }); // 修正action拼写 alert("Thanks for doing business with us! Come back soon!!"); } catch (error) { alert(getError(error)); } }, onClose: () => alert("Wait! Don't leave :("), };
2. Paystack平台配置调整
- 登录Paystack管理后台,进入设置页的API Keys & Webhooks板块,将项目线上域名、本地调试地址(如
http://localhost:3000)加入Allowed Domains列表 - 若使用Chrome等高安全策略浏览器,本地调试时可暂时关闭第三方Cookie拦截,或为本地开发服务配置HTTPS
- 确认当前使用的publicKey与环境匹配:测试环境使用test公钥,线上环境使用live公钥,禁止跨环境混用密钥
3. 后端支付回调接口修复
修正Sanity操作语法、字段映射,添加异常捕获:
import axios from "axios"; import nc from "next-connect"; import { isAuth } from "../../../../lib/auth"; const handler = nc(); handler.use(isAuth); handler.put(async (req, res) => { try { // 替换为实际的Sanity项目配置值 const projectId = "你的Sanity项目ID"; const dataset = "你的Sanity数据集名"; const tokenWithAccess = "你的Sanity操作token"; await axios.post( `https://${projectId}.api.sanity.io/v1/data/mutate/${dataset}`, { mutations: [ { // 修正为正确的patch语法 patch: { id: req.query.id, set: { isPaid: true, paidAt: new Date().toString(), // 修正字段映射,匹配Paystack返回的字段结构 "paymentResult.id": req.body.reference, "paymentResult.status": req.body.status, "paymentResult.email_address": req.body.customer.email, }, }, }, ], }, { headers: { "Content-type": "application/json", Authorization: `Bearer ${tokenWithAccess}`, }, } ); res.send({ message: "Order Paid Successfully" }); } catch (err) { res.status(500).send({ message: "Failed to update order payment status" }); } }); export default handler;
内容的提问来源于stack exchange,提问作者Peculiar DjEmmydon
相关产品推荐
相关产品推荐

