Skip to content

Instantly share code, notes, and snippets.

@reggie3
Last active September 25, 2017 19:52
Show Gist options
  • Save reggie3/0ab489ca586b9e8cd2e0ad7f5d36255f to your computer and use it in GitHub Desktop.
Save reggie3/0ab489ca586b9e8cd2e0ad7f5d36255f to your computer and use it in GitHub Desktop.
Braintree Payment Javascript Version index.js
import RNMessageChannel from "./react-native-webview-messaging";
const dropin = require("braintree-web-drop-in");
const submitButton = document.querySelector("#submit-button");
let clientToken = "";
const goBackButton = document.querySelector("#go-back-button");
const noticeBox = document.querySelector("#notice-box");
const loader = document.querySelector("#loader");
// receive the tokenReceived event
RNMessageChannel.on("tokenReceived", event => {
// extract token from event payload
clientToken = event.payload.clientToken;
// use token to create the payment UI
createCreditCardUI(clientToken);
});
// built the UI
const createCreditCardUI = clientToken => {
dropin
.create({
authorization: clientToken,
container: "#dropin-container"
})
.then(instance => {
// attach an event to the Braintree drop-in UI that sends the "nonceObtained" event
// along with the nonce as a payload
// back to the parent WebView so that it can be sent to the payment screen which
// will use it to submit the payment to the application server
submitButton.addEventListener("click", function() {
instance.requestPaymentMethod(function(err, response) {
// some error catching
if (err) {
RNMessageChannel.emit("nonceObtained", {
payload: {
type: "error",
err
}
});
} else {
// Submit payload nonce
RNMessageChannel.emit("nonceObtained", {
payload: {
type: "success",
response
}
});
}
});
});
})
.catch(function(err) {
// Handle any errors that might've occurred when creating Drop-in
RNMessageChannel.sendJSON({
type: "error",
err
});
});
};
// set up listeners to alter the DOM in response to different
// events in the payment cycle
RNMessageChannel.on("purchasing", event => {
submitButton.style.display = "none";
noticeBox.style.display = "inline";
loader.style.display = "inline";
noticeBox.innerHTML = "Making Purchase";
});
RNMessageChannel.on("purchaseSuccess", event => {
goBackButton.style.display = "inline";
loader.style.display = "none";
noticeBox.innerHTML = "Thank You For Your Purchase";
});
RNMessageChannel.on("purchaseFailure", event => {
goBackButton.style.display = "inline";
loader.style.display = "none";
noticeBox.innerHTML = `Purchase Error ${event.payload}`;
});
// add a listener to a button that will allow the user to navigate away from the payment
// page when the process is complete
goBackButton.addEventListener("click", function() {
RNMessageChannel.emit("goBack");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment