Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
//stripe.jsw
import {fetch} from 'wix-fetch';
export async function subscription(token, item) {
const cart = item;
const apiKey = "SECRET_API_KEY";
const response = await fetch("https://api.stripe.com/v1/subscriptions", {
method: 'post',
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Bearer " + apiKey
},
body: encodeBody(token, cart)
});
if (response.status >= 200 && response.status < 300) {
// transaction successful - get charge ID
const ret = await response.json();
return {"chargeId": ret.id};
}
// transaction failed - return error messages and codes
let res = await response.json();
let err = res.error.message;
let code = res.error.code;
let type = res.error.type;
return {"error": err, "code": code, "type": type};
}
function encodeBody(token, cart) {
let encoded = "";
for (let [k, v] of Object.entries(cart)) {
encoded = encoded.concat(k,"=", encodeURI(v), "&");
}
encoded = encoded.concat("source=", encodeURI(token));
return encoded;
}
//Creating a customer
export async function createCustomer(customer) {
const client = String(customer);
const apiKey = "SECRET_API_KEY";
const response = await fetch("https://api.stripe.com/v1/customers", {
method: 'post',
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Bearer " + apiKey
},
body: encodeClient(client)
});
if (response.status >= 200 && response.status < 300) {
const json = await response.json();
return json.id;
}
const responseText = await response.text();
return response.status;
}
function encodeClient(client){
let encoded = "";
encoded = encoded.concat("email=", encodeURI(client));
return encoded;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment