ربط زاتكا بـ Node.js
طلب HTTP واحد من Node.js (fetch + pg): ماثل يبني الفاتورة ويوقّعها ويرسلها للهيئة، ويرجّع رد الهيئة والـ XML القانوني والـ PDF مع رمز QR.
١. جرّبه الحين (بدون مفتاح)
// npm i matheel
import { Matheel } from "matheel";
const matheel = new Matheel(process.env.MATHEEL_KEY); // the sandbox needs no key
const res = await matheel.fileInvoice({ environment: "sandbox", pdf: true,
invoice: { type: "simplified", line_items: [{ name: "قهوة", quantity: 2, price: "50.00" }] } });
console.log(res.status); // "reported", plus res.qr, res.pdf, res.invoice_xml
// After a payment: matheel.fileWithStore(store, invoice) keeps the device chain for you
٢. الدالة الجاهزة بعد الدفع
تقفل صف الجهاز (عشان دفعتين بنفس اللحظة ما يكسرون السلسلة)، ترسل الفاتورة مع "pdf": true، وتحفظ device_token الجديد. أي رد غير 200 يرجّع الـ transaction والمفتاح القديم يظل صالح.
// pg (node-postgres). Same flow in any DB: lock the device row, file, save the new token, commit.
export async function matheelInvoice(pool, items) {
const db = await pool.connect();
try {
await db.query("BEGIN");
const { rows } = await db.query("SELECT token FROM matheel_device WHERE id = 1 FOR UPDATE");
const r = await fetch("https://matheel.app/api/v1/invoices", {
method: "POST",
headers: { "Content-Type": "application/json", Authorization: `Bearer ${process.env.MATHEEL_KEY}` },
body: JSON.stringify({ device_token: rows[0].token, pdf: true, invoice: { type: "simplified", line_items: items } }),
});
const res = await r.json();
if (r.status !== 200) throw new Error(JSON.stringify(res));
await db.query("UPDATE matheel_device SET token = $1 WHERE id = 1", [res.device_token]);
await db.query("COMMIT");
return res; // Buffer.from(res.pdf, "base64") is the PDF
} catch (e) { await db.query("ROLLBACK"); throw e; } finally { db.release(); }
}
أو بمكتبة ماثل الرسمية: npm i matheel، وfileWithStore تسوي نفس الشي: تقرأ المفتاح وتحفظه في متجرك، وتعيد المحاولة لحالها لو رجع 409.
٣. للإنتاج
- سجّل جهازك مرة (مفتاح الجهاز أو لينك التفعيل) وحط
device_tokenفي جدولmatheel_device. - لو المبلغ اللي معك شامل الضريبة، أرسل
"prices_include_vat": true. - احفظ
invoice_xml(القانوني) وpdfمع الطلب، والتطبيق يعرض الـ PDF من سيرفرك.
أسئلة شائعة
أحتاج مكتبة Node.js خاصة بزاتكا؟
لا. ماثل API عادي بـ JSON: طلب HTTP واحد. التوقيع والـ XML والشهادة والإرسال للهيئة كلها عند ماثل. وفيه مكتبة رسمية لو تبيها: npm i matheel
وين أحفظ مفتاح الجهاز؟
صف واحد في قاعدة بياناتك (جدول matheel_device). بعد كل رد 200 احفظ device_token الجديد في نفس الـ transaction.
أجرّب قبل الاشتراك؟
إيه، على بيئة المطورين بدون مفتاح: الطلب تحت يرجّع رد الهيئة الحقيقي والـ PDF.