【问题标题】:Subscription failed using Stripe API in Google Apps Script在 Google Apps 脚本中使用 Stripe API 订阅失败
【发布时间】:2018-10-04 11:48:57
【问题描述】:

我正在尝试使用Google Apps ScriptStripe 制作一个附加组件,用户可以在其中订阅项目作为年度订阅。每次我从 Stripe 结帐购买订阅时,都会收到这样的错误,

{
  "error": {
   "code": "parameter_unknown",
   "doc_url": "https://stripe.com/docs/error-codes/parameter-unknown",
   "message": "Received unknown parameter: @45b5a607",
   "param": "@45b5a607",
   "type": "invalid_request_error"
  }
}

当我检查 Stripe Dashboard 中的日志时,我得到了这样的 POST 正文,

{
  "items": "[Ljava.lang.Object",
  "@45b5a607": null,
  "customer": "cus_Dix0eSYM5qP0kx"
}

这是我在 Google Apps 脚本中的代码,

var headers = {
    "Authorization" : "Basic " + Utilities.base64Encode(USERNAME + ':' + PASSWORD)
};

var customer = {
  'email': customerEmail,
  'source': token
};

var optCreate = {
  'method' : 'post',
  "headers" : headers,
  'contentType': 'application/x-www-form-urlencoded',
  'payload' : customer,
  'muteHttpExceptions' : true
};

var createCustomer = UrlFetchApp.fetch(urlCreate, optCreate);
var respCreate = JSON.parse(createCustomer.getContentText());
var customerId = respCreate.id;
if (customerId == null) { return "Error"; }

var data = {
  "customer" : customerId,
  "items" : [
    {
      "plan" : "plan_Diuw7CdAGcSrhm"
    }
  ]
};

var options = {
  'method' : 'post',
  "headers" : headers,
  'contentType': 'application/x-www-form-urlencoded',
  'payload' : data,
  'muteHttpExceptions' : true
};

var response = UrlFetchApp.fetch(url, options);
var resp = JSON.parse(response.getContentText());
Logger.log(resp);

我想我的 data JSON 对象一定是做错了什么。 items 字段无法正常工作,这就是 POST 正文很奇怪的原因。这里的正确方法是什么?

【问题讨论】:

    标签: javascript json google-apps-script stripe-payments


    【解决方案1】:

    您需要对有效负载进行字符串化。

    var options = {
      'method' : 'post',
      "headers" : headers,
      'contentType': 'application/x-www-form-urlencoded',
      'payload' : JSON.stringify(data),
      'muteHttpExceptions' : true
    };
    

    【讨论】:

    • 谢谢,但还是没有运气! :'(
    • 现在在 POST 正文中我明白了,{ "{"customer":"cus_DiyHlTwF1aR2YN","items":": { "{"plan":"plan_Diuw7CdAGcSrhm"}": { "}": null } } }
    【解决方案2】:

    看起来您正在发布 JSON 数据,但 Stripe 的 API 不接受 JSON——您需要使用表单编码。即您的代码需要将data 设置为这种格式:

    items[0][plan]=plan_CvVNfwZ4pYubYg&customer=cus_Diygqj4wAq6L9T
    

    您可以参考 Stripe 的 API 文档中的 cURL examples 了解这一点。通常,您应该使用official library 来简化 API 请求,但这可能无法通过 Apps 脚本实现。

    【讨论】:

    • 我已经制作了一个脚本,用于使用 JSON 在 Google Apps 脚本中对卡进行收费。效果很好,但在订阅部分遇到了问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-03
    • 2020-11-10
    • 1970-01-01
    • 2013-10-21
    • 1970-01-01
    • 1970-01-01
    • 2014-08-25
    相关资源
    最近更新 更多