Issue with afterOrderPaid Event Not Firing for License Assignment

Hi everyone,

I’m running into a problem with my Wix site. I need to automatically assign a unique license key (from a CMS collection) to customers after their purchase. To do this, I set up custom backend code using the afterOrderPaid event in my events.js file. The code is supposed to query my CMS for an unassigned license, mark it as used, and then email the customer the license key. Unfortunately doesn’t work so far.

// events.js
import { wixData } from 'wix-data';
import { emailContact } from 'wix-crm-backend';

/*
 * This function is triggered automatically after an order is successfully paid.
 * The 'event' parameter contains details like orderId, lineItems, and buyerInfo.
 */
export async function afterOrderPaid(event) {
  console.log("afterOrderPaid triggered with event:", event);

  // Extract order details from the event
  const orderId = event.orderId;
  const lineItems = event.lineItems;
  const buyerEmail = event.buyerInfo?.email;

  // Loop through each purchased item in the order
  for (const item of lineItems) {
    // Get the product ID associated with the item
    const productId = item.productId;
    
    // Query your "SerialNumbers" CMS collection for an unassigned license
    const results = await wixData.query("SerialNumbers")
      .eq("ProductID", productId)
      .eq("Assigned", false)
      .limit(1)
      .find();
    
    if (results.items.length > 0) {
      // Get the first available license and mark it as assigned
      let license = results.items[0];
      license.Assigned = true;
      license.OrderId = orderId; // Optionally store the order ID
      await wixData.update("SerialNumbers", license);
      
      // Send an email to the buyer with the license key
      await emailContact({
        toContact: { email: buyerEmail },
        subject: `Your License Key for Order ${orderId}`,
        body: `Thank you for your purchase! Your license key is: ${license.Serial}`
      });
      
      console.log(`License ${license.Serial} assigned to order ${orderId} and emailed to ${buyerEmail}`);
    } else {
      console.warn(`No available license found for product ${productId}`);
    }
  }
}

“afterOrderPaid” is incorrect and cannot be used in events.js

use onOrderCreated instead for events.js file On Order Created | Velo

Hi @jaosh_wiixrocket thank you for your message. I tried with your suggestion but unfortunately couldn’t get it to work. Is there anything else I could try?

You can try using wix automations and then run velo code through there. Invoke | Velo

Tried, can’t get it to work. Ahh I am trying for over a month now and still stuck.

What is not working? Have you consoled logged it?

If its not getting triggered, try the automation sequence and run a test order. See if the details go through.