หรืออธิบายโค้ด JavaScript: Storefront MCP Server + OpenAI Responses API

สิ่งนี้เหมาะสำหรับสิ่งที่ Shopify มือใหม่ต้องการเริ่มต้นใช้งานเซิร์ฟเวอร์ MCP หน้าร้านกับ OpenAI

📋ห้องนอน 1: การพึ่งพาอาศัยกัน

 npm install @shopify/storefront-mcp-server openai dotenv

สคริปต์ 2: สร้างไฟล์ .env

Create File .env ในโปรเจกต์ของคุณ:

 # ข้อมูลร้าน ShopifySHOPIFY_STORE_DOMAIN=your-store.myshopify.comSHOPIFY_STOREFRONT_ACCESS_TOKEN=your-storefront-access-token# OpenAI API KeyOPENAI_API_KEY=sk-your-openai-api-key

วัดอุณหภูมิ 3: อธิบายโค้ดพื้นฐาน

อธิบายที่ 1: การพิจารณาเบื้องต้น

// index.jsimport { StorefrontMCPServer } from '@shopify/storefront-mcp-server';import OpenAI from 'openai';import dotenv from 'dotenv';// โหลด environment variablesdotenv.config();// สร้าง instance ของ Storefront MCP Serverconst mcpServer = new StorefrontMCPServer({ storeDomain: process.env.SHOPIFY_STORE_DOMAIN, storefrontAccessToken: process.env.SHOPIFY_STOREFRONT_ACCESS_TOKEN});// สร้าง instance ของ OpenAIconst openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY});console.log('✅ เชื่อมต่อสำเร็จ!');

อธิบายที่ 2: ค้นหาสินค้า

// searchProducts.jsasync function searchProducts(query) { try { const response = await mcpServer.searchProducts({ query: query, first: 10 // จำนวนสินค้าที่ต้องการ }); console.log('พบสินค้า:', response.products.edges.length, 'รายการ'); response.products.edges.forEach(({ node }) => { console.log('- ', node.title, ':', node.priceRange.minVariantPrice.amount, 'บาท'); }); return response.products; } catch (error) { console.error('เกิดข้อผิดพลาด:', error.message); }} // ทดสอบค้นหาสินค้าsearchProducts('เสื้อยืด');

อธิบายที่ 3:เพิ่มสินค้าลงตะกร้า

// addToCart.jsasync function addToCart(variantId, quantity = 1) { try { const cart = await mcpServer.cartCreate({ lines: [ { merchandiseId: variantId, quantity: quantity } ] }); console.log('✅ เพิ่มสินค้าลงตะกร้าสำเร็จ!'); console.log('Cart ID:', cart.id); console.log('จำนวนสินค้าในตะกร้า:', cart.lines.edges.length); return cart; } catch (error) { console.error('เกิดข้อผิดพลาด:', error.message); }} // ตัวอย่างการใช้งานconst variantId = 'gid://shopify/ProductVariant/123456789';addToCart(variantId, 2);

อธิบายที่ 4: สร้างลิงก์การชำระเงิน

// createCheckout.jsasync function createCheckoutLink(cartId) { try { const cart = await mcpServer.cartQuery({ id: cartId }); const checkoutUrl = cart.checkoutUrl; console.log('✅ สร้างลิงก์ชำระเงินสำเร็จ!'); console.log('URL:', checkoutUrl); return checkoutUrl; } catch (error) { console.error('เกิดข้อผิดพลาด:', error.message); }} // ตัวอย่างการใช้งานconst cartId = 'gid://shopify/Cart/abc123';createCheckoutLink(cartId);

อธิบายที่ 5: สร้าง AI Chatbot แบบง่าย

// chatbot.jsasync function createAIChatbot() {  const assistant = await openai.beta.assistants.create({    name: 'Shopify Shopping Assistant',    instructions: 'คุณคือผู้ช่วยช็อปปิ้งที่ช่วยลูกค้าค้นหาสินค้า เพิ่มลงตะกร้า และชำระเงิน',    model: 'gpt-4-turbo-preview',    tools: [      {        type: 'function',        function: {          name: 'search_products',          description: 'ค้นหาสินค้าในร้าน',          parameters: {            type: 'object',            properties: {              query: {                type: 'string',                description: 'คำค้นหา'              }            },            required: ['query']          }        }      }    ]  });  console.log('✅ สร้าง AI Assistant สำเร็จ!');  console.log('Assistant ID:', assistant.id);  return assistant;}createAIChatbot();

