Problem with applying Coupon on Wix Pricing Plans - please Help

I have this code in a .jsw File:

import { coupons } from 'wix-marketing-backend';
import { checkout } from 'wix-pricing-plans-backend';

export async function createAndApplyCoupon(currentOrder, activeOrder) {
    const today = new Date();
    const endDate = new Date(activeOrder.currentCycle.startedDate);
    endDate.setFullYear(today.getFullYear() + 1);

    const timeDifference = endDate.getTime() - today.getTime();
    const daysUntilEnd = Math.ceil(timeDifference / (1000 * 3600 * 24));

    const total = activeOrder.priceDetails.total;
    const daysInCycle = activeOrder.pricing.prices[0].duration.cycleFrom === 1 ? 365 : 30;

    const pricePerDay = total / daysInCycle;
    const amountOff = Math.ceil(pricePerDay * daysUntilEnd);

    try {
        const uniqueCode = "UPGRADE" + Date.now();
        await createCoupon(amountOff, uniqueCode);
        await new Promise(resolve => setTimeout(resolve, 2000));
        const discountedOrder = await applyCoupon(currentOrder._id, uniqueCode);
        console.log('Coupon applied to current order successfully', discountedOrder);
    } catch (error) {
        console.error('Error in createAndApplyCoupon:', error);
    }
}


async function applyCoupon(orderId, couponCode) {
    return checkout.applyCoupon(orderId, couponCode)
        .then((discountedOrder) => {
            return discountedOrder;
        })
        .catch((error) => {
            console.error('Error applying coupon:', error);
            throw new Error('Failed to apply coupon');
        });
}


export function createCoupon(amountOff, couponCode) {
  let couponInfo = {
    "name": "Gutschrift",
    "code": couponCode,
    "startTime": new Date(),
    "expirationTime": new Date(2025, 12, 31),
    "usageLimit": 1,
    "limitedToOneItem": true,
    "limitPerCustomer": 1,
    "active": true,
    "scope": {
      "namespace": "pricingPlans"
    },
    "moneyOffAmount": 10 //should actually be "amountOff", but changed it for testing
  };
  console.log("Creating Coupon: " + couponInfo)
  return coupons.createCoupon(couponInfo);
}

And this code in the frontend Pricing page:

import wixLocation from 'wix-location';
import { orders } from 'wix-pricing-plans-frontend';
import { createAndApplyCoupon } from 'backend/upgradeLogic.jsw';

$w.onReady(function () {
    // Funktion zum Finden des ersten Auftrags mit einem bestimmten Status
    function findFirstOrderWithStatus(status) {
        const filters = {
            orderStatuses: [status]
        };

        return orders.listCurrentMemberOrders(filters)
            .then((ordersList) => {
                return ordersList.length > 0 ? ordersList[0] : null;
            })
            .catch((error) => {
                console.error('Error fetching orders:', error);
                return null;
            });
    }

    // Zuerst den aktiven Auftrag finden
    findFirstOrderWithStatus('ACTIVE').then(activeOrder => {
        if (activeOrder) {
            // Dann den Entwurfsauftrag finden
            findFirstOrderWithStatus('DRAFT').then(draftOrder => {
                if (draftOrder) {
                    console.log('Current Active Order:', activeOrder);
                    console.log('Current Draft Order:', draftOrder);
                    createAndApplyCoupon(draftOrder, activeOrder);
                } else {
                    console.log("No Current Draft order");
                }
            });
        } else {
            console.log("No Current Active order");
        }
    });

    let queryParams = wixLocation.query;
    if ("appSectionParams" in queryParams) {
        wixLocation.to("/preise?NoPlanRedirect=true");
    } else {
        $w('#section1').expand();
    }
});

Iā€™m trying to automatically apply a Coupon the the current order, which the user has opened. The coupon getā€™s successfully applied (as I can see in the backend events) but the coupon field on the standard checkout page stays empty (doesnā€™t get updated), even though itā€™s applied in the backend.

@CODE-NINJA ? Any thoughts? :sweat_smile:

Can anyone help?

I will take a look onto it todayā€¦ to be continuedā€¦

What iā€™m trying to achieve is get the ID of the current order which is opened in the Checkout page and then apply a Coupon code programmaticaly to that order:

@anthony any ideas?

