使用Zoho Flow的Deluge函数调用Shopify GraphQL接口遇问题求解决
问题分析与解决方案
你的Deluge代码核心问题出在请求体的JSON拼接错误以及GraphQL查询的构建逻辑上,以下是具体修正方案:
核心问题点
- 无效JSON请求体:原代码手动拼接
body时,错误地给已包含外层大括号的query重复嵌套大括号,同时字符串转义逻辑混乱,导致请求体格式不符合Shopify GraphQL接口要求。 - 字符串拼接风险:直接将
externalId和email拼进查询字符串,易因特殊字符破坏语法,还存在潜在的注入风险。
修正后的代码
// 构建请求头 headers = Map(); headers.put("X-Shopify-Access-Token", v_AccessToken); headers.put("Content-Type", "application/json"); // 构建GraphQL查询,使用变量传递参数避免直接拼接 query = "query($externalId: String!, $email: String!) { companies(first: 1, query: \"external_id:'$externalId'\") { edges { node { id name defaultRole { id name } contacts(first: 1, query: \"email:$email\") { edges { node { id title isMainContact customer { id lastName firstName email } __typename } } } locations(first: 1) { nodes { id name catalogs(first: 1) { nodes { title } } } } } } }"; // 用Map构建请求体,自动生成标准JSON requestBody = Map(); requestBody.put("query", query); // 定义GraphQL变量 variables = Map(); variables.put("externalId", externalId); variables.put("email", email); requestBody.put("variables", variables); // 转换为JSON字符串 body = requestBody.toJSONString(); // 发送POST请求 response = postUrl("https://dev-speechi-partenaire.myshopify.com/admin/api/2024-07/graphql.json", {"headers": headers, "body": body}); // 解析响应 response_map = response.toMap(); info response_map;
关键修改说明
- 用Map构建请求体:通过Deluge的
Map对象构建请求体,再调用toJSONString()生成标准JSON,彻底避免手动拼接导致的转义错误。 - GraphQL变量传参:将
externalId和email作为GraphQL变量传入,既解决了直接拼接的语法问题,也提升了代码安全性。 - 修正查询结构:确保查询字符串本身是合法的GraphQL语句,请求体的
query字段直接使用该语句,无需额外嵌套大括号。
如果需要兼容原写法(不推荐),也可以直接修正字符串拼接逻辑:
// 修正请求体拼接逻辑 query = "{ companies(first: 1, query: \"external_id:'" + externalId + "'\") { edges { node { id name defaultRole { id name } contacts(first: 1, query: \"email:" + email + "\") { edges { node { id title isMainContact customer { id lastName firstName email } __typename } } } locations(first: 1) { nodes { id name catalogs(first: 1) { nodes { title } } } } } } }"; // 手动转义查询字符串中的双引号,避免破坏JSON结构 body = "{\"query\": \"" + query.replaceAll("\"", "\\\\\"") + "\"}";
内容的提问来源于stack exchange,提问作者Lucas Montier
相关产品推荐
相关产品推荐

