【问题标题】:Issue sending a JSON object to Stripe向 Stripe 发送 JSON 对象的问题
【发布时间】:2022-01-09 14:40:23
【问题描述】:

我正在尝试向 Stripe 发送 JSON 对象,但我总是收到来自响应的错误。

在未发送 /api/ctrlpnl/products_submit 响应的情况下解析 API,这可能会导致请求停止。 { 错误: { 代码:'parameter_unknown', doc_url: 'https://stripe.com/docs/error-codes/parameter-unknown', message: '收到未知参数:{"name":"dasdas"}', 参数:'{"name":"dasdas"}', 类型:'invalid_request_error' } }

我的代码如下:

 import Stripe from 'stripe';
 import { NextApiRequest, NextApiResponse } from 'next';

 const stripe = new Stripe(process.env.STRIPE_SECRET_KEY, {
     apiVersion: '2020-08-27'
 });

 export default async function handler(req: NextApiRequest, res: NextApiResponse) {

   if (req.method === 'POST') {
     try {   
       const name = { name: req.body.name };

       fetch(`${process.env.BASE_URL}/v1/products`, {
    
         method: 'POST',
         body: JSON.stringify(name),
         headers: {
             'Accept': 'application/json',
             "content-type": 'application/x-www-form-urlencoded',
             Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,
         }
         }).then((response) => {
             return response.json();
         }).then(data => {
             console.log(data);
             res.status(200).json(data)
         })

 } catch (err) {
     res.status(err.statusCode || 500).json(err.message);
 }
  } else {
     res.setHeader('Allow', 'POST');
     res.status(405).end('Method Not Allowed');
 }
 }

【问题讨论】:

  • 如果您还是要导入条带包,为什么要手动创建发布请求而不使用 sdk? stripe.products.create(...)
  • 感谢帕特里克的留言。可能需要将其转换为 stripe.create 产品。但我问的原因是,我想为培训目的解决这个问题。一般是希望能解决这个问题,所以以后如果需要发送JSON格式的数据,我可以实现,这里就不用发帖了。

标签: node.js http next.js stripe-payments


【解决方案1】:

fetchcontent-type 正确设置为application/x-www-form-urlencoded,但body 包含一个json。所以 Stripe 无法解析 body 参数。

要解决此问题,您需要将 JSON.stringify 替换为 new URLSearchParams

const name = { name: req.body.name };

fetch(`${process.env.BASE_URL}/v1/products`, { 
    method: 'POST',
    body: new URLSearchParams(name), // ← this will return "name=xxxx"
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization': `Bearer ${process.env.STRIPE_SECRET_KEY}`,
    }
});

请注意,我建议使用更简单的the Stripe librarystripe.products.create(name);,尤其是因为您已经将它包含在代码中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-10
    • 2014-03-14
    • 1970-01-01
    相关资源
    最近更新 更多