(function () { // Define your API keys and campaign name
const voucherifyBaseUrl = 'https://api.voucherify.io/client/v1'; // Replace with your API endpoint
const campaignName = 'campaign_name'; // Replace with your campaign name from which the voucher should be published
const apiKey = 'apiKey'; // Replace with your client-side Application ID
const secretKey = 'secretKey'; // Replace with your client-side Secret Key
const customer_id = window.wyng['_WYNG_ID_'].getLocalUserId(); // By this function, you can get the unique customer ID generated by Wyng
// Function to call Voucherify publication API. Pass variables as parameters you want to send to Voucherify, e.g., email, first_name, last_name, etc.
async function publishCode(email, first_name, last_name) {
try {
const response = await fetch(`${voucherifyBaseUrl}/publish`, {
method: 'POST',
headers: {
'X-Client-Application-Id': apiKey,
'X-Client-Token': secretKey,
'Content-Type': 'application/json',
},
body: JSON.stringify({
campaign: campaignName,
customer: {
source_id: customer_id,
email: email,
name: first_name + " " + last_name},
})
});
if (!response.ok) {
throw new Error('Failed to publish voucher');
}
// Below data will be displayed on the Wyng page
const publishedVoucher = await response.json();
document.getElementById('voucher_code').innerHTML =
publishedVoucher.voucher.code; // Get published voucher code
if(publishedVoucher.voucher.expiration_date){ // Optional: get voucher
expiration date published and display it in customer’s local timezone
document.getElementById('voucher_expiration_date').innerHTML = (new
Date(publishedVoucher.voucher.expiration_date)).toLocaleString()
}
else{
document.getElementById('voucher_expiration_date_containere').remove()
}
document.getElementById('voucher_qr_code_img').setAttribute("src",
publishedVoucher.voucher.assets.qr.url) // Optional: get voucher QR code published
} catch (error) {
console.error('Error publishing voucher:', error);
}
}
// Function to get data entered by the customer on the form
function listener(event) {
console.log(event) // Optional: to see event details in the console (may be useful to find
fields from which data should be passed)
const email = event.email;
const first_name = event.fields.find(field => field.field_type === 'first_name')?.answer;
const last_name = event.fields.find(field => field.field_type === 'last_name')?.answer;
publishCode(email,first_name,last_name)
}
window.wyng['_WYNG_ID_'].addEventListener('form_submit_success', listener);
})();