You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在不刷新页面的情况下更新Shopify客户的accepts marketing?

无需刷新页面更新Shopify客户营销订阅状态的解决方案

方法1:针对已登录客户 - 使用Storefront API更新营销同意状态

Shopify已弃用accepts_marketing字段,改用marketingConsent对象管理订阅状态。通过Storefront API的GraphQL mutation可以无刷新完成更新:

  1. 在Liquid中准备必要参数:

    • 获取当前登录客户的GID格式ID:{{ 'gid://shopify/Customer/' | append: customer.id }}
    • 在Shopify后台创建开发应用,配置Storefront API权限(勾选write_customers),获取公共访问令牌
  2. Vue中发送GraphQL请求:

// 替换为你的店铺域名和Storefront API令牌
const shopDomain = '{{ shop.permanent_domain }}';
const storefrontToken = 'your-storefront-api-token';
const customerId = '{{ 'gid://shopify/Customer/' | append: customer.id }}';

// 构造mutation
const mutation = `
mutation UpdateCustomerMarketingConsent($customerId: ID!, $marketingConsent: CustomerMarketingConsentInput!) {
  updateCustomer(customerId: $customerId, marketingConsent: $marketingConsent) {
    customer {
      id
      marketingConsent {
        state
        optInLevel
      }
    }
    userErrors {
      message
    }
  }
}
`;

// 请求变量
const variables = {
  customerId: customerId,
  marketingConsent: {
    state: 'SUBSCRIBED', // 可选状态:SUBSCRIBED, UNSUBSCRIBED, PENDING
    optInLevel: 'SINGLE_OPT_IN', // 可选:SINGLE_OPT_IN, DOUBLE_OPT_IN
    marketingOptInLevel: 'SINGLE_OPT_IN'
  }
};

// 发送请求
fetch(`https://${shopDomain}/api/2024-07/graphql.json`, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-Shopify-Storefront-Access-Token': storefrontToken
  },
  body: JSON.stringify({ query: mutation, variables })
})
.then(res => res.json())
.then(data => {
  if (data.errors) {
    console.error('更新失败:', data.errors);
    // 提示用户错误信息
  } else {
    console.log('订阅状态更新成功:', data.data.updateCustomer.customer.marketingConsent);
    // 处理成功逻辑,比如显示订阅成功提示
  }
});

方法2:针对访客(未登录用户) - AJAX提交到邮件订阅端点

如果用户未登录,直接通过AJAX提交到Shopify内置的/newsletter端点,订阅后Shopify会自动创建客户并设置正确的营销同意状态:

const subscribeNewsletter = (email) => {
  fetch('/newsletter', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      'X-Requested-With': 'XMLHttpRequest'
    },
    body: new URLSearchParams({
      'contact[email]': email,
      'contact[tags]': 'newsletter-subscriber' // 可选:添加自定义标签
    })
  })
  .then(res => res.json())
  .then(data => {
    if (data.status === 'success') {
      // 订阅成功,显示提示
      alert('订阅成功!');
    } else {
      // 处理错误,比如邮箱已存在
      alert(data.message || '订阅失败,请重试');
    }
  })
  .catch(err => {
    console.error('请求错误:', err);
    alert('网络错误,请稍后重试');
  });
};

// 调用示例:subscribeNewsletter('user@example.com')

方法3:解决/contact接口的验证码问题

如果坚持使用/contact接口,需要处理Shopify的验证码验证(如hCaptcha/reCAPTCHA):

  1. 在页面中加载Shopify的验证码脚本(Liquid中添加:{{ '//hcaptcha.com/1/api.js' | script_tag }})
  2. 获取验证码token后,将其作为参数加入请求体:
// 先获取hCaptcha token
hcaptcha.execute('your-site-key', { action: 'newsletter' })
.then(token => {
  fetch('/contact', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      'X-Requested-With': 'XMLHttpRequest'
    },
    body: new URLSearchParams({
      'contact[email]': 'user@example.com',
      'contact[accepts_marketing]': 'true',
      'h-captcha-response': token
    })
  })
  .then(res => res.json())
  .then(data => {
    // 处理响应
  });
});

内容的提问来源于stack exchange,提问作者dustin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 08:01:23