חשבונית מס מקוד PHP, בלי להתקין ספרייה
ל-BillOS אין ספריית PHP, וה-API לא צריך אחת: הוא JSON מעל HTTPS עם כותרת אחת. כאן הקוד המלא, פונקציה אחת מעל curl, שמפיק חשבונית מס קבלה ממוספרת מ-Laravel, מ-WordPress או מקובץ PHP בודד.
מה צריך
PHP 8.1 ומעלה עם הרחבת curl, ומפתח Sandbox. את המפתח מבקשים בפקודה אחת ומאשרים בדפדפן, או יוצרים באזור המפתחים בחשבון BillOS. הוא בחינם, בלי כרטיס אשראי.
# prints a link; approve it in the browser
npx billos sandbox
export BILLOS_API_KEY=bk_test_...
php -S localhost:3000 index.phpהדוגמה היא שני קבצים: billos.php, הלקוח, ו-index.php, שרת קטן עם נתיב לכל פעולה. הקוד בעמוד הזה נקרא מהקבצים עצמם, והם רצים בבדיקה אוטומטית: הפקה, שליחה חוזרת, קבלה, זיכוי ו-webhook.
הלקוח: פונקציה אחת
כל קריאה ל-API נראית אותו דבר: המפתח בכותרת X-Api-Key, גוף ב-JSON, ותשובה ב-JSON. הפונקציה מחזירה את התשובה כמערך, וזורקת BillosError על כל תשובה שאינה 2xx.
/** What a BillOS refusal says beyond its message. Branch on $reason, never on the message. */
final class BillosError extends RuntimeException
{
public function __construct(
string $message,
public int $status, // the HTTP status; 0 when no answer arrived
public ?string $reason, // stable: validation, not_found, payments_mismatch, ...
public ?string $hint, // what to change
public ?string $param, // the field it is about, when there is one
public ?string $docUrl,
public bool $retryable, // whether sending the same call again can succeed
public ?string $requestId, // quote it when you write to us
) {
parent::__construct($message);
}
}
/**
* One call to the API. $path starts after /v1, $body is an array that is sent as JSON.
* Returns the decoded answer, or throws BillosError on anything that is not a 2xx.
*/
function billos(string $method, string $path, ?array $body = null, ?string $idempotencyKey = null): array
{
$headers = ['X-Api-Key: ' . BILLOS_API_KEY, 'Accept: application/json'];
$options = [
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_TIMEOUT => 30,
];
if ($body !== null) {
$headers[] = 'Content-Type: application/json';
// An empty PHP array encodes as [], and the API reads a body as an object.
$options[CURLOPT_POSTFIELDS] = json_encode($body ?: new stdClass(), JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
}
// The same key on a repeat answers the document that already exists, so a retry after
// a timeout never issues twice.
if ($idempotencyKey !== null) {
$headers[] = 'Idempotency-Key: ' . $idempotencyKey;
}
$options[CURLOPT_HTTPHEADER] = $headers;
$ch = curl_init(BILLOS_BASE_URL . $path);
curl_setopt_array($ch, $options);
$raw = curl_exec($ch);
$status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
$failure = $raw === false ? curl_error($ch) : null;
curl_close($ch);
if ($failure !== null) {
throw new BillosError("BillOS did not answer: $failure", 0, 'network', null, null, null, true, null);
}
$answer = json_decode($raw, true);
if ($status >= 200 && $status < 300 && is_array($answer)) {
return $answer;
}
$e = is_array($answer) ? $answer : [];
throw new BillosError(
$e['error'] ?? "BillOS answered $status",
$status,
$e['reason'] ?? null,
$e['hint'] ?? null,
$e['param'] ?? null,
$e['doc_url'] ?? null,
(bool) ($e['retryable'] ?? false),
$e['request_id'] ?? null,
);
}שני פרטים שקל לפספס ב-PHP. מערך ריק מקודד כ-[], וה-API מצפה לאובייקט, ולכן גוף ריק נשלח כ-{}. והדגל JSON_UNESCAPED_UNICODE שומר על העברית כמו שהיא.
מההזמנה לטיוטה
כל סכום ב-API הוא מספר שלם באגורות: 354.00 ₪ הם 35400. ממירים פעם אחת, במקום שבו המחיר נכנס לקוד, ומשם לא נוגעים בשברים.
/** Money is integer agorot everywhere in the API (1 shekel = 100 agorot). Convert once, where
* a price enters, and never carry a float past this line. */
function to_agorot(int|float|string $shekels): int
{
return (int) round((float) $shekels * 100);
}מההזמנה בונים את גוף המסמך. הזמנה ששולמה היא חשבונית מס קבלה (סוג 320), והזמנה שתשולם אחר כך היא חשבונית מס (סוג 305). הלקוח נמצא לפי הטלפון ואז לפי השם, כך שלקוח חוזר נשאר כרטיס אחד.
function document_body(string $bid, array $order): array
{
$customer = $order['customer'] ?? [];
// Matched by phone, then by exact name, so a returning customer keeps one card.
$party = billos('POST', "/businesses/$bid/parties/find-or-create", [
'name' => $customer['name'] ?? null,
'phone' => $customer['phone'] ?? null,
'email' => $customer['email'] ?? null,
])['party'];
$lines = [];
$total = 0;
foreach ($order['items'] ?? [] as $item) {
$line = [
'description' => $item['description'] ?? null,
'quantity' => $item['quantity'] ?? 1,
'unitPriceExVat' => to_agorot($item['unitPrice'] ?? 0),
];
// The API rounds once per line (quantity x unit price), and so does this.
$total += (int) round($line['quantity'] * $line['unitPriceExVat']);
$lines[] = $line;
}
$paid = isset($order['payment']);
$body = [
// 320 is an invoice-receipt (חשבונית מס קבלה): the sale and its payment on one document.
// 305 is a tax invoice, for payment later. An exempt dealer (עוסק פטור) may issue
// neither: receipts (400) and proformas (300) only.
'docType' => $paid ? 320 : 305,
// The shop's prices include VAT. In gross mode unitPriceExVat carries the VAT-inclusive
// price, the total is exactly the sum the customer paid, and the VAT is derived from it.
'priceMode' => 'gross',
'party' => ['partyId' => $party['id']],
'lines' => $lines,
];
if ($paid) {
// On a 320 the payments must add up to the total exactly, or issuing answers payments_mismatch.
$body['payments'] = [['method' => $order['payment']['method'] ?? null, 'amount' => $total]];
} else {
$body['dueDate'] = $order['dueDate'] ?? null;
}
return $body;
}המחירים בחנות כוללים מע״מ, ולכן המסמך נשלח ב-priceMode: gross: הסכום הכולל הוא בדיוק מה שהלקוח שילם, והמע״מ מחושב מתוכו.
הטיוטה נוצרת עם מפתח idempotency, שהוא המזהה שלכם להזמנה. לחיצה כפולה, ניסיון חוזר אחרי timeout ובדיקה שבאה לפני הפקה מגיעים כולם לאותו מסמך.
/** The idempotency key is your own id (an order, a payment): a double click, a retry after a
* timeout and the validate-then-issue pair all land on the same document. */
function draft_for(string $bid, string $idempotencyKey, array $body): array
{
$created = billos('POST', "/businesses/$bid/documents", $body, $idempotencyKey);
// A replay answers the row that exists and does not read the body it was sent. A draft is
// not a tax document yet and may be deleted freely, so a leftover one is replaced by the
// request as it stands now. An issued document comes back as it is: it can never change.
if (!empty($created['deduped']) && $created['document']['status'] === 'draft') {
billos('DELETE', "/businesses/$bid/documents/{$created['document']['id']}");
$created = billos('POST', "/businesses/$bid/documents", $body, $idempotencyKey);
}
return $created['document'];
}מפיקים, ושולחים ללקוח
ההפקה היא הנקודה שאין ממנה חזרה: המסמך מקבל את המספר הבא ברצף, ומאותו רגע הוא קבוע. מי שרוצה להציג ללקוח מסך אישור לפני כן קורא ל-validate, שמריץ את כל הבדיקות של ההפקה ולא תופס מספר.
if ($method === 'POST' && preg_match('#^/orders/([^/]+)/invoice$#', $path, $m)) {
$draft = draft_for($bid, "order-$m[1]", document_body($bid, $input));
// The point of no return: a gapless legal number and a signed PDF. Issuing is idempotent
// on the document itself: sent again, it answers the same document with deduped: true.
$issued = billos('POST', "/businesses/$bid/documents/{$draft['id']}/issue", []);
$document = $issued['document'];
reply(empty($issued['deduped']) ? 201 : 200, [
'documentId' => $document['id'], // keep it on the order: the receipt and the credit note need it
'docType' => $document['docType'],
'docNumber' => $document['docNumber'],
'totalIncVat' => $document['totalIncVat'],
'vatAmount' => $document['vatAmount'],
'deduped' => !empty($issued['deduped']),
'warnings' => $issued['warnings'] ?? [],
] + pdf_link($bid, $document['id']));
}הקישור ל-PDF הוא קישור ציבורי, מתאים ל-WhatsApp או למייל. הקישור הראשון נושא את המקור, שנמסר פעם אחת, וכל קישור אחריו נושא העתק.
/** The public link to the PDF. `path` is relative to the API host. Sharing is a print: the first
* link carries the original, which may be handed out once, and every later link a copy. */
function pdf_link(string $bid, string $documentId): array
{
try {
$share = billos('POST', "/businesses/$bid/documents/$documentId/share", []);
} catch (BillosError $e) {
// The document is issued and numbered; only its PDF is still rendering. Ask again shortly.
if ($e->reason === 'pdf_pending') {
return ['pdfUrl' => null, 'pdfVariant' => null];
}
throw $e;
}
$host = preg_replace('#^(https?://[^/]+).*$#', '$1', BILLOS_BASE_URL);
return ['pdfUrl' => $host . $share['path'], 'pdfVariant' => $share['variant']];
}כשה-API מסרב
כל סירוב מגיע עם reason, קוד יציב שעליו מסתעפים, ועם hint, שאומר מה לשנות. ההודעה עצמה מיועדת לאנשים וליומן, והקוד לא נשען עליה.
} catch (BillosError $e) {
// Pass the reason and the hint on to whoever called. The message is for people and logs:
// never branch on it.
error_log("[billos] {$e->status} {$e->reason}: {$e->getMessage()}" . ($e->hint ? " | hint: {$e->hint}" : '') . " (request {$e->requestId})");
reply($e->status ?: 502, [ // status 0 is a network failure
'error' => $e->getMessage(),
'reason' => $e->reason,
'hint' => $e->hint,
'param' => $e->param,
'docUrl' => $e->docUrl,
'retryable' => $e->retryable,
'requestId' => $e->requestId,
]);
}| שדה | מה הוא אומר |
|---|---|
reason | הקוד היציב של הסירוב, למשל validation או payments_mismatch. |
hint | מה לשנות בבקשה. |
param | השדה שהסירוב מדבר עליו, כשיש כזה. |
retryable | האם אותה קריאה יכולה להצליח בניסיון נוסף. |
requestId | מזהה הקריאה. אותו מצרפים לפנייה לתמיכה. |
תיקון הוא זיכוי
מסמך שהופק לא נערך ולא נמחק. מתקנים אותו בחשבונית זיכוי שמפנה אליו, על כל הסכום או על חלק ממנו. כשהכסף חזר ללקוח, refund מפיק גם את הקבלה השלילית על ההחזר.
if ($method === 'POST' && preg_match('#^/documents/([^/]+)/credit-note$#', $path, $m)) {
// A repeat of a credit in full is caught by reading the source first. A partial credit
// leaves no such mark: dedupe it on your side.
$source = billos('GET', "/businesses/$bid/documents/$m[1]")['document'];
if (!empty($source['cancelledById'])) {
reply(200, ['alreadyCredited' => true, 'creditNoteId' => $source['cancelledById']]);
}
$credit = ['reason' => $input['reason'] ?? null]; // printed on the credit note, and required for a partial credit
if (isset($input['amount'])) {
$credit['amount'] = to_agorot($input['amount']); // a partial credit, VAT included
}
if (!empty($input['refunded'])) {
// An invoice-receipt whose money went back also needs the negative receipt for the refund.
$credit['refund'] = true;
}
$result = billos('POST', "/businesses/$bid/documents/$m[1]/credit-note", $credit);
$note = $result['document'];
$refund = $result['refund'] ?? null;
reply(201, [
'creditNote' => ['documentId' => $note['id'], 'docType' => $note['docType'], 'docNumber' => $note['docNumber'], 'totalIncVat' => $note['totalIncVat']],
'refund' => $refund ? ['documentId' => $refund['id'], 'docNumber' => $refund['docNumber'], 'totalIncVat' => $refund['totalIncVat']] : null,
'source' => $result['source'], // { id, cancelledById, creditedAmount, remaining }
] + pdf_link($bid, $note['id']));
}Webhook חתום
BillOS שולחת אירוע על כל מסמך שהופק או שולם. כל משלוח חתום ב-HMAC-SHA256 על חותמת הזמן, נקודה והגוף הגולמי. ב-PHP קוראים את הגוף מ-php://input לפני שמפענחים אותו, ומשווים ב-hash_equals.
/**
* Is this delivery from BillOS? The header is "t=<unix time>,v1=<hex>", and v1 is the
* HMAC-SHA256 of "<t>.<raw body>" with the endpoint's secret (whsec_...). Sign the bytes
* as they arrived: a body that was decoded and encoded again does not match.
*/
function billos_webhook_is_genuine(string $secret, string $header, string $rawBody, int $toleranceSeconds = 300): bool
{
$parts = [];
foreach (explode(',', $header) as $pair) {
[$name, $value] = array_pad(explode('=', $pair, 2), 2, '');
$parts[trim($name)] = trim($value);
}
$t = $parts['t'] ?? '';
$v1 = $parts['v1'] ?? '';
if ($v1 === '' || !ctype_digit($t)) {
return false;
}
// An old delivery sent again by someone who recorded it.
if (abs(time() - (int) $t) > $toleranceSeconds) {
return false;
}
// hash_equals compares in constant time; == would leak how much of the signature matched.
return hash_equals(hash_hmac('sha256', "$t.$rawBody", $secret), $v1);
}המקבל עונה 200 מהר, כי תשובה שלא הגיעה בתוך עשר שניות נשלחת שוב, ומטפל בכל משלוח פעם אחת לפי המזהה שלו.
if ($method === 'POST' && $path === '/webhooks/billos') {
if (BILLOS_WEBHOOK_SECRET === '') {
reply(503, ['error' => 'BILLOS_WEBHOOK_SECRET is not set']);
}
if (!billos_webhook_is_genuine(BILLOS_WEBHOOK_SECRET, $_SERVER['HTTP_X_BILLOS_SIGNATURE'] ?? '', $raw)) {
reply(400, ['error' => 'invalid signature']);
}
$delivery = json_decode($raw, true);
// Delivery is at least once and unordered: a retry carries the same delivery id.
if (first_time_seen($delivery['id'])) {
// Anything but a 2xx inside ten seconds is retried. Under PHP-FPM the answer goes
// out first and the work runs after it; anything slower belongs in your queue.
if (function_exists('fastcgi_finish_request')) {
http_response_code(200);
fastcgi_finish_request();
}
try {
handle_event($delivery);
} catch (Throwable $e) {
error_log('[billos] webhook handler failed: ' . $e->getMessage());
}
}
reply(200);
}Laravel, WordPress וכל השאר
הקובץ billos.php לא תלוי במסגרת עבודה. הוא קורא שני קבועים, BILLOS_API_KEY ו-BILLOS_BASE_URL, ואותם מגדירים פעם אחת מתוך ההגדרות של הפרויקט שלכם. מכאן קוראים ל-billos() מ-controller, מ-job בתור או מ-hook.
- המפתח נשאר בשרת. מי שמחזיק בו יכול להפיק מסמכים בשם העסק. הוא לא נשלח לדפדפן ולא נכנס לקוד.
- מגדירים את מזהה העסק. PHP מתחיל מאפס בכל בקשה. בלי
BILLOS_BUSINESS_IDכל בקשה שואלת קודם איזה עסק יש למפתח. - חנות WooCommerce. לחיבור של חנות יש עמוד משלו: חשבונית אוטומטית ל-WooCommerce.
- לקוח עסקי. חשבונית מס לעסק אחר יכולה להזדקק למספר הקצאה. הוא מגיע בתוך קריאת ההפקה, בלי קוד נוסף.
כל קריאה אחרת, גם ב-PHP
הדוגמה מכסה את המסלול הנפוץ. לכל שאר הקריאות, מהוצאות ועד דוחות לרואה החשבון, יש עמוד ב-API reference, וכל עמוד מציג את הבקשה שלו ב-PHP, מוכנה להעתקה, לצד cURL, Node.js, Python ו-C#.
שאלות נפוצות
יש ל-BillOS ספריית PHP או חבילת Composer?
לא. ה-API הוא JSON מעל HTTPS עם כותרת אחת, והקוד בעמוד הזה, פונקציה אחת מעל curl, הוא כל מה שצריך. מי שרוצה לקוח עם טיפוסים יכול לייצר אותו ממפרט ה-OpenAPI.
איזו גרסת PHP צריך?
PHP 8.1 ומעלה, עם הרחבת curl. אין תלות אחרת.
זה עובד ב-Laravel וב-WordPress?
כן. הקובץ billos.php לא תלוי במסגרת עבודה. טוענים אותו, מגדירים את המפתח ואת כתובת ה-API, וקוראים לפונקציה מכל מקום בקוד.
איך מונעים חשבונית כפולה כשהלקוח לוחץ פעמיים?
הטיוטה נוצרת עם הכותרת Idempotency-Key, שהיא מזהה ההזמנה שלכם. קריאה שנייה עם אותו מפתח מחזירה את המסמך שכבר קיים, ולא מפיקה מספר נוסף.
איך בודקים בלי להפיק מסמך אמיתי?
במפתח Sandbox, שמתחיל ב-bk_test_. הוא בחינם, עובד מול מסד נתונים נפרד, ושום דבר ממנו לא מגיע לרשות המסים. כשהכול עובד מחליפים את המפתח, והקוד נשאר כמו שהוא.
ומה עם C# ושפות אחרות?
כל עמוד ב-API reference מציג את הקריאה שלו גם ב-C#, לצד cURL, Node.js ו-Python. ל-Node.js ול-Python יש גם ספריות, וממפרט ה-OpenAPI אפשר לייצר לקוח לכל שפה אחרת.
המסמך הראשון, עוד היום
מפתח Sandbox בחינם, בלי כרטיס אשראי. הקוד שעובד מול הבדיקות עובד מול live בלי שינוי.
מפתח Sandbox בחינם