Take a look, if you can use this one betterā€¦

import wixLocation from ā€˜wix-locationā€™;
import { orders } from ā€˜wix-pricing-plans-frontendā€™;

$w.onReady(async()=> {
    // Dein STEP-1: ---> Funktion zum Finden des ersten Auftrags mit einem bestimmten Status (ACTIVE)....
    let activeOrder = await findFirstOrderWithStatus('ACTIVE'); console.log('Active-Order: ', activeOrder);

    if (activeOrder) { 
      let draftOrder = await findFirstOrderWithStatus('DRAFT'); console.log('Draft-Order: ', draftOrder);
      if (draftOrder) {console.log("Draft order has been found!");
        console.log('Active Order:', activeOrder);
        console.log('Draft Order:', draftOrder);
        createAndApplyCoupon(draftOrder, activeOrder); //---> Now starting BACKEND-PROCESS ....
      } 
      else {console.log("No Current Draft order has been found!");}     
    } 
    else {console.log("No Current Active order has been found!");}

    //------------------------------------------------
    let queryParams = wixLocation.query;
    if ("appSectionParams" in queryParams) {
        wixLocation.to("/preise?NoPlanRedirect=true");
    } else {
        $w('#section1').expand();
    }
});


function findFirstOrderWithStatus(status) {
  return orders.listCurrentMemberOrders({orderStatuses:[status]})
  .then((ordersList)=> {return ordersList.length>0?ordersList[0]:null;})
  .catch((err)=> {console.error('Error fetching orders:', err); return null;});
}

For me it is a little bit difficult to follow, since i did not install whatever app to be able to work with coupons.

Next time please add some more information about your setup, likeā€¦
-what kind of editor
-which apps have been installed (in your case probably Wix-Events, including the COUPONS-Feature + Wix-Pricing-Plans, or Wix-Store).
2024-01-23 00_08_40-Wix Website Editor _ Pricing Plans Setup

Which automatically includes ā†’ The Coupons-Databaseā€¦

I changed your code a little bitā€¦

.
.
.

FRONTEND:

import wixLocation from 'wix-location';
import { orders } from 'wix-pricing-plans-frontend';

$w.onReady(async()=> {
    // Dein STEP-1: ---> Funktion zum Finden des ersten Auftrags mit einem bestimmten Status (ACTIVE)....
    let activeOrder = await findFirstOrderWithStatus('ACTIVE'); console.log('Active-Order: ', activeOrder);

    if (activeOrder) { 
      let draftOrder = await findFirstOrderWithStatus('DRAFT'); console.log('Draft-Order: ', draftOrder);
      if (draftOrder) {console.log("Draft order has been found!");
        console.log('Active Order:', activeOrder);
        console.log('Draft Order:', draftOrder);

        //Step-2: --> creating coupon....    
        const endDate = new Date(activeOrder.currentCycle.startedDate);
        endDate.setFullYear(new Date().getFullYear()+1);
        const timeDifference = endDate.getTime()-new Date().getTime();
        const daysUntilEnd = Math.ceil(timeDifference / (1000*3600*24));
        const total = activeOrder.priceDetails.total;
        const daysInCycle = activeOrder.pricing.prices[0].duration.cycleFrom===1 ? 365:30;
        const pricePerDay = total / daysInCycle;
        const amountOff = Math.ceil(pricePerDay * daysUntilEnd);
        const uniqueCode = "UPGRADE" + Date.now();
        //-------------------------------------------------        
        let myCoupon = await createCoupon(amountOff, uniqueCode); console.log('My-Coupon: ', myCoupon);

        //Step-3: --> applying coupon....    
        const discountedOrder = await applyCoupon(draftOrder._id, uniqueCode); console.log('Discount-Order: ', discountedOrder );

        // WHAT NEXT ?????????????????????????????????????

        //createAndApplyCoupon(draftOrder, activeOrder); //---> Now starting BACKEND-PROCESS ....
      } else {console.log("No Current Draft order has been found!");}     
    } else {console.log("No Current Active order has been found!");}

    //------------------------------------------------
    let queryParams = wixLocation.query;
    if ("appSectionParams" in queryParams) {
        wixLocation.to("/preise?NoPlanRedirect=true");
    } else {$w('#section1').expand();}
});

.
.
.
BACKEND:

