You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用PayPal Order API时遭遇「Access Token not found in cache」错误

PayPal创建订单API调用报错:invalid_token

错误信息

{
  error: 'invalid_token',
  error_description: 'Access Token not found in cache'
}

问题背景

已实现Login with PayPal功能并存储用户access_token,但调用create order和capture order API时出现上述错误。已确认token未过期,尝试用memory-cache缓存access_token后问题依旧。

API调用在NextJS后端的/api路径下进行,流程为调用/api/create-order,相关代码及依赖接口代码如下:


/api/create-order 代码

import dbConnect from "@/helpers/dbConnect";
import PaypalUser from "@/models/PaypalUser";
import axios from "axios";
import cache from "memory-cache";

const checkAccess = async (gmail) => {
    axios
        .post(process.env.NEXT_PUBLIC_AUTH_URL+"api/paypal/access", {
            gmail: gmail,
        })
        .then((res) => {
            if (res.data.success) {
                if (!res.data.check) {
                    return;
                } else {
                    axios
                        .post(process.env.NEXT_PUBLIC_AUTH_URL+"api/paypal/refresh", {
                            gmail: gmail,
                        })
                        .then((res) => {
                            if (res.data.success) {
                                return;
                            } else {
                                return;
                            }
                        })
                        .catch((err) => {
                            console.log(err);
                        });
                }
            } else {
                return;
            }
        })
        .catch((err) => {
            console.log(err);
        });
};

const handler = async (req, res) => {
    if (req.method === "POST") {
        const { gmail } = req.body;
        await checkAccess(gmail);
        const user = await PaypalUser.findOne({ gmail: gmail });
        if (user) {
            const { access_token, expires_in } = user;
            cache.put("access_token", access_token, expires_in);
            var myHeaders = new Headers();
            myHeaders.append("Content-Type", "application/json");
            myHeaders.append("Prefer", "return=representation");
            myHeaders.append(
                "Authorization",
                "Bearer " + access_token
            );

            var raw = JSON.stringify({
                intent: "CAPTURE",
                purchase_units: [
                    {
                        items: [
                            {
                                name: "Plan 1",
                                description: "This is a plan 1",
                                quantity: "1",
                                unit_amount: {
                                    currency_code: "USD",
                                    value: "100.00",
                                },
                            },
                        ],
                        amount: {
                            currency_code: "USD",
                            value: "100.00",
                            breakdown: {
                                item_total: {
                                    currency_code: "USD",
                                    value: "100.00",
                                },
                            },
                        },
                    },
                ],
            });

            var requestOptions = {
                method: "POST",
                headers: myHeaders,
                body: raw,
                redirect: "follow",
            };

            fetch(
                "https://api-m.sandbox.paypal.com/v2/checkout/orders",
                requestOptions
            )
                .then((response) => response.json())
                .then((result) => {
                    console.log(result)
                    res.status(200).json({ success: true, message: "Order created", order_id: result.id });
                })
                .catch((error) => console.log("error", error));
        } else {
            res.status(400).json({ success: false, message: "User not found" });
        }
    } else {
        res.status(400).json({ success: false, message: "Method not allowed" });
    }
};

export default dbConnect(handler);

/api/paypal/access 代码

import dbConnect from "@/helpers/dbConnect";
import PaypalUser from "@/models/PaypalUser";

const handler = async (req, res) => {
    if (req.method === 'POST') {
        const { gmail } = req.body;
        const user = await PaypalUser.findOne({ gmail: gmail });
        if (user) {
            const { last_time, expires_in, refresh_token } = user;
            const now = new Date().getTime();
            if (last_time + expires_in < now) {
                // token已过期
                res.status(200).json({ success: true, check: true, message: 'Token is expired' });
            } else {
                // token未过期
                res.status(200).json({ success: true, check: false, message: 'Token is not expired' });
            }
        } else {
            res.status(400).json({ success: false, message: 'User not found' });
        }
    } else {
        res.status(400).json({ success: false, message: 'Method not allowed' });
    }
}

export default dbConnect(handler);

/api/paypal/refresh 代码

import dbConnect from "@/helpers/dbConnect";
import PaypalUser from "@/models/PaypalUser";

const handler = async (req, res) => {
    if (req.method === "POST") {
        const { gmail } = req.body;
        const user = await PaypalUser.findOne({ gmail: gmail });
        if (user) {
            const { refresh_token } = user;
            var myHeaders = new Headers();
            myHeaders.append(
                "Content-Type",
                "application/x-www-form-urlencoded"
            );
            myHeaders.append(
                "Authorization",
                "Bearer {my base64 encoded clientID and secret}"
            );

            var urlencoded = new URLSearchParams();
            urlencoded.append("grant_type", "refresh_token");
            urlencoded.append("refresh_token", refresh_token);

            var requestOptions = {
                method: "POST",
                headers: myHeaders,
                body: urlencoded,
                redirect: "follow",
            };

            fetch(
                "https://api-m.sandbox.paypal.com/v1/oauth2/token",
                requestOptions
            )
                .then((response) => response.json())
                .then(async (result) => {
                    const { access_token, refresh_token, expires_in } = result;
                    // console.log(typeof access_token,typeof  refresh_token,typeof  expires_in);
                    const now = new Date();
                    const last_time = now.getTime();
                    const user = await PaypalUser.findOne({ gmail: gmail });
                    if (user) {
                        const user2 = await PaypalUser.findOneAndUpdate(
                            { gmail: gmail },
                            {
                                access_token: access_token,
                                last_time: last_time,
                                expires_in: expires_in,
                            }
                        );
                        res.status(200).json({ success: true, data: user2 });
                    } else {
                        const user3 = await PaypalUser.create({
                            access_token: access_token,
                            refresh_token: refresh_token,
                            last_time: last_time,
                            expires_in: expires_in,
                            gmail: email,
                        });
                        res.status(200).json({ success: true, data: user3 });
                    }
                })
                .catch((error) => {
                    console.log("error", error);
                    res.status(400).json({ success: false });
                });
        } else {
            res.status(400).json({ success: false, message: "User not found" });
        }
    } else {
        res.status(400).json({ success: false, message: "Method not allowed" });
    }
};

export default dbConnect(handler);

内容的提问来源于stack exchange,提问作者Pragyan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 04:07:11