How to implement json object in Cloud Functions for Firebase?

Viewed 2971

I want to verify apple in app purchase receipt by sending the original receipt to App store server for validation and get validated receipt back, using Firebase cloud functions.

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

This is the logic code. How do i input the receipt JSON object (which is sitting in the Firebase database) and how do i integrate this code in an http function? I am using 'request' npm library.

1 Answers

Based on your comment, it sounds as if you don't know how to query the database from within an HTTPS type function. You can use the Firebase Admin SDK for this. There are lots of examples of how to do this. In particular, this uppercase quickstart sample illustrates it. You start like this:

// The Firebase Admin SDK to access the Firebase Realtime Database. 
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
Related