Google Apps Script缓存键过长:Stripe支付链接生成优化求助
我在Google Apps Script中编写了一个为客户数据库生成Stripe支付链接的脚本,需在HTTP请求中传递邮箱参数与订阅链接。当前要作为缓存键的键值对集合如下:
line_items[0][price_data][currency]:"RON",line_items[0][price_data][recurring][interval]:"month",line_items[0][price_data][recurring][interval_count]:4,line_items[0][quantity]:1,line_items[0][price_data][product_data][name]:"Name",line_items[0][price_data][unit_amount]:31000,[customer_email]:"test@test.com"
需将其作为缓存键存入Cache.put(input, url, 21600),但Apps Script不允许超过250字符的参数。现确认以下三个方案的可行性:
- 是否支持传入多个对象执行PUT请求,如
put(input1,input2, url, 21600); - 在无法访问Stripe后端的前提下,能否通过精简重复字符串(如
line_items[0][price_data])来缩短输入; - 是否可以扩大Google Apps Script的参数最大长度至250字符以上。
相关源码:
const STRIPESUB = (amount, currency, description, customer_email) => { const input = { "line_items[0][price_data][currency]": currency || "RON", "line_items[0][price_data][recurring][interval]" : "month", "line_items[0][price_data][recurring][interval_count]" : 4, "line_items[0][quantity]" : 1, "line_items[0][price_data][product_data][name]": description || "Name", "line_items[0][price_data][unit_amount]": Math.ceil(amount * 100), "[customer_email]" : customer_email || "", }; const cacheKey = JSON.stringify(input); const cachedLink = CacheService.getScriptCache().get(cacheKey); if (cachedLink) return cachedLink; const params = { cancel_url: STRIPE_CANCEL_URL, success_url: STRIPE_SUCCESS_URL, mode: "subscription", billing_address_collection: "required", "payment_method_types[]": "card", ...input, }; const payload = Object.entries(params) .map(([key, value]) => [encodeURIComponent(key), encodeURIComponent(value)].join("=") ) .join("&"); const response = UrlFetchApp.fetch( "https://api.stripe.com/v1/checkout/sessions", { method: "POST", headers: { Authorization: `Bearer ${STRIPE_API_KEY}`, "Content-Type": "application/x-www-form-urlencoded", }, payload, muteHttpExceptions: true, } ); const { url, error } = JSON.parse(response); if (url) { CacheService.getScriptCache().put(cacheKey, url, 21600); } return error ? error.message : url; };
方案可行性分析
1. 多对象PUT请求的可行性
不可行。Google Apps Script的CacheService.put()方法仅支持单个键值对,签名为put(key, value, expirationInSeconds),不允许传入多个键或拆分键存储同一个值,强行传入会报错或忽略多余参数。
2. 精简重复字符串缩短输入的可行性
完全可行,这是最推荐的解决方案。你可以通过两种方式精简:
- 对原键名做自定义缩写,比如将
line_items[0][price_data][currency]简化为c,line_items[0][price_data][recurring][interval]简化为ri,生成缓存键后再映射回原键名构建Stripe请求; - 把
input改成结构化的简洁对象,而非展开成Stripe格式的长键,示例如下:
这样const input = { currency: currency || "RON", interval: "month", intervalCount: 4, quantity: 1, productName: description || "Name", unitAmount: Math.ceil(amount * 100), customerEmail: customer_email || "" };JSON.stringify(input)后的长度会大幅缩短,完全符合缓存键的长度限制,之后在构建Stripe请求参数时再映射回官方要求的完整键名即可。
3. 扩大参数最大长度的可行性
不可行。Google Apps Script的CacheService对键的长度限制是硬限制,官方文档明确规定键长度不能超过250字符,无法通过配置或其他方式修改该限制。
内容的提问来源于stack exchange,提问作者Iulian Tunea

