Skip to content

Instantly share code, notes, and snippets.

@smilingleo
Last active December 22, 2015 19:19
Show Gist options
  • Save smilingleo/6518914 to your computer and use it in GitHub Desktop.
Save smilingleo/6518914 to your computer and use it in GitHub Desktop.
CORS-enabled API
function createXHR(method, url) {
var xhr = new XMLHttpRequest();
if (xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open(method, url, true);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
}
function generateSignature(callback) {
// call your own service to create a signature and token (by call Zuora's POST /v1/hmac-signatures)
var xhr = createXHR('get', '/signature');
if (!xhr) {
alert('CORS not supported');
return;
}
xhr.onload = function() {
var text = xhr.responseText;
var json = JSON.parse(text);
if (json.success) {
callback(json.signature, json.token);
}else {
alert("failed to get a signature from Zuora");
}
};
xhr.onerror = function(error) {
alert('Woops, there was an error making the request:' + error);
};
try {
xhr.send();
} catch (e) {
alert(e);
}
}
// Make the actual CORS request.
function makeCorsRequest(signature, token) {
var postCreditCardURL = 'https://api.zuora.com/rest/v1/payment-methods/credit-cards';
var xhr = createXHR('post', postCreditCardURL);
if (!xhr) {
alert('CORS not supported');
return;
}
// Set Headers
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("signature", signature);
xhr.setRequestHeader("token", token);
xhr.withCredentials = true;
// Response handlers.
xhr.onload = function() {
var text = xhr.responseText;
if (text) {
var json = JSON.parse(text);
if (json.success) {
// successfully create a credit card
alert("Woohoo, created a credit card in Zuora, its Zuora internal id: " + json.paymentMethodId);
} else {
// Your error handling code here, note: the error code is your friend.
}
} else
alert("failed to get response text");
};
xhr.onerror = function() {
alert('Woops, there was an error making the request.');
};
var postCreditCard = {
"accountKey": document.getElementById("accountKey").value,
"creditCardType": document.getElementById("creditCardType").value,
"creditCardNumber": document.getElementById("creditCardNumber").value,
"expirationMonth": document.getElementById("expirationMonth").value,
"expirationYear": document.getElementById("expirationYear").value,
"securityCode": document.getElementById("securityCode").value,
"defaultPaymentMethod": document.getElementById("defaultPaymentMethod").value
};
try {
xhr.send(JSON.stringify(postCreditCard));
} catch (e) {
alert(e);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment