{
 "name": "Telr payment → ZATCA invoice (Matheel)",
 "nodes": [
  {
   "parameters": {
    "httpMethod": "POST",
    "path": "matheel-telr",
    "responseMode": "onReceived",
    "options": {}
   },
   "name": "Telr webhook",
   "type": "n8n-nodes-base.webhook",
   "typeVersion": 2,
   "position": [
    0,
    0
   ],
   "notes": "Paste this node's Production URL in Telr → Transaction advice (authorised transactions only)",
   "notesInFlow": true
  },
  {
   "parameters": {
    "jsCode": "// ── Settings: edit these ─────────────────────────────────────────────\nconst MATHEEL_KEY = '';                 // your Matheel key (mtl_…); empty = developer sandbox\nconst TELR_SECRET = 'YOUR-TELR-SECRET';  // Telr dashboard → Transaction advice → secret\nconst ITEM_NAME = 'Service | خدمة';      // invoice line name when Telr sends no description\n// ─────────────────────────────────────────────────────────────────────\n// Telr \"Transaction advice\": verify tran_check (SHA1 of secret + tran_* fields), file only authorised sales.\nfunction sha1(msg) {\n  const b = new TextEncoder().encode(msg), l = b.length, w = new Uint32Array(((l + 8 >> 6) + 1) * 16);\n  for (let i = 0; i < l; i++) w[i >> 2] |= b[i] << (24 - (i % 4) * 8);\n  w[l >> 2] |= 0x80 << (24 - (l % 4) * 8); w[w.length - 1] = l * 8;\n  let h = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0];\n  const r = (x, n) => (x << n) | (x >>> (32 - n));\n  for (let i = 0; i < w.length; i += 16) {\n    const x = new Array(80); let [a, bb, c, d, e] = h;\n    for (let t = 0; t < 80; t++) {\n      x[t] = t < 16 ? w[i + t] : r(x[t - 3] ^ x[t - 8] ^ x[t - 14] ^ x[t - 16], 1);\n      const f = t < 20 ? (bb & c) | (~bb & d) : t < 40 ? bb ^ c ^ d : t < 60 ? (bb & c) | (bb & d) | (c & d) : bb ^ c ^ d;\n      const k = t < 20 ? 0x5A827999 : t < 40 ? 0x6ED9EBA1 : t < 60 ? 0x8F1BBCDC : 0xCA62C1D6;\n      const tmp = (r(a, 5) + f + e + k + x[t]) | 0; e = d; d = c; c = r(bb, 30); bb = a; a = tmp;\n    }\n    h = h.map((v, j) => (v + [a, bb, c, d, e][j]) | 0);\n  }\n  return h.map((v) => (v >>> 0).toString(16).padStart(8, '0')).join('');\n}\nconst p = $input.first().json.body || {};\nconst names = ['tran_store', 'tran_type', 'tran_class', 'tran_test', 'tran_ref', 'tran_prevref', 'tran_firstref',\n  ...('tran_order' in p ? ['tran_order'] : []), 'tran_currency', 'tran_amount', 'tran_cartid', 'tran_desc',\n  'tran_status', 'tran_authcode', 'tran_authmessage'];\nconst check = sha1([TELR_SECRET, ...names.map((n) => String(p[n] ?? '').trim())].join(':'));\nif (String(p.tran_check || '').toLowerCase() !== check) throw new Error('Telr tran_check does not match: wrong secret or forged request');\nif (!['A', 'H'].includes(p.tran_status)) return [];                       // not authorised: no invoice\nif (/void|refund|release|cancel/i.test(String(p.tran_type || ''))) return []; // money going back: no sale invoice\nreturn [{ json: {\n  matheel_key: MATHEEL_KEY,\n  email: p.bill_email || null,\n  telr_ref: p.tran_ref,\n  invoice: { type: 'simplified', number: String(p.tran_cartid || p.tran_ref), prices_include_vat: true,\n             line_items: [{ name: p.tran_desc || ITEM_NAME, quantity: 1, price: String(p.tran_amount) }] },\n} }];\n"
   },
   "name": "Verify Telr",
   "type": "n8n-nodes-base.code",
   "typeVersion": 2,
   "position": [
    220,
    0
   ],
   "notes": "Edit the three settings at the top",
   "notesInFlow": true
  },
  {
   "parameters": {
    "resource": "row",
    "operation": "get",
    "dataTableId": {
     "__rl": true,
     "mode": "name",
     "value": "matheel_device"
    },
    "returnAll": false,
    "limit": 1,
    "options": {}
   },
   "name": "Get device token",
   "type": "n8n-nodes-base.dataTable",
   "typeVersion": 1,
   "position": [
    440,
    0
   ],
   "notes": "Data table matheel_device: one row, column token = your device_token",
   "notesInFlow": true
  },
  {
   "parameters": {
    "method": "POST",
    "url": "https://matheel.app/api/v1/invoices",
    "sendHeaders": true,
    "headerParameters": {
     "parameters": [
      {
       "name": "Authorization",
       "value": "=Bearer {{ $('Verify Telr').first().json.matheel_key }}"
      }
     ]
    },
    "sendBody": true,
    "specifyBody": "json",
    "jsonBody": "={{ JSON.stringify({ device_token: $json.token, pdf: true, invoice: $('Verify Telr').first().json.invoice }) }}",
    "options": {
     "response": {
      "response": {
       "fullResponse": true,
       "neverError": true
      }
     }
    }
   },
   "name": "File with Matheel",
   "type": "n8n-nodes-base.httpRequest",
   "typeVersion": 4.2,
   "position": [
    660,
    0
   ]
  },
  {
   "parameters": {
    "conditions": {
     "options": {
      "caseSensitive": true,
      "leftValue": "",
      "typeValidation": "loose",
      "version": 2
     },
     "conditions": [
      {
       "leftValue": "={{ $json.statusCode }}",
       "rightValue": 200,
       "operator": {
        "type": "number",
        "operation": "equals"
       }
      }
     ],
     "combinator": "and"
    },
    "options": {}
   },
   "name": "Filed?",
   "type": "n8n-nodes-base.if",
   "typeVersion": 2.2,
   "position": [
    880,
    0
   ]
  },
  {
   "parameters": {
    "resource": "row",
    "operation": "update",
    "dataTableId": {
     "__rl": true,
     "mode": "name",
     "value": "matheel_device"
    },
    "filters": {
     "conditions": [
      {
       "keyName": "id",
       "condition": "eq",
       "keyValue": "={{ $('Get device token').first().json.id }}"
      }
     ]
    },
    "columns": {
     "mappingMode": "defineBelow",
     "value": {
      "token": "={{ $('File with Matheel').first().json.body.device_token }}"
     },
     "matchingColumns": [],
     "schema": [
      {
       "id": "token",
       "displayName": "token",
       "required": false,
       "defaultMatch": false,
       "display": true,
       "type": "string",
       "canBeUsedToMatch": true
      }
     ]
    },
    "options": {}
   },
   "name": "Save new token",
   "type": "n8n-nodes-base.dataTable",
   "typeVersion": 1,
   "position": [
    1100,
    -100
   ],
   "notes": "The next invoice must use the new token",
   "notesInFlow": true
  },
  {
   "parameters": {},
   "name": "Invoice ready (send the PDF here)",
   "type": "n8n-nodes-base.noOp",
   "typeVersion": 1,
   "position": [
    1320,
    -100
   ],
   "notes": "Replace with Gmail/SMTP: to {{ $('Verify Telr').first().json.email }}, attach {{ $('File with Matheel').first().json.body.pdf }} (base64)",
   "notesInFlow": true
  },
  {
   "parameters": {
    "conditions": {
     "options": {
      "caseSensitive": true,
      "leftValue": "",
      "typeValidation": "loose",
      "version": 2
     },
     "conditions": [
      {
       "leftValue": "={{ $json.statusCode }}",
       "rightValue": 409,
       "operator": {
        "type": "number",
        "operation": "equals"
       }
      }
     ],
     "combinator": "and"
    },
    "options": {}
   },
   "name": "Chain busy (409)?",
   "type": "n8n-nodes-base.if",
   "typeVersion": 2.2,
   "position": [
    1100,
    100
   ]
  },
  {
   "parameters": {
    "resume": "timeInterval",
    "amount": 2,
    "unit": "seconds"
   },
   "name": "Wait 2s",
   "type": "n8n-nodes-base.wait",
   "typeVersion": 1.1,
   "position": [
    1320,
    60
   ],
   "notes": "Another payment took this token: re-read it and try again",
   "notesInFlow": true
  },
  {
   "parameters": {
    "errorMessage": "={{ 'Matheel ' + $json.statusCode + ': ' + JSON.stringify($json.body) }}"
   },
   "name": "Stop: not filed",
   "type": "n8n-nodes-base.stopAndError",
   "typeVersion": 1,
   "position": [
    1320,
    200
   ]
  }
 ],
 "connections": {
  "Telr webhook": {
   "main": [
    [
     {
      "node": "Verify Telr",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Verify Telr": {
   "main": [
    [
     {
      "node": "Get device token",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Get device token": {
   "main": [
    [
     {
      "node": "File with Matheel",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "File with Matheel": {
   "main": [
    [
     {
      "node": "Filed?",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Filed?": {
   "main": [
    [
     {
      "node": "Save new token",
      "type": "main",
      "index": 0
     }
    ],
    [
     {
      "node": "Chain busy (409)?",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Save new token": {
   "main": [
    [
     {
      "node": "Invoice ready (send the PDF here)",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Chain busy (409)?": {
   "main": [
    [
     {
      "node": "Wait 2s",
      "type": "main",
      "index": 0
     }
    ],
    [
     {
      "node": "Stop: not filed",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Wait 2s": {
   "main": [
    [
     {
      "node": "Get device token",
      "type": "main",
      "index": 0
     }
    ]
   ]
  }
 },
 "settings": {
  "executionOrder": "v1"
 }
}