next.js 我得到“访问令牌未在缓存中找到”错误,而使用贝宝订单API

gywdnpxw  于 2023-04-30  发布在  其他
关注(0)|答案(1)|浏览(99)

我已经在我的应用程序中实现了使用Paypal功能登录,现在我已经存储了来自用户的access_tokenf。现在,当我调用创建订单API,然后调用捕获订单API时,我得到了这个错误。

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

我甚至试图验证,看看令牌是否未过期,它不是,但我仍然得到这个错误。我甚至尝试使用memory-cache在缓存中添加access_token,但仍然出现相同的错误。
我从/api nextJS后端调用这些API。所以我首先调用我的后端像/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 is expired
                res.status(200).json({ success: true, check: true, message: 'Token is expired' });
            } else {
                // token is not expired
                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使用refresh_token更新access_token的代码

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);
vof42yt1

vof42yt11#

看起来您正在使用身份登录PayPal /身份API令牌,就好像它们是API调用的client_credentials一样。他们不是。它们仅用于获取有关用户帐户的信息。
对于API调用,有两个选项:

(a)使用您自己的API actor客户端ID和secret,并在v2/checkout/orders API请求正文中指定payee

(b)对于某些API,例如v2/payments Refunds和Captures,指定PayPal-Auth-Assertion HTTP标头,其中包含对正在操作的帐户的payer_id进行编码的JWT令牌。
所有这些都记录在PayPal开发者参考文件中,这取决于您正在尝试执行的API操作;由于您的代码显示v2/checkout/orders查看使用您自己的client_id和secret来获取访问令牌(不使用Identity API,也不使用authentication_code和refresh_token,这些与grant_type=client_credentials无关)沿着payee来指定将接收付款的帐户。

相关问题