Hi to all,
please advise me where I made a mistake. I need to connect wix with Stripe p [latebni method. Nsel s co co wixtrainingacadeemy and all others work. It shows me an error, I show below with the whole code.
Thanks
// page code
import { createToken, encodeCard } from "public/stripeAPI.js";
import { charge } from 'backend/stripeProxy.jsw';
var payment;
export function payNow(event) {
createToken(encodeCard(createCard()))
.then((token) => {
console.log("Card token: " + token);
charge(token, payment)
.then((chargeResponse) => {
console.log("Charge ID: " + chargeResponse.id);
});
});
}
function createCard() {
return {
"name": $w('#cname').value,
"number": $w('#cnumber').value,
"cvc": $w('#ccvc').value,
"exp_year": $w('#cyear').value,
"exp_month": $w('#cmonth').value
};
}
function changeState() {
payment = {
"amount": ($w("#amt").value),
"currency": "czk",
"description": $w("#desc").value
}
}
export function btn_click(event, $w) {
payNow();
}
export function amt_charge(event) {
changeState;
}
export function desc_change(event) {
changeState();
}
//public code
import {fetch} from 'wix-fetch';
export async function createToken(card) {
//Go to stripe.com to create a test key and replace the one in the example
const apiKey = "pk_test_YorS3kIpVkPaMp1F1z72Y1pO00tCVmuA08";
const response = await fetch("https://api.stripe.com/v1/tokens", {
method: 'post',
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Bearer " + apiKey
},
body: card
});
if (response.status >= 200 && response.status < 300) {
const json = await response.json()
return json.id;
}
const responseText = await response.text();
console.log(responseText);
return response.status;
}
export function encodeCard(card){
let encoded = "";
for (let [k, v] of Object.entries(card)) {
encoded = encoded.concat("card[", k, "]=", encodeURI(v), "&");
}
return encoded.substr(0, encoded.length - 1);
}
//backend code
import { fetch } from 'wix-fetch';
export async function charge(token, payment) {
const cart = payment;
//Go to stripe.com to create a test key and replace th eone in the example
const apiKey = "sk_test_dh0QSziJhsXrh5z7yGALlZgC00A5GVZVwp";
const response = await fetch("https://api.stripe.com/v1/charges", {
method: 'post',
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Bearer " + apiKey
},
body: encodeBody(token, cart)
});
if (response.status >= 200 && response.status < 300) {
return await response.json();
}
return await response.text();
}
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;
}