Last active
August 29, 2015 14:17
-
-
Save greenido/fd255727cceb76e13184 to your computer and use it in GitHub Desktop.
An example for a blog post on In-App payments on the web
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
// Typically you would attach this to the click handler on a Buy button. | |
purchaseSomething("Buy a new mountain bike! Something that is 29' in yellow - please!"); | |
function purchaseSomething(productID) { | |
var xhr = new XMLHttpRequest(); | |
xhr.responseType = 'json'; | |
// Prepare to send a productID to your server and | |
// receive an array of JSON Web Token (=jwts) that describe your data | |
xhr.open('POST', '/create_jwts'); | |
xhr.addEventListener('load', function () { | |
// Retrieve the JSON Web Token and a transactionID from a JSON response, | |
// Such as: | |
// {"jwts": ["jwt1...", "jwt2..."], "transactionID": "1234"} | |
var jwts = xhr.response.jwts; | |
var transactionID = xhr.response.transactionID; | |
// Pass the JSON Web Tokens to the payment provider | |
var request = navigator.mozPay(jwts); | |
// Set up the success/error handler for the payment window. | |
request.onsuccess = function () { | |
console.log('The user payment flow completed successfully! Go ride!'); | |
// Although the payment flow completed, you need to poll your server and wait | |
// for a verified payment result to be sure the payment went through. | |
waitForPaymentResult(transactionID); | |
}; | |
request.onerror = function () { | |
console.log(':( Sorry, the payment flow had an error:', this.error.name); | |
}; | |
}) | |
// Initiate the payment request by sending information to | |
// get the signed JSON Web Tokens. In our example, productID | |
// is the ID of the product the user wants to puchase. | |
xhr.send(productID); | |
} | |
function waitForPaymentResult(transactionID) { | |
var xhr = new XMLHttpRequest(); | |
xhr.responseType = 'json'; | |
// Prepare to check if a postback/chargeback has been received for transactionID. | |
xhr.open('GET', '/payment_result/' + transactionID); | |
xhr.addEventListener('load', function () { | |
// Retrieve the result, such as: | |
// {"result": "postback received"} or {"result": "still waiting"} | |
if (xhr.response.result == 'postback received') { | |
// A postback notice was received and you verified the incoming JWT signature. | |
console.log('Success! The product has been purchased'); | |
} else { | |
// No postback/chargeback has been sent to your server yet. Try again in 3 seconds. | |
window.setTimeout(function() { waitForPaymentResult(transactionID); }, 3000); | |
} | |
}); | |
// Send the request to check the transactionID status. | |
xhr.send(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment