Shopify Ajax API PUT更新客户信息返回404错误咨询
问题现象
通过Ajax请求调用Shopify后端接口更新客户邮箱、手机号、姓名信息时,请求返回404错误。
- 同接口在Postman、Chrome浏览器中可正常返回数据
- Postman中使用PUT方法调用该接口可成功修改对应字段值
现有实现代码
let custFN = document.getElementById("customerFirstName").getAttribute("value") ; let custLN = document.getElementById("customerLarstName").getAttribute("value") ; let custEM = document.getElementById("customerEmail").getAttribute("value") ; let custPH = document.getElementById("customerPhone").getAttribute("value") ; let custID = document.getElementById("customerId").getAttribute("value") ; let customerdata = { "customer": { "id": custID, "first_name": custFN , "last_name": custLN, "email": custEM, "phone": custPH, } }; var customer_data_json = JSON.stringify(customerdata); jQuery.cookie("session", null); jQuery.ajax({ url:'https://{api key}:{api password}@{mysotre}.myshopify.com/admin/api/2022-04/customers/{customer_id}}.json', type: 'PUT', cache: false, data: customer_data_json, crossDomain: true, dataType: "JSONP", contentType: "application/json; charset=utf-8", success: function(response) { console.log(response); }, error: function(response) { console.log("-------------------------------- <ERROR> --------------------------------"); console.log(response); console.log("-------------------------------- </ERROR> --------------------------------"); } });
已确认信息
- URL中
{}标注的占位参数均已替换为实际有效值 - 为解决CORS跨域报错,已将请求
dataType从JSON改为JSONP,当前请求返回的readyState值为4 - 已按Shopify官方文档指引创建私有应用,完成了Shopify API执行CRUD操作所需的全部配置步骤
问题原因及修复方法
直接触发404的两个显性问题
- 接口URL存在拼写错误:路径末尾的
{customer_id}}.json多写了一个右花括号,实际请求路径不匹配,会直接触发404,修正为{customer_id}.json即可解决路径拼写问题。 - JSONP根本不支持PUT请求:JSONP的实现原理是动态插入
<script>标签加载资源,天生只能发起GET请求,哪怕你在Ajax配置里写了type: 'PUT',jQuery处理JSONP请求时也会强制改用GET方法。用GET方法请求要求PUT方法的更新接口,自然无法匹配到正确的接口路由,会返回404或者405方法不允许错误。
致命安全隐患
把Shopify私有应用的API Key、API密码直接写在前端代码里的做法是完全错误的,所有访问页面的用户都可以直接在浏览器源码里拿到这两个凭证,获得店铺Admin API的全部操作权限,可随意篡改、删除商品、订单、客户数据,必须立刻废弃这种写法。
正确实现方案
- 不要在前端环境直接调用Shopify Admin API,需要在自己的服务端搭建一个中转接口:前端把待更新的客户信息提交到自有服务端接口,由服务端携带Admin API凭证向Shopify发起PUT更新请求,拿到结果后再返回给前端。这种方案既不会泄露API凭证,也不存在CORS跨域问题,更可以正常使用PUT方法完成更新操作。
- 如果是实现店铺前台已登录客户自主修改个人信息的功能,不要使用Admin API,应该使用Shopify面向前台场景的官方接口,配合客户的登录态做鉴权,不需要使用私有应用密钥。
内容的提问来源于stack exchange,提问作者Abd Bashir
相关产品推荐
相关产品推荐