อธิบายที่ 6: ระบบสมบูรณ์ (ตัวอย่างเต็ม)

// app.js - ตัวอย่างแอปพลิเคชันแบบสมบูรณ์import { StorefrontMCPServer } from '@shopify/storefront-mcp-server';import OpenAI from 'openai';import dotenv from 'dotenv';dotenv.config();class ShopifyAIAssistant {  constructor() {    this.mcpServer = new StorefrontMCPServer({      storeDomain: process.env.SHOPIFY_STORE_DOMAIN,      storefrontAccessToken: process.env.SHOPIFY_STOREFRONT_ACCESS_TOKEN    });    this.openai = new OpenAI({      apiKey: process.env.OPENAI_API_KEY    });  }  async searchProducts(query) {    const response = await this.mcpServer.searchProducts({      query: query,      first: 5    });    return response.products.edges.map(({ node }) => ({      id: node.id,      title: node.title,      price: node.priceRange.minVariantPrice.amount,      image: node.images.edges[0]?.node.url    }));  }  async addToCart(variantId, quantity = 1) {    const cart = await this.mcpServer.cartCreate({      lines: [{ merchandiseId: variantId, quantity }]    });    return cart;  }  async chat(userMessage) {    const completion = await this.openai.chat.completions.create({      model: 'gpt-4-turbo-preview',      messages: [        {          role: 'system',          content: 'คุณคือผู้ช่วยช็อปปิ้งที่เป็นมิตร ช่วยลูกค้าค้นหาและซื้อสินค้า'        },        {          role: 'user',          content: userMessage        }      ]    });    return completion.choices[0].message.content;  }}// ตัวอย่างการใช้งานasync function main() {  const assistant = new ShopifyAIAssistant();  // ค้นหาสินค้า  console.log('🔍 กำลังค้นหาสินค้า...');  const products = await assistant.searchProducts('เสื้อยืด');  console.log('พบสินค้า:', products.length, 'รายการ');  // สนทนากับ AI  console.log('\n💬 สนทนากับ AI...');  const response = await assistant.chat('แนะนำเสื้อยืดสีขาวหน่อย');  console.log('AI:', response);}main().catch(console.error);

🎯 คำแนะนำสำหรับผู้เริ่มต้น

1. กรณีที่เกิดข้อผิดพลาด

 // ใช้ try-catch เสมอtry { const result = await mcpServer.searchProducts({ query: 'test' });} catch (error) { if (error.response) { console.error('API Error:', error.response.data); } else { console.error('Network Error:', error.message); }}

2. เลย

 // ทดสอบการเชื่อมต่อก่อนใช้งานจริงasync function testConnection() { try { const shop = await mcpServer.getShop(); console.log('✅ เชื่อมต่อร้าน:', shop.name); return true; } catch (error) { console.error('❌ เชื่อมต่อไม่สำเร็จ:', error.message); return false; }} testConnection();

3. ตัวแปรสภาพแวดล้อมอย่างปลอดภัย

// ตรวจสอบว่ามี environment variables ครบconst requiredEnvVars = [ 'SHOPIFY_STORE_DOMAIN', 'SHOPIFY_STOREFRONT_ACCESS_TOKEN', 'OPENAI_API_KEY'];requiredEnvVars.forEach(varName => { if (!process.env[varName]) { throw new Error(`Missing required environment variable: ${varName}`); }} );

📚ถัดไปถัดไป

  • ทดลองรันโค้ดตัวอย่างทีละตัว
  • ปรับแต่งให้เหมาะกับร้านของคุณ
  • เราจะพยายามอย่างเต็มที่
  • ทดสอบกับข้อมูลจริง
  • ปรับใช้การผลิต

🆘 แหล่งความช่วยเหลือ

💡 หลักปฏิบัติ: ตัวอย่างง่ายๆ และจากนั้นก็เพิ่มความเข้าใจในการทำงานแล้ว