1

I've read here that it's possible to send an IPN directly to a Google cloud function. I have my Google Cloud functions running on Firebase on an index.js file.

I've set up my Paypal buttons to send the IPN to a page on my webapp.

Here is an example of one of the functions I'm running off Google Cloud Functions/Firebase:

// UPDATE ROOMS INS/OUTS
exports.updateRoomIns = functions.database.ref('/doors/{MACaddress}').onWrite((change, context) => {
    const beforeData = change.before.val(); 
    const afterData = change.after.val(); 
    const roomPushKey = afterData.inRoom; 
    const insbefore = beforeData.ins; 
    const insafter = afterData.ins; 
    if ((insbefore === null || insbefore === undefined) && (insafter === null || insafter === undefined) || insbefore === insafter) {
        return 0;
    } else {
        const updates = {};
        Object.keys(insafter).forEach(key => {
            updates['/rooms/' + roomPushKey + '/ins/' + key] = true;
        });
        return admin.database().ref().update(updates); // do the update} 
    }   
    return 0;
});

Now question:

1) I want to add another function to process IPN from Paypal as soon as I have a transaction. How would I go about this?

I'll mark the answer as correct if solves this first question.

2) how would that Google cloud function even look like?

I'll create another question if you can solve this one.

Note I am using Firebase (no other databases nor PHP).

4 Answers 4

1

IPN is simply a server that tries to reach a given endpoint.

First, you have to make sure that your firebase plan supports 3rd party requests (it's unavailable in the free plan).

After that, you need to make an http endpoint, like so:

exports.ipn = functions.http.onRequest((req, res) => {
    // req and res are instances of req and res of Express.js
    // You can validate the request and update your database accordingly.
});

It will be available in https://www.YOUR-FIREBASE-DOMAIN.com/ipn

2
  • I'm on a Blaze plan. It supports 3rd party requests. Do I have to install the express.JS npm package? Could you provide an example on how to use/debug that req/res instances? Would I have to point the paypal button notify_url parameter to MY-FIREBASE-DOMAIN.com/ipn? Dec 5, 2018 at 14:38
  • Cloud Functions is using express.js, so you don't have to install it again. You can install the types if you want. And to your second question - No. Only Paypal should have access to that endpoint. I think you should take a look again at Paypal's docs to understand how the data should flow. Dec 5, 2018 at 14:52
1

Based on @Eliya Cohen answer:

on your firebase functions create a function such as:

exports.ipn = functions.https.onRequest((req, res) => {
    var reqBody = req.body;
    console.log(reqBody);
    // do something else with the req.body i.e: updating a firebase node with some of that info
    res.sendStatus(200);
});

When you deploy your functions go to your firebase console project and check your functions. You should have something like this:

enter image description here

Copy that url, go to paypal, edit the button that's triggering the purchase, scroll down to Step 3 and at the bottom type:

notify_url= paste that url here

Save changes.

You can now test your button and check the req.body on your firebase cloud functions Log tab.

1

Thanks to the answers here, and especially to this gist: https://gist.github.com/dsternlicht/fdef0c57f2f2561f2c6c477f81fa348e,

.. finally worked out a solution to verify the IPN request in a cloud func:

let CONFIRM_URL_SANDBOX = 'https://ipnpb.sandbox.paypal.com/cgi-bin/webscr';

exports.ipn = functions.https.onRequest((req, res) => {

    let body = req.body;
    logr.debug('body: ' + StringUtil.toStr(body));

    let postreq = 'cmd=_notify-validate';

    // Iterate the original request payload object
    // and prepend its keys and values to the post string
    Object.keys(body).map((key) => {
        postreq = `${postreq}&${key}=${body[key]}`;
        return key;
    });

    let request = require('request');

    let options = {
        method: 'POST',
        uri   : CONFIRM_URL_SANDBOX,
        headers: {
            'Content-Length': postreq.length,
        },
        encoding: 'utf-8',
        body: postreq
    };

    res.sendStatus(200);

    return new Promise((resolve, reject) => {

        // Make a post request to PayPal
        return request(options, (error, response, resBody) => {

            if (error || response.statusCode !== 200) {
                reject(new Error(error));
                return;
            }

            let bodyResult = resBody.substring(0, 8);
            logr.debug('bodyResult: ' + bodyResult);

            // Validate the response from PayPal and resolve / reject the promise.
            if (resBody.substring(0, 8) === 'VERIFIED') {
                return resolve(true);
            } else if (resBody.substring(0, 7) === 'INVALID') {
                return reject(new Error('IPN Message is invalid.'));
            } else {
                return reject(new Error('Unexpected response body.'));
            }
        });

    });

});

Also thanks to:

To receive IPN message data from PayPal, your listener must follow this request-response flow:

Your listener listens for the HTTPS POST IPN messages that PayPal sends with each event. After receiving the IPN message from PayPal, your listener returns an empty HTTP 200 response to PayPal. Otherwise, PayPal resends the IPN message. Your listener sends the complete message back to PayPal using HTTPS POST.

Prefix the returned message with the cmd=_notify-validate variable, but do not change the message fields, the order of the fields, or the character encoding from the original message.

1

Extremely late to the party but for anyone still looking for this, PayPal have made a sample in their JS folder on their IPN samples Github repo.

You can find this at: https://github.com/paypal/ipn-code-samples/blob/master/javascript/googlecloudfunctions.js

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.