Shopify自定义Buy Now按钮首次点击跳转异常问题求助
Shopify自定义Buy Now按钮首次点击跳主页问题解决
问题描述
在Shopify中创建了自定义Buy Now按钮,期望点击后直接跳转到结账页面而非购物车,但用户首次访问站点点击按钮时,会被重定向到站点主页,再次点击则正常跳转至结账页。
相关代码
产品表单HTML
{% form 'product', product %} <div class="item-bottom"> <div class="item-left"> <h4>quantity</h4> <div class="item-count"> <div class="button-container"> <button type="button" id="decrease">-</button> </div> <input type="text" name="quantity" min="1" value="1" id="quantity" aria-label="Quantity of goods"> <div class="button-container"> <button type="button" id="increase">+</button> </div> </div> </div> </div> <div class="item-price"> <h4>price</h4> <p>{{ product.price | money }} <span>129.99$</span></p> </div> <select name="id" style="display: none;"> <option value="{{ product.variants[0].id }}"> {{ product.variants[0].title }} </option> </select> <button class="button buynow-btn" title="Buy" onClick="instantBuy()">Buy now</button> {% endform %}
点击事件JS
function instantBuy(){ var $ = jQuery; var formParams = $('form').serialize(); $.ajax({ url: "/cart", type: "post", data: formParams, success: function(){ window.location.href = "/checkout"; }, error: function(){ } }) }
问题原因
核心原因是Shopify的CSRF令牌验证机制:首次访问页面时,产品表单的CSRF令牌(_form_key字段)未完成正确初始化,手动发送的AJAX请求提交到/cart时验证失败,Shopify会默认重定向至主页;第二次点击时,表单已完成初始化,令牌有效,请求就能成功执行。另外,按钮默认的表单提交行为也可能和AJAX请求产生冲突,加重这个问题。
解决方案
方案一:使用Shopify官方JS方法添加商品
Shopify提供了内置的Shopify.addItem方法,会自动处理CSRF验证和变体校验,避免手动AJAX的问题:
function instantBuy(){ // 获取变体ID和数量 const variantId = $('select[name="id"]').val(); const quantity = parseInt($('#quantity').val()); // 调用官方方法添加商品 Shopify.addItem(variantId, quantity, function() { // 添加成功后跳转结账页 window.location.href = '/checkout'; }, function(error) { // 处理添加失败的情况 console.error('添加商品失败:', error); alert('添加商品失败,请重试'); }); }
方案二:修复AJAX请求,阻止表单默认行为
- 修改按钮为非提交类型,避免触发表单默认提交:
<button class="button buynow-btn" title="Buy" type="button" onClick="instantBuy()">Buy now</button>
- 改用Shopify标准的
/cart/add.js接口,并确保请求携带正确参数:
function instantBuy(){ const $ = jQuery; const formParams = $('form').serialize(); $.ajax({ url: "/cart/add.js", // 使用Shopify标准添加商品接口 type: "post", data: formParams, dataType: 'json', // 指定返回格式为JSON success: function() { window.location.href = "/checkout"; }, error: function(xhr) { // 打印错误信息方便调试 console.log('请求错误:', xhr.responseText); } }) }
方案三:直接构建结账跳转URL
跳过添加购物车的步骤,直接生成结账页URL,这种方式最简洁,也避免了AJAX的各种问题:
function instantBuy(){ const variantId = $('select[name="id"]').val(); const quantity = parseInt($('#quantity').val()); // 直接跳转至携带参数的结账页 window.location.href = `/checkout?variant=${variantId}&quantity=${quantity}`; }
注意事项
- 测试时请清除浏览器缓存,模拟首次访问的场景
- 确保变体ID正确无误,避免因变体不存在导致的跳转失败
- 若使用AJAX方案,优先选择Shopify官方提供的方法,减少兼容性问题
内容的提问来源于stack exchange,提问作者ilia416300
相关产品推荐
相关产品推荐

