curl如何映射到Google App脚本URLFetchApp

时间:2018-12-18 03:11:07

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

我正在寻找在Google Apps脚本中实现Stripe的功能,该功能带有URLFetch功能,用于与第三方通信。但是,我很困惑Stripe使用的curl格式如何映射到URLFetch。

以下是他们文档中的Stripe调用示例:

curl https://api.stripe.com/v1/charges \
-u testtoken123: \
-H "Idempotency-Key: testkey" \
-d amount=2000 \
-d currency=usd \
-d description="Charge for jenny.rosen@example.com" \
-d source=tok_mastercard

URLFetchApp文档在这里:https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app

curl调用中的标志是否直接映射到URLFetch中的参数?

1 个答案:

答案 0 :(得分:1)

下面是帮助程序函数的示例,可用于在Google Apps脚本中调用Stripe API。

function getAuthHeader(){
  var apiKey = "STRIPE_API_KEY__CONSIDER_TO_GENERATE_A_KEY_WITH_LIMITED_SCOPE";
  var authHeader = 'Basic ' +Utilities.base64Encode(apiKey);
  return {
    headers: {Authorization: authHeader}
   }
}

function goFetch(url){
  var reponse; 
  try{
    reponse = JSON.parse(UrlFetchApp.fetch(url,getAuthHeader()).getContentText());
  }catch(err){
    Logger.log(err);
  }
  return reponse;
}

示例用法,列出费用:

function listCharges(lim){
  var url = 'https://api.stripe.com/v1/charges?'+limit=lim;
  return goFetch(url);
}
Logger.log(listCharges(10));

在您的示例中,您正在使用curl发出发布请求。从curl手册中:

  

-d,-数据                 (HTTP)将POST请求中的指定数据发送到HTTP服务器,就像浏览器在用户填写HTML表单并按Submit时所做的一样                 按钮。这将导致curl使用内容类型application / x-www-form-urlencoded将数据传递到服务器。与-F,-form进行比较。

UrlFetchApp reference manual中,您会找到以下内容:

// Make a POST request with form data.
var resumeBlob = Utilities.newBlob('Hire me!', 'text/plain', 'resume.txt');
var formData = {
  'name': 'Bob Smith',
  'email': 'bob@example.com',
  'resume': resumeBlob
};
// Because payload is a JavaScript object, it will be interpreted as
// as form data. (No need to specify contentType; it will automatically
// default to either 'application/x-www-form-urlencoded'
// or 'multipart/form-data')
var options = {
  'method' : 'post',
  'payload' : formData
};
UrlFetchApp.fetch('https://httpbin.org/post', options);

所以goPost函数将是这样的:

function goPost(url,data){
   var options = {
   'method' : 'post',
   'payload' : data,
   'headers': getAuthHeader()['headers']
   };
   var reponse; 
   try{
     reponse = JSON.parse(UrlFetchApp.fetch(url,options).getContentText());
   }catch(err){
    Logger.log(err);
   }
   return response;
 }

用法示例:

var data = {
  amount:2000,
  currency:'usd',
  source:'tok_amex',
  description:'Charge for jenny.rosen@example.com'
}
var result = goPost('https://api.stripe.com/v1/charges',data);
Logger.log(result);