1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
|
function arrayBufferToBase64(buffer) { const bytes = new Uint8Array(buffer); let binary = ''; for (let i = 0; i < bytes.byteLength; i++) { binary += String.fromCharCode(bytes[i]); } return btoa(binary); }
function safeCompare(a, b) { if (a.length !== b.length) return false; let result = 0; for (let i = 0; i < a.length; i++) { result |= a.charCodeAt(i) ^ b.charCodeAt(i); } return result === 0; }
async function verifyShopifySignature(request, rawBody, secret) { const hmacHeader = request.headers.get('X-Shopify-Hmac-Sha256'); if (!hmacHeader || !secret) return false;
const encoder = new TextEncoder(); const keyBuffer = encoder.encode(secret); const bodyBuffer = encoder.encode(rawBody);
const cryptoKey = await crypto.subtle.importKey( 'raw', keyBuffer, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign'] );
const signatureBuffer = await crypto.subtle.sign('HMAC', cryptoKey, bodyBuffer); const calculatedHmac = arrayBufferToBase64(signatureBuffer);
return safeCompare(calculatedHmac, hmacHeader); }
export default { async fetch(request, env, ctx) { if (request.method !== 'POST') { return new Response('Method Not Allowed', { status: 405 }); }
const shopDomain = request.headers.get('X-Shopify-Shop-Domain'); if (!shopDomain) { return new Response('Bad Request: Missing Shop Domain Header', { status: 400 }); }
let currentStoreRaw = null; try { currentStoreRaw = await env.STORE_PUSH.get(shopDomain); } catch (e) { console.error('KV Storage 读取失败:', e); return new Response('Internal Server Error', { status: 500 }); }
if (!currentStoreRaw) { console.error(`未注册的店铺域名: ${shopDomain}`); return new Response('Unauthorized: Unknown Shop Domain', { status: 403 }); }
const currentStore = JSON.parse(currentStoreRaw); const rawBody = await request.text();
const isValid = await verifyShopifySignature(request, rawBody, currentStore.secret); if (!isValid) { console.error(`签名校验失败: ${shopDomain}`); return new Response('Unauthorized: Invalid Signature', { status: 401 }); }
try { const order = JSON.parse(rawBody);
const storeName = currentStore.name || shopDomain; const orderName = order.name || '未知订单'; const totalPrice = order.total_price || '0.00'; const currency = order.currency || 'USD';
let customerName = '游客/无客户信息'; let orderCountText = '游客下单'; if (order.customer) { const firstName = order.customer.first_name || ''; const lastName = order.customer.last_name || ''; customerName = `${firstName} ${lastName}`.trim() || '匿名客户'; const count = order.customer.orders_count || 1; orderCountText = count === 1 ? '🔥 第 1 次订购 (新客)' : `🔁 第 ${count} 次复购`; }
const customerEmail = order.email || (order.customer && order.customer.email) || '无邮箱信息'; const country = order.shipping_address ? order.shipping_address.country : (order.billing_address ? order.billing_address.country : '未知国家');
let discounts = []; if (order.discount_codes && order.discount_codes.length > 0) { order.discount_codes.forEach(d => { const amountText = d.amount ? ` (-${d.amount} ${currency})` : ''; discounts.push(`\`码: ${d.code}\`${amountText}`); }); } if (order.discount_applications && order.discount_applications.length > 0) { order.discount_applications.forEach(app => { if (app.type === 'discount_code') { const alreadyAdded = order.discount_codes && order.discount_codes.some(d => d.code === app.code); if (alreadyAdded) return; } const discountTitle = app.title || app.code || '自动折扣'; let valueText = ''; if (app.value_type === 'percentage') { valueText = ` (-${app.value}%)`; } else if (app.value_type === 'fixed_amount') { valueText = ` (-${app.value} ${currency})`; } discounts.push(`\`自动: ${discountTitle}\`${valueText}`); }); } const discountText = discounts.length > 0 ? discounts.join(', ') : '未使用折扣';
let shippingText = '免运费'; if (order.shipping_lines && order.shipping_lines.length > 0) { shippingText = order.shipping_lines.map(s => { const price = parseFloat(s.price); return price > 0 ? `${s.title} (${s.price} ${currency})` : `免运费 (${s.title})`; }).join(', '); }
let lineItemsText = ''; if (order.line_items && order.line_items.length > 0) { lineItemsText = order.line_items.map(item => { const skuText = item.sku ? `\`SKU: ${item.sku}\`` : '*无 SKU*'; const itemPrice = item.price || '0.00'; return `• **${item.title}** x ${item.quantity} _(${itemPrice} ${currency}/件)_\n ┗ ${skuText}`; }).join('\n'); } else { lineItemsText = '无商品数据'; }
const feishuPayload = { msg_type: "interactive", card: { config: { wide_screen_mode: true }, header: { title: { tag: "plain_text", content: `[${storeName}] 🎉 新订单 ${orderName} (${totalPrice} ${currency})` }, template: "indigo" }, elements: [ { tag: "column_set", background_style: "grey", columns: [ { tag: "column", width: "weighted", weight: 1, elements: [ { tag: "div", fields: [ { is_short: true, text: { tag: "lark_md", content: `**来源站点:**\n${storeName}` } }, { is_short: true, text: { tag: "lark_md", content: `**订单总额:**\n${totalPrice} ${currency}` } }, { is_short: true, text: { tag: "lark_md", content: `**购买客户:**\n${customerName}` } }, { is_short: true, text: { tag: "lark_md", content: `**购买频次:**\n${orderCountText}` } }, { is_short: true, text: { tag: "lark_md", content: `**目的国家:**\n${country}` } }, { is_short: true, text: { tag: "lark_md", content: `**客户邮箱:**\n${customerEmail}` } }, { is_short: true, text: { tag: "lark_md", content: `**折扣优惠:**\n${discountText}` } }, { is_short: true, text: { tag: "lark_md", content: `**配送运费:**\n${shippingText}` } } ] } ] } ] }, { tag: "hr" }, { tag: "div", text: { tag: "lark_md", content: `**📦 商品清单:**\n${lineItemsText}` } }, ...(order.note ? [{ tag: "hr" }, { tag: "note", elements: [{ tag: "plain_text", content: `💬 客户备注: ${order.note}` }] }] : []) ] } };
const targetWebhookUrl = currentStore.feishu_webhook || env.FEISHU_WEBHOOK_URL; if (!targetWebhookUrl) { console.error('未配置飞书 Webhook 链接'); return new Response('Configuration Error', { status: 500 }); }
const feishuResponse = await fetch(targetWebhookUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(feishuPayload) });
if (!feishuResponse.ok) { console.error('Feishu Push Failed:', await feishuResponse.text()); }
return new Response('OK', { status: 200 });
} catch (error) { console.error('Logic Error:', error); return new Response('Bad Request', { status: 400 }); } } };
|