Hello,Could you help me? I’m trying to create a function that, every time a customer makes a purchase in my store, generates an alphanumeric code for each item in their order.
For example:
Customer bought: 3x shoes and 3x dress shirt
Total = 6 items
Generated codes:
CODE1 = ABC5415
CODE2 = ABC5420
CODE3 = ABC5430
CODE4 = ABC5440
CODE5 = ABC5450
CODE6 = ABC5460
And save the generated code in the order’s metafield.
I created a file called ADDCODES.JS with this script:
// GENERATE RANDOM CODES
function generateRandomCode(length) { // ...code omitted }
// ADD CODES TO ORDERS
function addCodesToOrders(order) { const codes = []; for (let i = 1; i <= order.line_items.length; i++) { const namespace = custom.code${i}; const code = generateRandomCode(6); codes.push({ namespace, key: CODE${i}, value: code, value_type: 'string' }); }
// Add metafields to the order
shopify.order.addMetafields(order.id, codes); }
// EXECUTE
{% if order %} {% include 'addcodes' %} {% endif %}
However, when performing a test purchase, the metafields remain empty.
I will conduct a draw among customers who have purchased a specific item, and each of these items in the order entitles them to a number to enter the draw. Later, I will send these codes to the customers send by e-mail . Could you help me?