export async function applyCoupon(orderId, couponCode) {
  return wixPricingPlansBackend.checkout.applyCoupon(orderId, couponCode)
  .then((discountedOrder)=> {return discountedOrder;})
  .catch((err) => {return err});
}


export function createCoupon(amountOff, couponCode) {
  let couponInfo = {
    "name": "Gutschrift",
    "code": couponCode,
    "startTime": new Date(),
    "expirationTime": new Date(2025, 12, 31),
    "usageLimit": 1,
    "limitedToOneItem": true,
    "limitPerCustomer": 1,
    "active": true,
    "scope": {
      "namespace": "pricingPlans"
    },
    "moneyOffAmount": 10 //should actually be "amountOff", but changed it for testing
  };
  console.log("Creating Coupon: " + couponInfo)
  return coupons.createCoupon(couponInfo);
}

Check if you can complete it like thatā€¦
Once you have a working version ā†’ you can then put all code back to BACKEND.

1 Like

Hi Russian-dima,

First of all thank you for your time and looking at my problem :slight_smile: Sorry for not including any additional info. As far as editor im using the regular Editor. And as far as apps, Iā€™m only using Members & Pricing plans, nothing else.

What Iā€™m trying to achieve with this code is giving the user a discount, for the unused time of his old plan (if he has one). I think this is called ā€œPro-Rata Chargesā€ (similar to, when you upgrade your Wix Premium Plan, you get a discount on your new plan, if youā€™re in the middle of a billing cycle of your old plan).

Thatā€™s why Iā€™m getting the ACTIVE order (this is the order which heā€™s currently on; so his active plan) and the DRAFT order (this is should be order which heā€™s currently ordering in the checkout).

Iā€™m using the regular Pricing Plans Widget to display the pricing plans to the users, so no custom repeater, etc. Meaning if the user clicks on Order pricing plan in that widget he gets redirected to the checkout (the standard Wix pricing plans checkout; no custom code in this step either). Meaning the only way to get the DRAFT order is during the checkout process (where the user is already in the standard checkout).

The main parts of the code work, I think, but the problem Iā€™m facing is that the applied coupon doesnā€™t get shown to the user in the checkout (the Coupon Field stays empty).

P.s As you can see in my backend-logs the coupon getā€™s created and applied to the order, but this isnā€™t shown to the user.

1 Like

Yes i already understood.

But you have the best overview over your own project-setup.

My recomendation would be to use more console-logs and working first as much as possible on the FRONTEND and inspect every little step first, by console-logs.

This is why i changed parts of your old code-version.

Do you get the same result with my provided code? Did you already test it?

I tried to simplyfy the code-structure and sort it by single steps and pushing it more over to frontend. This way, you are able to analy and debug faster, then doing it all the time on backend.

Also, there was a suspicious ā†’ timeOut inside of your code, i did not like it.
What for did you need the timeOut?

It is always much easier to debug, when you have the SETUP infront of your eyes, instead holding all the setup in your imaginations (brain).

Another question is: How did you got the Coupon-Database installed?
When i install only the Pricing-Plan-App ā†’ i do not get the COUPONDATABASE installed automatically, this happens only if i install the Wix-Events-App additionaly.

And as far as apps, Iā€™m only using Members & Pricing plans, nothing else.

What about generating a CUSTOM-CHECKOUT ?

1 Like

Iā€™m not sure of how to show this to the user. Perhaps this would make a good feature request on the Product Roadmap

hi Anthony,

This shouldnā€™t be an additional feature, this is more in the lines of a major bug with the applyCoupon function.

Iā€™ve also chatted to Wix Support, and according to them you arenā€™t able to add a coupon code programmatically and use the standard checkout page. Meaning I would have to create the whole checkout process from scratch.

Wix Support answer:

[ā€¦] It is not possible to change anything within Wix app widgets (like the checkout page) with the Velo code. If you want to apply the coupon code and display it at checkout, you need to create a custom checkout page from scratch.

1 Like

2024-01-24 12_41_20-Problem with applying Coupon on Wix Pricing Plans - please Help - Discussion _ A

Seeeems you did not read my post carefully :grinning:

I indeed read it, but thought, ā€œwix canā€™t possibly restrict that on the regular Checkoutā€ :smiling_face_with_tear: