Created
June 30, 2020 06:43
-
-
Save shanwixcode/b3fc81979f8e205fa60df5416bf35082 to your computer and use it in GitHub Desktop.
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
//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