How to make an HTTP request in Cloud Functions for Firebase?

社会主义新天地 提交于 2019-12-21 06:48:38

问题


I am trying to make a call to apples receipt verification server using Cloud Functions for Firebase. Any idea how to make an HTTP call?


回答1:


Keep in mind that your dependency footprint will affect deployment and cold-start times. Here's how I use https.get() and functions.config() to ping other functions-backed endpoints. You can use the same approach when calling 3rd party services as well.

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



回答2:


Answer is copied from OP's edit in question


OP solved this using 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.');
  }
});



回答3:


mostly using https://nodejs.org/api/https.html

const http = require("http");
const https = require('https');
const mHostname ='www.yourdomain.info';
const mPath     = '/path/file.php?mode=markers';

       const options = {
               hostname: mHostname,
               port: 80, // should be 443 if https
               path: mPath ,
               method: 'GET',
               headers: {
                  'Content-Type': 'application/json'//; charset=utf-8',
                }
       };

 var rData=""
       const req0 = http.request(options, (res0)=>
       {
          res0.setEncoding('utf8');

          res0.on('data',(d) =>{
                   rData+=d;

           });
           res0.on('end',function(){
                console.log("got pack");
                res.send("ok");
              });
      }).on('error', (e) => {
          const err= "Got error:"+e.message;
          res.send(err);
      });
req0.write("body");//to start request


来源:https://stackoverflow.com/questions/43486393/how-to-make-an-http-request-in-cloud-functions-for-firebase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!