如何在Cloud Functions for Cloudbase中发出HTTP请求?

Ras*_*han 26 node.js firebase google-cloud-functions firebase-cloud-functions

我正在尝试使用Cloud Functions for Firebase拨打苹果收据验证服务器.知道如何进行HTTP调用吗?

Sag*_*r V 7

答案是从 OP 的相关编辑中复制的


OP 使用https://github.com/request/request解决了这个问题

var jsonObject = {
  'receipt-data': receiptData,
  password: functions.config().apple.iappassword
};
var jsonData = JSON.stringify(jsonObject);
var firebaseRef = '/' + fbRefHelper.getUserPaymentInfo(currentUser);
let url = "https://sandbox.itunes.apple.com/verifyReceipt"; //or production  
request.post({
  headers: {
    'content-type': 'application/x-www-form-urlencoded'
  },
  url: url,
  body: jsonData
}, function(error, response, body) {
  if (error) {
  } else {
    var jsonResponse = JSON.parse(body);
    if (jsonResponse.status === 0) {
      console.log('Recipt Valid!');
    } else {
      console.log('Recipt Invalid!.');
    }
    if (jsonResponse.status === 0 && jsonResponse.environment !== 'Sandbox') {
      console.log('Response is in Production!');
    }
    console.log('Done.');
  }
});
Run Code Online (Sandbox Code Playgroud)


小智 6

请记住,您的依赖项占用空间将影响部署和冷启动时间。这是我使用https.get()functions.config()ping其他功能支持的端点的方法。在呼叫第三方服务时,您也可以使用相同的方法。

const functions = require('firebase-functions');
const https = require('https');
const info = functions.config().info;

exports.cronHandler = functions.pubsub.topic('minutely-tick').onPublish((event) => {
    return new Promise((resolve, reject) => {
        const hostname = info.hostname;
        const pathname = info.pathname;
        let data = '';
        const request = https.get(`https://${hostname}${pathname}`, (res) => {
            res.on('data', (d) => {
                data += d;
            });
            res.on('end', resolve);
        });
        request.on('error', reject);
    });
});
Run Code Online (Sandbox Code Playgroud)