Last active
June 24, 2020 04:06
-
-
Save gopalkildoliya/1e254530b82cb86b55f7b83e8989fe25 to your computer and use it in GitHub Desktop.
Firebase function to handle Paddle incoming events
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const crypto = require('crypto'); | |
const Serialize = require('php-serialize'); | |
const functions = require('firebase-functions'); | |
const admin = require('firebase-admin') | |
admin.initializeApp(); | |
const pubKey = `-----BEGIN PUBLIC KEY----- | |
YOUR PUBLIC KEY HERE | |
-----END PUBLIC KEY-----` | |
function ksort(obj){ | |
const keys = Object.keys(obj).sort(); | |
let sortedObj = {}; | |
for (let i in keys) { | |
sortedObj[keys[i]] = obj[keys[i]]; | |
} | |
return sortedObj; | |
} | |
function validateWebhook(jsonObj) { | |
const mySig = Buffer.from(jsonObj.p_signature, 'base64'); | |
delete jsonObj.p_signature; | |
// Need to serialize array and assign to data object | |
jsonObj = ksort(jsonObj); | |
for (let property in jsonObj) { | |
if (jsonObj.hasOwnProperty(property) && (typeof jsonObj[property]) !== "string") { | |
if (Array.isArray(jsonObj[property])) { // is it an array | |
jsonObj[property] = jsonObj[property].toString(); | |
} else { //if its not an array and not a string, then it is a JSON obj | |
jsonObj[property] = JSON.stringify(jsonObj[property]); | |
} | |
} | |
} | |
const serialized = Serialize.serialize(jsonObj); | |
// End serialize data object | |
const verifier = crypto.createVerify('sha1'); | |
verifier.update(serialized); | |
verifier.end(); | |
const verification = verifier.verify(pubKey, mySig); | |
return verification; | |
} | |
exports.webhookPaddle = functions.https.onRequest(async (request, response) => { | |
if (validateWebhook(request.body)) { | |
var data = request.body; | |
delete data.p_signature; | |
if (data.alert_name === 'subscription_created' && data.passthrough) { | |
data.uid = data.passthrough; | |
} | |
await admin.firestore().collection('subscriptions').doc(data.subscription_id).set(data, {merge: true}); | |
await admin.firestore().collection('subscriptions').doc(data.subscription_id).collection('event').doc(data.alert_id).set(data, {merge: true}); | |
} | |
response.send(true) | |
// response.send("Hello from Firebase!"); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment