Prerequisites:
- Shopify Partner account.
- Shopify CLI installed.
- Node.js installed.
Step 1: Create a New App with Shopify CLI
shopify app create
Follow the prompts to set up your app. Choose Node.js
as the language.
Step 2: Add Shopify Functions to Your App
shopify app generate extension
Select Discount
as the type of extension.
Step 3: Develop the Function Logic
Navigate to the extensions
directory in your app, and open the discount function folder. Inside the src
directory, modify function.js
(or index.js
depending on your setup) to include the logic for customer tag-based discounts.
src/function.js
import { extend } from '@shopify/checkout-ui-extensions';
extend('checkout.discount', async (discounts) => {
// Get customer tags from the buyer
const customerTags = await fetchCustomerTags();
// Define your tag-based discount rules
const discountRules = [
{ tag: 'VIP', discount: 20 },
{ tag: 'Loyal', discount: 15 },
{ tag: 'New', discount: 10 }
];
// Find the highest discount applicable based on customer tags
let maxDiscount = 0;
customerTags.forEach(tag => {
const rule = discountRules.find(rule => rule.tag === tag);
if (rule && rule.discount > maxDiscount) {
maxDiscount = rule.discount;
}
});
// Apply the discount if any
if (maxDiscount > 0) {
discounts.apply({
percentage: maxDiscount,
message: `You received a ${maxDiscount}% discount for being a valued customer!`
});
}
});
async function fetchCustomerTags() {
// Replace with actual logic to fetch customer tags
// For demonstration, return a static list of tags
return ['VIP', 'New'];
}
Step 4: Deploy the Function
Deploy your app and function to Shopify using the following commands:
shopify app deploy
shopify app publish
Step 5: Update Shopify Admin to Use Your Function
- In your Shopify admin, navigate to
Settings > Checkout > Discounts
. - Enable the new discount extension and configure it to apply the discount based on customer tags.
Step 6: Testing
Test the discount by creating a customer with the appropriate tags and checking out. The discount should automatically apply based on the customer’s tags.
Explanation:
- Customer Tags Fetching: Replace
fetchCustomerTags
with logic to fetch actual customer tags, possibly using the Shopify Admin API. - Discount Rules: Define the discount rules based on customer tags.
- Applying Discounts: The function checks the customer’s tags and applies the highest applicable discount.
- Deployment: Deploy and publish your function, then enable it in your Shopify admin.
This example provides a basic structure for creating a customer tag-based discount function. You can customize it further based on your requirements.
Leave a Reply