بکاند آماده فروشگاه اینترنتی
کاتالوگ با تنوع کالا، سبد، نشانی، روش ارسال، کد تخفیف، نظر خریدار و تنظیمات فروشگاه؛ سفارش فقط از راه فانکشن امن checkout ثبت میشود و پرداختش با زرینپال است — بکاند کامل یک فروشگاه، بیآنکه چیزی به آن اضافه کنید.
۱۵ روز اول رایگانبا پلنکاپوچینو
اعتبار هدیهٔ ثبتنام هزینهاش را میدهد؛ لازم نیست حتی یک تومان پرداخت کنید.
مناسب برای
- فروشگاه اینترنتی با اپ یا سایت اختصاصی خودتان
- اپ موبایل فروشگاهی (Flutter / Kotlin / Swift / React Native)
- فروش کالای دارای رنگ و سایز، با کد تخفیف و پرداخت آنلاین
همان لحظهٔ ساخت، اینها در جدول هستند
/v1/product- لیوان سرامیکی دستساز شیراز۲۸۵٬۰۰۰ تومان
- کاسهٔ مینای اصفهان۱٬۴۵۰٬۰۰۰ تومان
- تختهٔ سرو چوب گردو۶۲۰٬۰۰۰ تومان
۱۱ جدولورود کاربران۱۱ قانون۴ فانکشن۲۴ ردیف نمونه
با این قالب چه میشود ساخت
کارهایی که اپ یا سایت شما از روز اول روی همین بکاند انجام میدهد.
خواندن کاتالوگ با کلید عمومی
محصول، دستهبندی، تنوع، روش ارسال، نظرها و تنظیمات فروشگاه عمومیاند؛ اپ قبل از ورود کاربر نشانشان میدهد. include=variants تنوعهای هر محصول را هم میآورد و قیمت خرید هیچوقت در پاسخ نیست.
GET /v1/productثبتنام خریدار
خریدار با ایمیل و رمز ثبتنام میکند؛ از این به بعد سبد، نشانی و سفارشهایش فقط برای خودش است.
POST /v1/auth/signupافزودن به سبد
product_id، در صورت نیاز variant_id، و quantity را بفرستید؛ customer_id خودکار پر میشود. قیمت در سبد نیست — checkout آن را از خود محصول میخواند.
POST /v1/cart_itemثبت نشانی تحویل
گیرنده، موبایل، استان، شهر، کد پستی و نشانی؛ هر خریدار فقط نشانیهای خودش را میبیند.
POST /v1/addressثبت سفارش
با address_id و shipping_method_id (و در صورت نیاز coupon_code و notes) فانکشن checkout را صدا بزنید. سبد به سفارش «در انتظار پرداخت» تبدیل میشود، موجودی کم و سبد خالی میشود. POST مستقیم به /v1/order برای خریدار بسته است.
POST /v1/fn/checkoutشروع پرداخت
با order_id و callback_url فانکشن pay_start را صدا بزنید و کاربر را به payment_url بفرستید. پیش از آن مرچنتکد زرینپال را با نام ZARINPAL_MERCHANT_ID در secrets پروژه بگذارید.
POST /v1/fn/pay_startتأیید پرداخت
صفحهٔ بازگشت، order_id و Authority و Status را از نشانی برمیدارد و به pay_verify میفرستد؛ سفارش «پرداختشده» میشود و ایمیل تأیید برای خریدار میرود. صدا زدن دوبارهاش بیخطر است.
POST /v1/fn/pay_verifyلغو سفارش پرداختنشده
خریدار با order_id فانکشن cancel_order را صدا میزند؛ سفارش «لغوشده» میشود، موجودی برمیگردد و کد تخفیفش آزاد میشود. سفارش پرداختشده را فقط فروشگاه لغو میکند.
POST /v1/fn/cancel_orderارسال سفارش از طرف فروشگاه
با توکن کاربر مدیر یا کلید Production، status را shipped و tracking_code را بفرستید؛ بدون کد رهگیری رد میشود و سفارش پرداختنشده تحویلشده نمیشود.
PATCH /v1/order/{id}نوشتن نظر
خریدار واردشده product_id، rating (۱ تا ۵) و comment را میفرستد؛ همه نظرها را میخوانند.
POST /v1/review
دادهای که همان لحظه دارید
این ردیفها با ساخت پروژه در جدولها هستند. رکورد معمولیاند و هر وقت خواستید از پنل ویرایش یا پاکشان میکنید.
دستهبندی
۳ ردیف/v1/category| نام | نشانی | ترتیب نمایش |
|---|---|---|
| لوازم آشپزخانه | kitchen | ۱ |
| دکوری و تزئینی | decor | ۲ |
| پوشاک | apparel | ۳ |
محصول
۶ ردیف/v1/product| نام | قیمت (تومان) | قیمت پیش از تخفیف (تومان) | وضعیت |
|---|---|---|---|
| لیوان سرامیکی دستساز شیراز | ۲۸۵٬۰۰۰ | ۳۲۰٬۰۰۰ | فعال |
| کاسهٔ مینای اصفهان | ۱٬۴۵۰٬۰۰۰ | — | فعال |
| تختهٔ سرو چوب گردو | ۶۲۰٬۰۰۰ | — | فعال |
و ۳ ردیف دیگر
تنوع محصول
۳ ردیف/v1/product_variant| عنوان | قیمت جایگزین (تومان) | کد کالا (SKU) | موجودی |
|---|---|---|---|
| فیروزهای / M | — | APP-TEE-01-TQ-M | ۸ |
| فیروزهای / L | — | APP-TEE-01-TQ-L | ۶ |
| سرمهای / XL | ۴۲۰٬۰۰۰ | APP-TEE-01-NV-XL | ۴ |
سبد خرید
۱ ردیف/v1/cart_item| تعداد |
|---|
| ۱ |
نشانی
۱ ردیف/v1/address| نشانی | نام گیرنده | استان | شهر |
|---|---|---|---|
| خیابان ولیعصر، کوچهٔ بهار، پلاک ۱۲، واحد ۳ | مریم احمدی | تهران | تهران |
روش ارسال
۲ ردیف/v1/shipping_method| نام | هزینه (تومان) | ارسال رایگان از (تومان) | زمان تحویل |
|---|---|---|---|
| پست پیشتاز | ۶۵٬۰۰۰ | ۲٬۰۰۰٬۰۰۰ | ۲ تا ۴ روز کاری |
| پیک تهران | ۱۲۰٬۰۰۰ | ۰ | همان روز، فقط تهران |
کد تخفیف
۱ ردیف/v1/coupon| عنوان | مقدار (درصد یا تومان) | حداقل خرید (تومان) | نوع |
|---|---|---|---|
| ۱۰٪ تخفیف پاییزه | ۱۰ | ۵۰۰٬۰۰۰ | درصدی |
سفارش
۱ ردیف/v1/order| شمارهٔ سفارش | مبلغ کالاها (تومان) | تخفیف (تومان) | هزینهٔ ارسال (تومان) |
|---|---|---|---|
| FK-DEMO-0001 | ۱٬۷۳۵٬۰۰۰ | ۰ | ۶۵٬۰۰۰ |
سطر سفارش
۲ ردیف/v1/order_item| عنوان | قیمت واحد هنگام خرید (تومان) | تعداد |
|---|---|---|
| لیوان سرامیکی دستساز شیراز | ۲۸۵٬۰۰۰ | ۱ |
| کاسهٔ مینای اصفهان | ۱٬۴۵۰٬۰۰۰ | ۱ |
نظر خریدار
۳ ردیف/v1/review| نظر | امتیاز (۱ تا ۵) |
|---|---|
| لعابش دقیقاً مثل عکس است و دستهٔ خوشدستی دارد. بستهبندی هم خیلی محکم بود. | ۵ |
| کار دست و ظریف است؛ فقط کمی کوچکتر از چیزی بود که فکر میکردم. | ۴ |
| چوبش سنگین و خوشرنگ است و بعد از چند بار شستن هم تاب برنداشت. | ۵ |
تنظیمات فروشگاه
۱ ردیف/v1/store_settings| نام فروشگاه | تلفن | نشانی | اینستاگرام |
|---|---|---|---|
| سفال و هنر پارسی | 021-88001234 | تهران، خیابان انقلاب، نبش خیابان فلسطین، پلاک ۱۲۰ | parsi.crafts |
جدولها و دسترسی
هر جدول یک مسیر API دارد و از قبل مشخص است چه کسی میخواندش. فیلدهای هر جدول زیر همان جدول باز میشوند.
دستهبندی
/v1/categoryعمومی: هر کسی میخواندش، حتی بدون ورود و با کلید عمومی داخل اپ.
دستهبندی محصولات — عمومی، برای منوی اپ
۳ فیلدو ۱ رابطه
nameناممتنضروریslugنشانیمتنضروریsort_orderترتیب نمایشعدد= 0
- رابطه با محصولیک به چند
category_id
محصول
/v1/productعمومی: هر کسی میخواندش، حتی بدون ورود و با کلید عمومی داخل اپ.
محصولات فروشگاه — عمومی، همان چیزی که اپ قبل از ورود کاربر نشان میدهد
۱۲ فیلدو ۳ رابطه
nameناممتنضروریقابل جستجوslugنشانیمتنضروریdescriptionتوضیحاتمتنimageتصویر اصلیفایلgalleryگالری تصاویرJSONpriceقیمت (تومان)عددضروریcompare_at_priceقیمت پیش از تخفیف (تومان)عددstockموجودیعدد= 0skuکد کالا (SKU)متنstatusوضعیتگزینهای= "active"category_idدستهبندیمتنcost_priceقیمت خریدعددفقط مدیر
- رابطه با دستهبندیچند به یک
category_id - رابطه با تنوع محصولیک به چند
product_id - رابطه با نظر خریداریک به چند
product_id
تنوع محصول
/v1/product_variantعمومی: هر کسی میخواندش، حتی بدون ورود و با کلید عمومی داخل اپ.
رنگ، سایز یا هر ترکیب دیگری از یک محصول، با موجودی خودش — عمومی
۵ فیلدو ۱ رابطه
product_idمحصولمتنضروریtitleعنوانمتنضروریpriceقیمت جایگزین (تومان)عددstockموجودیعدد= 0skuکد کالا (SKU)متن
- رابطه با محصولچند به یک
product_id
سبد خرید
/v1/cart_itemفقط صاحب ردیف: هر کاربر فقط ردیفهای خودش را میبیند. مالکیت از روی
customer_idسطرهای سبد هر خریدار — فقط خودش میبیند و مینویسد
۴ فیلدو ۳ رابطه
customer_idخریدارمتنproduct_idمحصولمتنضروریvariant_idتنوعمتنquantityتعدادعددضروری
- رابطه با کاربرچند به یک
customer_id - رابطه با محصولچند به یک
product_id - رابطه با تنوع محصولچند به یک
variant_id
نشانی
/v1/addressفقط صاحب ردیف: هر کاربر فقط ردیفهای خودش را میبیند. مالکیت از روی
customer_idنشانیهای تحویل هر خریدار — فقط خودش میبیند
۸ فیلدو ۱ رابطه
customer_idخریدارمتنrecipientنام گیرندهمتنضروریmobileموبایل گیرندهتلفنضروریprovinceاستانمتنضروریcityشهرمتنضروریpostal_codeکد پستیمتنlineنشانیمتنضروریis_defaultنشانی پیشفرضبله/خیر= false
- رابطه با کاربرچند به یک
customer_id
روش ارسال
/v1/shipping_methodعمومی: هر کسی میخواندش، حتی بدون ورود و با کلید عمومی داخل اپ.
روشهای ارسال و هزینهشان — عمومی
۵ فیلد
nameناممتنضروریcostهزینه (تومان)عددضروریfree_overارسال رایگان از (تومان)عدد= 0estimateزمان تحویلمتنactiveفعالبله/خیر= true
کد تخفیف
/v1/couponکاربران واردشده: هر کاربری که وارد شده باشد همه را میبیند.
کدهای تخفیف — کاربر واردشده شرطها را میبیند، خود کد را هیچوقت
۹ فیلد
titleعنوانمتنضروریcodeکدمتنضروریفقط مدیرkindنوعگزینهای= "percent"valueمقدار (درصد یا تومان)عددضروریmin_orderحداقل خرید (تومان)عدد= 0expires_atتاریخ انقضاتاریخusage_limitسقف دفعات استفادهعدد= 0used_countدفعات استفادهشدهعدد= 0activeفعالبله/خیر= true
سفارش
/v1/orderفقط صاحب ردیف: هر کاربر فقط ردیفهای خودش را میبیند. مالکیت از روی
customer_idسفارشها — فقط checkout میسازد؛ خریدار فقط سفارش خودش را میبیند و جز یادداشت چیزی رویش نمینویسد
۲۰ فیلدو ۳ رابطه
order_numberشمارهٔ سفارشمتنcustomer_idخریدارمتنstatusوضعیتگزینهای= "pending"subtotalمبلغ کالاها (تومان)عددضروریdiscountتخفیف (تومان)عدد= 0shipping_costهزینهٔ ارسال (تومان)عدد= 0totalمبلغ کل (تومان)عددضروریcoupon_codeکد تخفیفمتنshipping_method_idروش ارسالمتنrecipientگیرندهمتنmobileموبایل گیرندهتلفنprovinceاستانمتنcityشهرمتنpostal_codeکد پستیمتنaddress_lineنشانی تحویلمتنtracking_codeکد رهگیری مرسولهمتنpaid_atزمان پرداختتاریخpayment_authorityAuthority زرینپالمتنفقط مدیرpayment_refکد پیگیری پرداختمتنnotesیادداشت خریدارمتن
- رابطه با کاربرچند به یک
customer_id - رابطه با روش ارسالچند به یک
shipping_method_id - رابطه با سطر سفارشیک به چند
order_id
سطر سفارش
/v1/order_itemفقط صاحب ردیف: هر کاربر فقط ردیفهای خودش را میبیند. مالکیت از روی
customer_idسطرهای هر سفارش — فقط سرور مینویسد، قیمت لحظهٔ خرید در خودش میماند
۷ فیلدو ۳ رابطه
customer_idخریدارمتنorder_idسفارشمتنضروریproduct_idمحصولمتنضروریvariant_idتنوعمتنtitleعنوانمتنquantityتعدادعددضروریprice_at_purchaseقیمت واحد هنگام خرید (تومان)عددضروری
- رابطه با سفارشچند به یک
order_id - رابطه با محصولچند به یک
product_id - رابطه با تنوع محصولچند به یک
variant_id
نظر خریدار
/v1/reviewعمومی: هر کسی میخواندش، حتی بدون ورود و با کلید عمومی داخل اپ.
امتیاز و نظر خریداران — همه میخوانند، هر کس فقط نظر خودش را مینویسد
۴ فیلدو ۲ رابطه
customer_idنویسندهمتنproduct_idمحصولمتنضروریratingامتیاز (۱ تا ۵)عددضروریcommentنظرمتن
- رابطه با محصولچند به یک
product_id - رابطه با کاربرچند به یک
customer_id
تنظیمات فروشگاه
/v1/store_settingsعمومی: هر کسی میخواندش، حتی بدون ورود و با کلید عمومی داخل اپ.
یک ردیف: نام، لوگو، تماس و متنهای ثابت فروشگاه — عمومی، برای سربرگ و پانویس اپ
۱۰ فیلد
store_nameنام فروشگاهمتنضروریlogoلوگوفایلphoneتلفنمتنemailایمیلایمیلaddressنشانیمتنinstagramاینستاگراممتنtelegramتلگراممتنaboutدربارهٔ فروشگاهمتنreturn_policyقوانین مرجوعیمتنshipping_infoتوضیح ارسالمتن
قوانین آماده
منطقی که همراه قالب نصب میشود و از لحظهٔ ساخت فعال است، بدون اینکه یک خط کد بنویسید.
کاهش موجودی محصول هنگام ثبت سطر سفارش
تریگرروی سطر سفارشکاهش موجودی تنوع هنگام ثبت سطر سفارش
تریگرروی سطر سفارشثبت زمان پرداخت
تریگرروی سفارشالزام کد رهگیری برای ارسالشده
اعتبارسنجیروی سفارشپیامی که کاربر میگیرد: «برای وضعیت ارسالشده، کد رهگیری مرسوله الزامی است»
جلوگیری از تحویل سفارش پرداختنشده
اعتبارسنجیروی سفارشپیامی که کاربر میگیرد: «سفارش پرداختنشده را نمیتوان تحویلشده علامت زد»
امتیاز نظر بین ۱ و ۵
اعتبارسنجیروی نظر خریدارپیامی که کاربر میگیرد: «امتیاز باید عدد صحیحی بین ۱ و ۵ باشد»
امتیاز نظر بین ۱ و ۵ (ویرایش)
اعتبارسنجیروی نظر خریدارپیامی که کاربر میگیرد: «امتیاز باید عدد صحیحی بین ۱ و ۵ باشد»
ایمیل پرداخت سفارش
تریگرروی سفارشایمیل ارسال سفارش
تریگرروی سفارشایمیل تحویل سفارش
تریگرروی سفارشایمیل لغو سفارش
تریگرروی سفارش
فانکشنهای آماده
منطقی که نباید دست اپ باشد همراه قالب نصب میشود و از لحظهٔ ساخت روشن است. هر فانکشن یک آدرس دارد که اپ یا سرور شما صدایش میزند، و از سهمیهٔ فانکشن پلن حساب میشود.
ثبت سفارش
POST /v1/fn/checkoutسبد خودِ خریدار را به سفارش تبدیل میکند: قیمت هر قلم را از محصول یا تنوعش، تخفیف را از کد تخفیف و هزینهٔ ارسال را از روش ارسال میخواند، موجودی را میسنجد، نشانی را در سفارش کپی میکند و سبد را خالی میکند. ورودی: address_id، shipping_method_id و در صورت نیاز coupon_code و notes.
کاربران واردشده: کاربری که در اپ وارد شده صدایش میزند؛ سرور شما هم با کلید API.
کد فانکشن
// Checkout: the only way an order comes into being. // // Everything that decides money is read here, on the server: each line's // price from the product (or its variant), the discount from the coupon // table, the shipping cost from the shipping method. The request names // only WHICH address, WHICH method and WHICH code — never an amount. // // Ownership is checked by hand, not left to the handle: a shop admin's // own handle reads every buyer's rows, and checkout must still only ever // turn the CALLER's cart into the CALLER's order. // // Budget: a function has 25 database calls. Six reads, one order, one // line per cart row, one status flip, one coupon update and one delete // per cart row — with the cap of 8 rows, 6 + 1 + 8 + 1 + 1 + 8 = 25. // // NOT atomic: every write is its own transaction. Every check runs before // the first write, so a bad request writes nothing. The writes are ordered // so that a failure half-way hurts least: // 1. the order is created «placing» — visible, but pay_start refuses it; // 2. its lines (each one lowers stock through the template's rules); // 3. the order flips to «pending», and only now can it be paid; // 4. the coupon's used_count goes up; // 5. the cart is emptied. // A failure in 1–3 leaves a «placing» order the shop cancels (restoring the // stock its written lines took) and a cart the buyer can check out again; // a failure in 4–5 leaves a valid order and, at worst, an under-counted // coupon or a cart the buyer clears by hand. Two buyers racing for the // last unit can both pass the stock check; the shop sees a negative stock. const MAX_LINES = 8; const TITLE_MAX = 200; // order_item.title's max function fail(status, code, message) { throw {status: status, code: code, message: message}; } // A row that is not there is null; any other refusal (the call budget, // authorization being unavailable) is not «not found» and goes up as is. function getOrNull(handle, entity, id) { try { return handle.get(entity, id); } catch (e) { if (e && e.status === 404) return null; throw e; } } function toman(n) { return String(Math.round(Number(n))).replace(/\B(?=(\d{3})+(?!\d))/g, ",") + " تومان"; } // An API key would read every buyer's cart; only a signed-in buyer checks out. if (ctx.auth !== "user" || !ctx.user.id) { fail(403, "login_required", "ثبت سفارش با توکن خریدارِ واردشده انجام میشود، نه با کلید API"); } const me = ctx.user.id; const body = ctx.request.body; const input = body && typeof body === "object" && !Array.isArray(body) ? body : {}; const addressId = typeof input.address_id === "string" ? input.address_id.trim() : ""; const methodId = typeof input.shipping_method_id === "string" ? input.shipping_method_id.trim() : ""; const couponCode = input.coupon_code == null ? "" : String(input.coupon_code).trim().toUpperCase(); const notes = input.notes == null ? "" : String(input.notes).trim(); if (!addressId) fail(400, "address_required", "نشانی تحویل را با address_id بفرستید"); if (!methodId) fail(400, "shipping_method_required", "روش ارسال را با shipping_method_id بفرستید"); if (notes.length > 500) fail(400, "notes_too_long", "یادداشت سفارش حداکثر ۵۰۰ نویسه است"); // ── reads ────────────────────────────────────────────────────────────── const cart = ctx.db.list("cart_item", {filter: {customer_id: me}, limit: MAX_LINES + 1}); if (cart.length === 0) fail(400, "cart_empty", "سبد خرید شما خالی است"); if (cart.length > MAX_LINES) { fail(400, "cart_too_large", "هر سفارش حداکثر ۸ قلم دارد؛ بقیه را در سفارش بعدی ثبت کنید"); } const address = getOrNull(ctx.db, "address", addressId); if (!address || address.customer_id !== me) { fail(404, "address_not_found", "این نشانی پیدا نشد یا مال شما نیست"); } const method = getOrNull(ctx.db, "shipping_method", methodId); if (!method || method.active === false) { fail(404, "shipping_method_not_found", "این روش ارسال پیدا نشد یا فعال نیست"); } const productIds = []; for (const item of cart) { if (productIds.indexOf(item.product_id) < 0) productIds.push(item.product_id); } const products = {}; const variants = {}; const hasVariants = {}; try { for (const p of ctx.db.list("product", {filter: {"id[in]": productIds}, limit: productIds.length})) { products[p.id] = p; } // Every variant of every product in the cart: the ones chosen, and // whether a line that chose none should have. for (const v of ctx.db.list("product_variant", {filter: {"product_id[in]": productIds}, limit: 500})) { variants[v.id] = v; hasVariants[v.product_id] = true; } } catch (e) { // A malformed id in the cart is the cart's fault; anything else is not. if (e && e.status === 400) { fail(409, "cart_item_invalid", "سبد شما کالایی دارد که دیگر وجود ندارد؛ آن را از سبد بردارید"); } throw e; } // ── prices and stock, all from the server's rows ─────────────────────── const takenProduct = {}; const takenVariant = {}; const lines = []; let subtotal = 0; for (const item of cart) { const quantity = Number(item.quantity); if (!Number.isInteger(quantity) || quantity < 1) { fail(400, "invalid_quantity", "تعداد هر قلم سبد باید عدد صحیح و دستکم ۱ باشد"); } const product = products[item.product_id]; if (!product) { fail(409, "product_unavailable", "سبد شما کالایی دارد که دیگر وجود ندارد؛ آن را از سبد بردارید"); } if (product.status !== "active") { fail(409, "product_unavailable", "«" + product.name + "» دیگر فروخته نمیشود؛ آن را از سبد بردارید"); } let price = Number(product.price); let title = product.name; let variantId = ""; if (item.variant_id) { const variant = variants[item.variant_id]; if (!variant || variant.product_id !== product.id) { fail(409, "variant_unavailable", "تنوع انتخابشده برای «" + product.name + "» دیگر وجود ندارد"); } if (typeof variant.price === "number") price = variant.price; title = product.name + " — " + variant.title; variantId = variant.id; takenVariant[variant.id] = (takenVariant[variant.id] || 0) + quantity; if (takenVariant[variant.id] > Number(variant.stock || 0)) { fail(409, "out_of_stock", "از «" + title + "» فقط " + Number(variant.stock || 0) + " عدد موجود است"); } } else if (hasVariants[product.id]) { // Bought without a variant, the product's stock would drift from the // sum of its variants' stock. fail(409, "variant_required", "برای «" + product.name + "» یکی از تنوعها (رنگ، سایز…) را انتخاب کنید"); } takenProduct[product.id] = (takenProduct[product.id] || 0) + quantity; if (takenProduct[product.id] > Number(product.stock || 0)) { fail(409, "out_of_stock", "از «" + product.name + "» فقط " + Number(product.stock || 0) + " عدد موجود است"); } subtotal += price * quantity; const line = {product_id: product.id, title: title.slice(0, TITLE_MAX), quantity: quantity, price_at_purchase: price}; if (variantId) line.variant_id = variantId; lines.push({line: line, cartId: item.id}); } // ── coupon (the code is admin-read: only this handle can match it) ───── let coupon = null; let discount = 0; if (couponCode) { const found = ctx.db.admin.list("coupon", {filter: {code: couponCode}, limit: 1}); coupon = found.length > 0 ? found[0] : null; if (!coupon || coupon.active === false) { fail(400, "coupon_invalid", "این کد تخفیف معتبر نیست"); } if (coupon.expires_at && new Date(coupon.expires_at).getTime() <= Date.now()) { fail(400, "coupon_expired", "مهلت استفاده از این کد تخفیف تمام شده است"); } const limit = Number(coupon.usage_limit || 0); if (limit > 0 && Number(coupon.used_count || 0) >= limit) { fail(400, "coupon_used_up", "ظرفیت استفاده از این کد تخفیف پر شده است"); } const minOrder = Number(coupon.min_order || 0); if (subtotal < minOrder) { fail(400, "coupon_min_order", "این کد تخفیف برای خرید از " + toman(minOrder) + " به بالاست"); } discount = coupon.kind === "percent" ? Math.floor(subtotal * Number(coupon.value) / 100) : Number(coupon.value); if (discount > subtotal) discount = subtotal; if (discount < 0) discount = 0; } // ── shipping: free once the goods (after discount) reach free_over ───── const goods = subtotal - discount; const freeOver = Number(method.free_over || 0); const shippingCost = freeOver > 0 && goods >= freeOver ? 0 : Number(method.cost || 0); const total = goods + shippingCost; // ── writes, in the order the header explains ─────────────────────────── // A readable, practically unique number: the millisecond in base 36 plus // two random characters. The field is unique, so a collision refuses the // order before anything else is written and the buyer simply retries. const suffix = ("0" + Math.floor(Math.random() * 1296).toString(36)).slice(-2); const order = { order_number: "FK-" + (Date.now().toString(36) + suffix).toUpperCase(), customer_id: me, status: "placing", subtotal: subtotal, discount: discount, shipping_cost: shippingCost, total: total, shipping_method_id: method.id, recipient: address.recipient, mobile: address.mobile, province: address.province, city: address.city, address_line: address.line, }; if (address.postal_code) order.postal_code = address.postal_code; if (coupon) order.coupon_code = coupon.code; if (notes) order.notes = notes; const created = ctx.db.admin.create("order", order); const items = []; for (const entry of lines) { const row = Object.assign({customer_id: me, order_id: created.id}, entry.line); items.push(ctx.db.admin.create("order_item", row)); } const placed = ctx.db.admin.update("order", created.id, {status: "pending"}); if (coupon) { ctx.db.admin.update("coupon", coupon.id, {used_count: Number(coupon.used_count || 0) + 1}); } for (const entry of lines) { ctx.db.delete("cart_item", entry.cartId); } delete placed.payment_authority; placed.items = items; ctx.respond(placed);شروع پرداخت
POST /v1/fn/pay_startبرای سفارش «در انتظار پرداخت» خودِ خریدار تراکنش زرینپال میسازد و نشانی درگاه را برمیگرداند. ورودی: order_id و callback_url (نشانی https صفحهٔ بازگشت اپ شما). شناسهٔ سفارش به callback_url اضافه میشود، پس صفحهٔ بازگشت order_id و Authority و Status را با هم دارد. سفارشی که قبلاً تراکنش گرفته همان نشانی درگاه را پس میگیرد، و سفارش صفرتومانی بیدرگاه پرداختشده میشود.
کاربران واردشده: کاربری که در اپ وارد شده صدایش میزند؛ سرور شما هم با کلید API.
مقدارهایی که از شما میخواهد:ZARINPAL_MERCHANT_IDمرچنتکد ۳۶ نویسهای درگاه زرینپال شما؛ از پنل زرینپال، بخش درگاهها.STORE_URLاختیاری: نشانی سایت یا اپ فروشگاه، مثل https://shop.example.com — اگر بگذارید، پرداخت فقط به صفحهای زیر همین نشانی برمیگردد.ZARINPAL_SANDBOXاختیاری: برای آزمایش بیهزینه 1 بگذارید تا پرداخت به درگاه آزمایشی زرینپال (sandbox) برود؛ پیش از فروش واقعی پاکش کنید.
کد فانکشن
// Starts a ZarinPal (v4) payment for one of the caller's own pending // orders. The amount is the order's own total, read here; the request // only says which order and where the gateway should send the buyer back. function fail(status, code, message) { throw {status: status, code: code, message: message}; } function getOrNull(handle, entity, id) { try { return handle.get(entity, id); } catch (e) { if (e && e.status === 404) return null; throw e; } } if (ctx.auth !== "user" || !ctx.user.id) { fail(403, "login_required", "پرداخت با توکن خریدارِ واردشده شروع میشود، نه با کلید API"); } const body = ctx.request.body; const input = body && typeof body === "object" && !Array.isArray(body) ? body : {}; const orderId = typeof input.order_id === "string" ? input.order_id.trim() : ""; const callback = typeof input.callback_url === "string" ? input.callback_url.trim() : ""; if (!orderId) fail(400, "order_required", "شناسهٔ سفارش را با order_id بفرستید"); // The admin handle is what reads the stored Authority; whose order it is // is checked by hand, for a shop admin's own handle would see them all. const order = getOrNull(ctx.db.admin, "order", orderId); if (!order || order.customer_id !== ctx.user.id) { fail(404, "order_not_found", "این سفارش پیدا نشد یا مال شما نیست"); } if (order.status !== "pending") { fail(409, "order_not_payable", "فقط سفارش «در انتظار پرداخت» پرداخت میشود"); } // A coupon can bring a total to zero, which no gateway takes — and which // needs no gateway, so it is settled before the merchant id is asked for. if (Number(order.total) <= 0) { ctx.db.admin.update("order", order.id, {status: "paid", paid_at: new Date().toISOString(), payment_ref: "FREE"}); ctx.respond({order_id: order.id, order_number: order.order_number, amount: 0, paid: true}); } const merchant = ctx.secrets.ZARINPAL_MERCHANT_ID; if (!merchant) { fail(400, "payment_not_configured", "درگاه پرداخت هنوز تنظیم نشده است: مرچنتکد زرینپال را با نام ZARINPAL_MERCHANT_ID در secrets پروژه بگذارید"); } const sandboxFlag = String(ctx.secrets.ZARINPAL_SANDBOX || "").trim(); const gateway = /^(1|true|yes)$/i.test(sandboxFlag) ? "sandbox.zarinpal.com" : "payment.zarinpal.com"; // https only: the gateway sends the buyer back to this page with the // payment's Authority in the query string. if (!/^https:[/][/][^/\s?#]+([/?#]\S*)?$/.test(callback)) { fail(400, "invalid_callback_url", "callback_url باید نشانی کامل https باشد، مثل https://shop.example.com/pay/return"); } const storeUrl = ctx.secrets.STORE_URL; if (storeUrl) { const base = String(storeUrl).trim().replace(/[/]+$/, ""); const rest = callback.slice(base.length); const under = callback.slice(0, base.length) === base && (rest === "" || rest.charAt(0) === "/" || rest.charAt(0) === "?" || rest.charAt(0) === "#"); if (!under) { fail(400, "invalid_callback_url", "callback_url باید زیر نشانی فروشگاه (STORE_URL) باشد"); } } // One order, one transaction. A second request would overwrite the // stored Authority, and a buyer who then paid through the FIRST link // would be refused by pay_verify with the money already taken. So an // order that has one gets the same gateway page back (and the buyer // returns to the callback given the first time). if (order.payment_authority) { ctx.respond({ order_id: order.id, order_number: order.order_number, amount: order.total, authority: order.payment_authority, payment_url: "https://" + gateway + "/pg/StartPay/" + order.payment_authority, }); } const sep = callback.indexOf("?") >= 0 ? "&" : "?"; let res = null; try { res = ctx.http.post("https://" + gateway + "/pg/v4/payment/request.json", { merchant_id: merchant, amount: Math.round(Number(order.total) * 10), // toman → rial callback_url: callback + sep + "order_id=" + encodeURIComponent(order.id), description: "پرداخت سفارش " + (order.order_number || order.id), metadata: {order_id: order.id}, }, {headers: {Accept: "application/json"}}); } catch (e) { ctx.respond(502, {code: "gateway_unreachable", detail: "درگاه زرینپال در دسترس نبود؛ چند لحظهٔ دیگر دوباره تلاش کنید"}); } const data = res.json && res.json.data && !Array.isArray(res.json.data) ? res.json.data : null; if (!data || data.code !== 100 || !data.authority) { const errors = res.json && res.json.errors && !Array.isArray(res.json.errors) ? res.json.errors : {}; ctx.respond(502, { code: "gateway_refused", detail: "زرینپال درخواست پرداخت را نپذیرفت (کد " + (errors.code || (data && data.code) || res.status) + ")؛ مرچنتکد و نشانی بازگشت را بررسی کنید", }); } ctx.db.admin.update("order", order.id, {payment_authority: data.authority}); ctx.respond({ order_id: order.id, order_number: order.order_number, amount: order.total, authority: data.authority, payment_url: "https://" + gateway + "/pg/StartPay/" + data.authority, });تأیید پرداخت
POST /v1/fn/pay_verifyصفحهٔ بازگشت اپ بعد از درگاه صدایش میزند: Authority را با تراکنش ذخیرهشدهٔ سفارش میسنجد، پرداخت را با مبلغ خود سفارش از زرینپال تأیید میگیرد و سفارش را «پرداختشده» میکند. ورودی: order_id، authority و در صورت وجود status (همان Status بازگشتی). صدا زدن دوبارهاش بیخطر است.
کاربران واردشده: کاربری که در اپ وارد شده صدایش میزند؛ سرور شما هم با کلید API.
مقدارهایی که از شما میخواهد:ZARINPAL_MERCHANT_IDمرچنتکد ۳۶ نویسهای درگاه زرینپال شما؛ همان که pay_start میخواند.ZARINPAL_SANDBOXاختیاری: همان مقدار pay_start؛ 1 یعنی تأیید از درگاه آزمایشی زرینپال (sandbox).
کد فانکشن
// Verifies a ZarinPal (v4) payment the gateway has just redirected back. // Idempotent: an order already paid is answered as it is, so a page that // reloads, or a buyer who presses back, never pays or fails twice. function fail(status, code, message) { throw {status: status, code: code, message: message}; } function getOrNull(handle, entity, id) { try { return handle.get(entity, id); } catch (e) { if (e && e.status === 404) return null; throw e; } } // The buyer's view of their order: the Authority stays server-side. function view(order) { delete order.payment_authority; return order; } if (ctx.auth !== "user" || !ctx.user.id) { fail(403, "login_required", "تأیید پرداخت با توکن خریدارِ واردشده انجام میشود، نه با کلید API"); } const body = ctx.request.body; const input = body && typeof body === "object" && !Array.isArray(body) ? body : {}; const orderId = typeof input.order_id === "string" ? input.order_id.trim() : ""; const authority = typeof input.authority === "string" ? input.authority.trim() : ""; if (!orderId) fail(400, "order_required", "شناسهٔ سفارش را با order_id بفرستید"); const order = getOrNull(ctx.db.admin, "order", orderId); if (!order || order.customer_id !== ctx.user.id) { fail(404, "order_not_found", "این سفارش پیدا نشد یا مال شما نیست"); } if (order.status === "paid" || order.status === "shipped" || order.status === "delivered") { ctx.respond(view(order)); } if (order.status !== "pending") { fail(409, "order_not_payable", "این سفارش در وضعیتی نیست که پرداختش تأیید شود؛ اگر مبلغی کم شده، طی ۷۲ ساعت به حساب برمیگردد"); } if (input.status === "NOK") { fail(400, "payment_cancelled", "پرداخت انجام نشد یا لغو شد؛ میتوانید دوباره پرداخت کنید"); } if (!authority || !order.payment_authority || authority !== order.payment_authority) { fail(400, "authority_mismatch", "این تراکنش با سفارش جور نیست؛ پرداخت را از نو شروع کنید"); } const merchant = ctx.secrets.ZARINPAL_MERCHANT_ID; if (!merchant) { fail(400, "payment_not_configured", "درگاه پرداخت هنوز تنظیم نشده است: مرچنتکد زرینپال را با نام ZARINPAL_MERCHANT_ID در secrets پروژه بگذارید"); } const sandboxFlag = String(ctx.secrets.ZARINPAL_SANDBOX || "").trim(); const gateway = /^(1|true|yes)$/i.test(sandboxFlag) ? "sandbox.zarinpal.com" : "payment.zarinpal.com"; let res = null; try { res = ctx.http.post("https://" + gateway + "/pg/v4/payment/verify.json", { merchant_id: merchant, amount: Math.round(Number(order.total) * 10), // toman → rial, as pay_start sent it authority: order.payment_authority, }, {headers: {Accept: "application/json"}}); } catch (e) { ctx.respond(502, {code: "gateway_unreachable", detail: "درگاه زرینپال در دسترس نبود؛ چند لحظهٔ دیگر دوباره تلاش کنید"}); } const data = res.json && res.json.data && !Array.isArray(res.json.data) ? res.json.data : null; // 100: verified now; 101: verified by an earlier call. if (!data || (data.code !== 100 && data.code !== 101)) { const errors = res.json && res.json.errors && !Array.isArray(res.json.errors) ? res.json.errors : {}; fail(402, "payment_not_verified", "زرینپال این پرداخت را تأیید نکرد (کد " + (errors.code || (data && data.code) || res.status) + ")؛ اگر مبلغی کم شده، طی ۷۲ ساعت به حساب برمیگردد"); } const paid = ctx.db.admin.update("order", order.id, { status: "paid", paid_at: new Date().toISOString(), payment_ref: String(data.ref_id || ""), }); ctx.respond(view(paid));لغو سفارش
POST /v1/fn/cancel_orderخریدار سفارش «در انتظار پرداخت» خودش را لغو میکند: سفارش «لغوشده» میشود، موجودی محصولها و تنوعهایش برمیگردد و کد تخفیفش دوباره قابل استفاده میشود. ورودی: order_id.
کاربران واردشده: کاربری که در اپ وارد شده صدایش میزند؛ سرور شما هم با کلید API.
کد فانکشن
// A pending order holds its stock and its coupon use until it is paid or // cancelled; this is how the buyer lets them go. // // NOT atomic. The status flips first, so from then on the order can be // neither paid (pay_start and pay_verify want «pending») nor cancelled // again by a later call. Then the stock and the coupon come back, each a // read-and-write of its own: a sale landing in between can be counted // over, and a failure half-way leaves a cancelled order whose remaining // stock the shop restores by hand. A buyer who pays an old gateway link // after cancelling is refused by pay_verify, and ZarinPal returns an // unverified payment by itself. const MAX_LINES = 8; // what checkout writes; more would overrun 25 calls function fail(status, code, message) { throw {status: status, code: code, message: message}; } function getOrNull(handle, entity, id) { try { return handle.get(entity, id); } catch (e) { if (e && e.status === 404) return null; throw e; } } if (ctx.auth !== "user" || !ctx.user.id) { fail(403, "login_required", "لغو سفارش با توکن خریدارِ واردشده انجام میشود، نه با کلید API"); } const body = ctx.request.body; const input = body && typeof body === "object" && !Array.isArray(body) ? body : {}; const orderId = typeof input.order_id === "string" ? input.order_id.trim() : ""; if (!orderId) fail(400, "order_required", "شناسهٔ سفارش را با order_id بفرستید"); const order = getOrNull(ctx.db.admin, "order", orderId); if (!order || order.customer_id !== ctx.user.id) { fail(404, "order_not_found", "این سفارش پیدا نشد یا مال شما نیست"); } if (order.status !== "pending") { fail(409, "order_not_cancellable", "فقط سفارش «در انتظار پرداخت» لغو میشود؛ برای سفارش پرداختشده با فروشگاه تماس بگیرید"); } const lines = ctx.db.admin.list("order_item", {filter: {order_id: order.id}, limit: MAX_LINES + 1}); if (lines.length > MAX_LINES) { fail(409, "order_too_large", "این سفارش بیش از ۸ قلم دارد و لغوش با فروشگاه است"); } const cancelled = ctx.db.admin.update("order", order.id, {status: "cancelled"}); const backProduct = {}; const backVariant = {}; for (const line of lines) { const q = Number(line.quantity || 0); backProduct[line.product_id] = (backProduct[line.product_id] || 0) + q; if (line.variant_id) backVariant[line.variant_id] = (backVariant[line.variant_id] || 0) + q; } const productIds = Object.keys(backProduct); if (productIds.length > 0) { for (const p of ctx.db.admin.list("product", {filter: {"id[in]": productIds}, limit: productIds.length})) { ctx.db.admin.update("product", p.id, {stock: Number(p.stock || 0) + backProduct[p.id]}); } } const variantIds = Object.keys(backVariant); if (variantIds.length > 0) { for (const v of ctx.db.admin.list("product_variant", {filter: {"id[in]": variantIds}, limit: variantIds.length})) { ctx.db.admin.update("product_variant", v.id, {stock: Number(v.stock || 0) + backVariant[v.id]}); } } if (order.coupon_code) { const found = ctx.db.admin.list("coupon", {filter: {code: order.coupon_code}, limit: 1}); if (found.length > 0 && Number(found[0].used_count || 0) > 0) { ctx.db.admin.update("coupon", found[0].id, {used_count: Number(found[0].used_count) - 1}); } } delete cancelled.payment_authority; ctx.respond(cancelled);
اولین درخواست
نمونهکدی که فقط نشانی پروژه و کلید شما را کم دارد. جای خالیها را بعد از ساخت پروژه، خود پنل پر میکند.
از کاتالوگ تا پرداخت
کاتالوگ عمومی است و با کلید عمومی و بدون ورود خوانده میشود. خرید از سبد خود خریدار شروع میشود و فقط از راه فانکشن checkout به سفارش میرسد؛ قیمت، تخفیف و هزینهٔ ارسال را سرور حساب میکند، نه اپ.
npm install @fikaro/clientimport { createClient } from "@fikaro/client";
const client = createClient({
project: "{{slug}}",
key: "{{publishable_key}}",
});
// ── صفحهٔ فروشگاه ─────────────────────────────────────────────
// ۱. کاتالوگ و روشهای ارسال — عمومی، بدون ورود
const { data: products } = await client.from("product").list({
filter: { status: "active" },
include: "variants",
sort: "-createdAt",
});
const { data: methods } = await client.from("shipping_method").list();
// ۲. خریدار ثبتنام میکند
await client.auth.signup("buyer@example.com", "a-strong-password");
// ۳. سبد و نشانی — هر دو فقط مال خود خریدارند. محصولی که تنوع دارد
// (رنگ، سایز) بدون variant_id فروخته نمیشود.
const product = products[0];
const variant = product.variants?.[0];
await client.from("cart_item").create({
product_id: product.id,
...(variant ? { variant_id: variant.id } : {}),
quantity: 1,
});
const address = await client.from("address").create({
recipient: "مریم احمدی",
mobile: "09121234567",
province: "تهران",
city: "تهران",
postal_code: "1416753955",
line: "خیابان ولیعصر، کوچهٔ بهار، پلاک ۱۲",
});
// ۴. ثبت سفارش — مبلغ را سرور حساب میکند. کد تخفیف اختیاری است:
// coupon_code: "PAEEZ10" برای خرید از ۵۰۰٬۰۰۰ تومان به بالا.
const order = await client.request("POST", "/fn/checkout", {
address_id: address.id,
shipping_method_id: methods[0].id,
});
// ۵. رفتن به درگاه زرینپال
const { payment_url } = await client.request("POST", "/fn/pay_start", {
order_id: order.id,
callback_url: "https://shop.example.com/pay/return",
});
window.location.href = payment_url;
// ── صفحهٔ بازگشت: /pay/return?order_id=…&Authority=…&Status=OK ──
// (صفحهای جدا؛ همان client، و خریدار هنوز وارد است)
const q = new URLSearchParams(window.location.search);
const paid = await client.request("POST", "/fn/pay_verify", {
order_id: q.get("order_id"),
authority: q.get("Authority"),
status: q.get("Status"),
});
// paid.status === "paid" و paid.order_number را به خریدار نشان دهید
کلید عمومی فقط موجودیتهای عمومی را میخواند و امن است که داخل اپ یا APK باشد؛ قیمت خرید محصول هرگز در پاسخش نمیآید. سبد، نشانی و سفارش «فقط مال خود کاربر» هستند، پس خریدار باید وارد شود. سفارش را مستقیم نمیشود ساخت یا وضعیت و مبلغش را عوض کرد — فقط checkout و کاربر مدیر. پرداخت تا وقتی ZARINPAL_MERCHANT_ID را در secrets پروژه نگذارید کار نمیکند. توجه: کلید خودِ پروژه همهچیز را میبیند — اگر از پنل تست میکنید دادهای میبینید که اپ شما نمیبیند.
از همین قالب شروع کنید؛ بکاندش با من.
۱۵ روز اول رایگانبا پلنکاپوچینو
اعتبار هدیهٔ ثبتنام هزینهاش را میدهد؛ لازم نیست حتی یک تومان پرداخت کنید.