Hi,
Please can I have some help amending the below (Stripe Payment integration) code to effectively;
a) check if the user already exists in the database - if they do, Update the subscriptionStartDate field in the database only (plus update end date if 'Associate'). If they don't already exist, all of the info is Saved to the database instead. At present, the user is added as an item in the database for the first time when they SignUp via the Wix User Login and then a second time when they successfully pay. I need it to update the pre-existing item instead of creating this second one.
b) upon buyNow click, also auto generate a "membershipNo" based on the year + the timestamp, then add the number to a specified field in the database (have come up with the below so far - my attempts to integrate this just brings up errors);
$w.onReady(function () { unixCode(); }); function unixCode (){
$w("#membershipNo").value = "2018" + Math.round(new Date().getTime()/1000.0); }
* Here is the full code, as it stands currently:
import wixUsers from 'wix-users';
import {
createToken,
encodeCard
} from "public/stripeAPI.js";
import {
charge,
createCustomer,
createBilling
} from 'backend/stripeProxy';
import wixWindow from "wix-window";
import wixData from "wix-data";
import wixLocation from 'wix-location';
let userID;
let userEmail;
var payment, pmtdata;
$w.onReady(async function () {
userID = wixUsers.currentUser.id;
userEmail = await wixUsers.currentUser.getEmail();
pmtdata = wixWindow.lightbox.getContext();
changeState(pmtdata.amount, pmtdata.description);
$w("#buyNow").label = "Pay " + "£" + pmtdata.amount;
});
async function payNow() {
let token = await createToken(encodeCard(createCard()));
console.log("Card token: " + token);
let chargeResponse = await charge(token, payment);
console.log("Charge response id: " + chargeResponse.id);
return chargeResponse;
}
async function billNow(email) {
let token = await createToken(encodeCard(createCard()));
console.log("Card token: " + token);
let customer = await createCustomer(email, userID, token);
console.log(customer.id);
if (!customer.id) {
return console.log("Error with Credit Card. Please contact us.")
}
let billing = await createBilling(customer.id, pmtdata.description);
console.log("Billing response id: " + billing.id);
return billing;
}
function createCard() {
return {
"name": $w("#cardName").value,
"number": $w("#cardNo").value,
"cvc": $w("#cvc").value,
"exp_year": $w("#expYear").value,
"exp_month": $w("#expMonth").value
};
}
function changeState(x, y) {
payment = {
"amount": (x * 100),
"currency": "GBP",
"description": y
}
}
export async function buyNow_click(event, $w) {
$w("#buyNow").disable();
let response;
if (pmtdata.itemName === "Associate") response = await payNow();
else response = await billNow(userEmail);
if (response.id === undefined) {
$w("#err").show();
$w("#err").text = "Error with Credit Card. Please contact us.";
return;
}
// sophie wrote
if (response.status) {
$w("#err").show();
$w("#err").text = "Payment success!";
let member = null;
let results = await wixData.query("Members").eq("wixUserId", wixUsers.currentUser.id).find();
if (results.items.length > 0) {
member = results.items[0];
}
let toSave = {
wixUserId: wixUsers.currentUser.id,
"firstName": pmtdata.firstName,
"surname": pmtdata.surname,
"email": pmtdata.email,
"paymentFrequency": pmtdata.paymentFrequency,
"subscriptionStartDate": new Date(),
"payments": response.id
};
if (pmtdata.itemName === "Associate") {
let oneYearFromNow = new Date();
oneYearFromNow.setFullYear(oneYearFromNow.getFullYear() + 1);
toSave.subscriptionEndDate = oneYearFromNow;
}
if (member !== null) {
toSave._id = wixUsers.currentUser.id;
}
console.log(toSave);
let options = {
"suppressAuth": true,
"suppressHooks": true
};
wixData.save("Members", toSave, options)
.then(() => {
console.log("Saved Successfully to Database.");
wixLocation.to("/thankyou");
}) .catch((err) => { let errorMsg = err; $w("#err").show(); $w("#err").text = errorMsg; }); } }
Thanks very much for any help! I have stared at this too long and can't seem to get it right any more!
Hi Anna,
For the check if user exist or not, it will be always true, because the registered user will be in the database. So, i think you're just missing to use the Wix Users api to check if the user role === 'member' then { do whatever you want} else { ... } - check it here
For the point B, what types of error you get? can you clarify more.
Hope this helps you,
Best.
Mustafa