{
  "name": "Create invoice PDFs from Stripe payments, email them and archive to S3",
  "id": "pdfops-stripe-invoice-storage",
  "nodes": [
    {
      "parameters": {
        "content": "## Create invoice PDFs from Stripe payments, email them and archive to S3\n\nEvery successful Stripe payment becomes an archival invoice PDF, emailed to the customer, stored in S3 and logged to a ledger. No invoicing service.\n\nThe trap this handles: **Stripe reports amounts in the smallest currency unit, but not every currency has 100 of them.** JPY, KRW and 13 others are zero-decimal; BHD, JOD, KWD, OMR and TND have three decimals. The usual `amount / 100` is wrong for them, so this handles each.\n\n### How it works\n- **Payment Succeeded** fires on `payment_intent.succeeded`; **Has Billable Amount?** drops $0 events.\n- **Check Ledger for Event** skips a redelivered event instead of invoicing twice.\n- **Fetch Stripe Customer** resolves the name and email. Guest payments skip it and use the receipt email.\n- **Build Invoice Payload** applies the right currency divisor and derives the net when a tax rate is set.\n- The PDF fans out: **S3** archives (the ledger row is written only after the upload succeeds), **Gmail** sends. A failed lookup, render, upload, email or ledger write alerts **Slack**. A failed duplicate check stops the run: set an error workflow.\n\n### Setup\n1. Install the **PDFops** community node (`n8n-nodes-pdfops`) from Settings > Community nodes. It is verified by n8n.\n2. Connect **Stripe**, **AWS**, **Gmail**, **Sheets** and **Slack** credentials.\n3. Open **Set Invoice Defaults** for company name, prefix, tax rate and bucket.\n4. Give the ledger sheet a header row: Invoice, Date, Customer, Currency, Total, Payment ID, Event ID. Select it on both Sheets nodes.\n5. Set your channel on **Alert Billing Channel**. *(Optional)* add a **PDFops API** credential; keyless works at 100 req/IP/month.\n\n### Customization tips\n- `minimumAmount` is in Stripe's smallest unit: 500 means $5.00.\n- Leave `taxRate` at 0 so the invoice total equals the charge.",
        "width": 560,
        "height": 1320
      },
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -840,
        -120
      ],
      "id": "note-overview",
      "name": "Overview"
    },
    {
      "parameters": {
        "content": "## 1. Catch the payment, skip what isn't billable\n**Set Invoice Defaults** is the one place to edit company details, tax and bucket. Zero-amount events and events already in the ledger stop here.",
        "width": 1100,
        "height": 700,
        "color": 7
      },
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -160,
        -40
      ],
      "id": "note-section-1",
      "name": "Section 1"
    },
    {
      "parameters": {
        "content": "## 2. Resolve the customer, shape the invoice\nLook up the customer, then map the charge. Zero- and three-decimal currencies are divided correctly, and tax is derived from the charged total.",
        "width": 660,
        "height": 700,
        "color": 7
      },
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        960,
        -40
      ],
      "id": "note-section-2",
      "name": "Section 2"
    },
    {
      "parameters": {
        "content": "## 3. Render once, deliver two ways\nOne deterministic PDF, then fan out: archive to S3 then log to the ledger, and email the customer when one is on file.",
        "width": 760,
        "height": 700,
        "color": 7
      },
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        1640,
        -40
      ],
      "id": "note-section-3",
      "name": "Section 3"
    },
    {
      "parameters": {
        "content": "## Failure path\nFailed steps after the duplicate check post to Slack with the payment id, so a missing invoice is noticed instead of silently never existing.",
        "width": 480,
        "height": 280,
        "color": 7
      },
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        1620,
        700
      ],
      "id": "note-section-4",
      "name": "Section 4"
    },
    {
      "parameters": {
        "events": [
          "payment_intent.succeeded"
        ]
      },
      "id": "trigger-stripe",
      "name": "Payment Succeeded",
      "type": "n8n-nodes-base.stripeTrigger",
      "typeVersion": 1,
      "position": [
        -80,
        180
      ]
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "cfg-company",
              "name": "companyName",
              "value": "Your Company Inc",
              "type": "string"
            },
            {
              "id": "cfg-prefix",
              "name": "invoicePrefix",
              "value": "INV",
              "type": "string"
            },
            {
              "id": "cfg-tax",
              "name": "taxRate",
              "value": 0,
              "type": "number"
            },
            {
              "id": "cfg-line",
              "name": "defaultLineItem",
              "value": "Payment received",
              "type": "string"
            },
            {
              "id": "cfg-notes",
              "name": "invoiceNotes",
              "value": "Thank you for your business.",
              "type": "string"
            },
            {
              "id": "cfg-bucket",
              "name": "s3Bucket",
              "value": "your-invoices-bucket",
              "type": "string"
            },
            {
              "id": "cfg-min",
              "name": "minimumAmount",
              "value": 1,
              "type": "number"
            }
          ]
        },
        "includeOtherFields": true,
        "options": {}
      },
      "id": "set-invoice-defaults",
      "name": "Set Invoice Defaults",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        140,
        180
      ]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "cond-billable",
              "leftValue": "={{ ($json.data.object.amount_received || $json.data.object.amount || 0) >= $json.minimumAmount }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "if-billable",
      "name": "Has Billable Amount?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        360,
        180
      ]
    },
    {
      "parameters": {},
      "id": "noop-skip",
      "name": "Skip Zero-Amount Payment",
      "type": "n8n-nodes-base.noOp",
      "typeVersion": 1,
      "position": [
        360,
        440
      ]
    },
    {
      "parameters": {
        "operation": "read",
        "documentId": {
          "mode": "url",
          "value": "https://docs.google.com/spreadsheets/d/REPLACE_WITH_YOUR_SHEET_ID/edit"
        },
        "sheetName": {
          "mode": "name",
          "value": "Invoices"
        },
        "filtersUI": {
          "values": [
            {
              "lookupColumn": "Event ID",
              "lookupValue": "={{ $('Payment Succeeded').first().json.id }}"
            }
          ]
        },
        "options": {}
      },
      "id": "sheets-check-event",
      "name": "Check Ledger for Event",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.5,
      "position": [
        580,
        180
      ],
      "onError": "stopWorkflow",
      "alwaysOutputData": true
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "cond-already-invoiced",
              "leftValue": "={{ !!$json['Event ID'] }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "if-already-invoiced",
      "name": "Already Invoiced?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        800,
        180
      ]
    },
    {
      "parameters": {},
      "id": "noop-duplicate",
      "name": "Skip Duplicate Event",
      "type": "n8n-nodes-base.noOp",
      "typeVersion": 1,
      "position": [
        800,
        440
      ]
    },
    {
      "parameters": {
        "resource": "customer",
        "operation": "get",
        "customerId": "={{ $('Payment Succeeded').first().json.data.object.customer }}"
      },
      "id": "stripe-customer",
      "name": "Fetch Stripe Customer",
      "type": "n8n-nodes-base.stripe",
      "typeVersion": 1,
      "position": [
        1200,
        180
      ],
      "onError": "continueErrorOutput"
    },
    {
      "parameters": {
        "jsCode": "// Stripe reports amounts in the smallest currency unit, but not every currency\n// has 100 of them. These 15 are zero-decimal (JPY, KRW and 13 others), so the\n// reflexive `amount / 100` issues an invoice 100x too small. UGX is NOT listed:\n// Stripe treats it as two-decimal in the API (500 means 5 UGX).\nconst ZERO_DECIMAL = ['bif', 'clp', 'djf', 'gnf', 'jpy', 'kmf', 'krw', 'mga', 'pyg', 'rwf', 'vnd', 'vuv', 'xaf', 'xof', 'xpf'];\n// BHD, JOD, KWD, OMR and TND are three-decimal: 1000 units to the major unit.\nconst THREE_DECIMAL = ['bhd', 'jod', 'kwd', 'omr', 'tnd'];\n\nconst cfg = $('Set Invoice Defaults').first().json;\n// The Stripe Trigger emits the Event envelope, not the PaymentIntent ,\n// the object itself is nested at data.object.\nconst payment = $('Payment Succeeded').first().json.data.object;\nconst customer = $input.first().json || {};\n\nconst currency = (payment.currency || 'usd').toLowerCase();\nconst decimals = ZERO_DECIMAL.includes(currency) ? 0 : THREE_DECIMAL.includes(currency) ? 3 : 2;\nconst round = (v) => Number(v.toFixed(decimals));\n\nconst total = round((payment.amount_received || payment.amount || 0) / 10 ** decimals);\n\n// If a tax rate is set, derive the net so the invoice shows net + tax. Note the\n// limit: PDFops recomputes subtotal -> tax -> total from unit_price, and roughly\n// 10% of (amount, rate) pairs have NO 2-decimal net that multiplies back to the\n// exact charged total: it is a representability limit, not a rounding bug.\n// Leave taxRate at 0 (the default) if you need the invoice total to equal the\n// charge exactly; the sticky says so too.\nconst rate = Number(cfg.taxRate) || 0;\nconst unitPrice = round(rate > 0 ? total / (1 + rate / 100) : total);\n\n// Guest checkouts have no customer object: fall back to the receipt email.\nconst billTo = customer.name || customer.email || payment.receipt_email || 'Customer';\n\nreturn [\n  {\n    json: {\n      invoice: {\n        from: cfg.companyName,\n        to: billTo,\n        invoice_number: `${cfg.invoicePrefix}-${String(payment.id).slice(-8).toUpperCase()}`,\n        date: new Date((payment.created || Date.now() / 1000) * 1000).toISOString().slice(0, 10),\n        currency: currency.toUpperCase(),\n        tax_rate: rate,\n        notes: cfg.invoiceNotes,\n        items: [\n          {\n            description: payment.description || cfg.defaultLineItem,\n            quantity: 1,\n            unit_price: unitPrice,\n          },\n        ],\n      },\n      customerEmail: customer.email || payment.receipt_email || '',\n      paymentId: payment.id,\n      eventId: $('Payment Succeeded').first().json.id,\n      chargedTotal: total,\n      s3Bucket: cfg.s3Bucket,\n    },\n  },\n];"
      },
      "id": "code-build-invoice",
      "name": "Build Invoice Payload",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1420,
        180
      ],
      "onError": "continueErrorOutput"
    },
    {
      "parameters": {
        "operation": "invoice",
        "invoice": "={{ $json.invoice }}",
        "outputBinaryPropertyName": "data",
        "fileName": "={{ $json.invoice.invoice_number }}.pdf"
      },
      "id": "pdfops-invoice",
      "name": "PDFops Generate Invoice",
      "type": "n8n-nodes-pdfops.pdfops",
      "typeVersion": 1,
      "position": [
        1660,
        180
      ],
      "onError": "continueErrorOutput"
    },
    {
      "parameters": {
        "resource": "file",
        "operation": "upload",
        "bucketName": "={{ $('Build Invoice Payload').item.json.s3Bucket }}",
        "fileName": "={{ 'invoices/' + $('Build Invoice Payload').item.json.invoice.invoice_number + '.pdf' }}",
        "binaryData": true,
        "binaryPropertyName": "data",
        "additionalFields": {}
      },
      "id": "s3-upload",
      "name": "Archive to S3",
      "type": "n8n-nodes-base.awsS3",
      "typeVersion": 2,
      "position": [
        1880,
        180
      ],
      "onError": "continueErrorOutput"
    },
    {
      "parameters": {
        "resource": "message",
        "operation": "send",
        "sendTo": "={{ $('Build Invoice Payload').item.json.customerEmail }}",
        "subject": "={{ 'Invoice ' + $('Build Invoice Payload').item.json.invoice.invoice_number }}",
        "emailType": "text",
        "message": "Thank you for your payment. Your invoice is attached.",
        "options": {
          "attachmentsUi": {
            "attachmentsBinary": [
              {
                "property": "data"
              }
            ]
          }
        }
      },
      "id": "gmail-invoice",
      "name": "Email Invoice to Customer",
      "type": "n8n-nodes-base.gmail",
      "typeVersion": 2.1,
      "position": [
        2100,
        400
      ],
      "onError": "continueErrorOutput"
    },
    {
      "parameters": {
        "operation": "append",
        "documentId": {
          "mode": "url",
          "value": "https://docs.google.com/spreadsheets/d/REPLACE_WITH_YOUR_SHEET_ID/edit"
        },
        "sheetName": {
          "mode": "name",
          "value": "Invoices"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "Invoice": "={{ $('Build Invoice Payload').item.json.invoice.invoice_number }}",
            "Date": "={{ $('Build Invoice Payload').item.json.invoice.date }}",
            "Customer": "={{ $('Build Invoice Payload').item.json.invoice.to }}",
            "Currency": "={{ $('Build Invoice Payload').item.json.invoice.currency }}",
            "Total": "={{ $('Build Invoice Payload').item.json.chargedTotal }}",
            "Payment ID": "={{ $('Build Invoice Payload').item.json.paymentId }}",
            "Event ID": "={{ $('Build Invoice Payload').item.json.eventId }}"
          },
          "matchingColumns": [],
          "schema": [
            {
              "id": "Invoice",
              "displayName": "Invoice",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Date",
              "displayName": "Date",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Customer",
              "displayName": "Customer",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Currency",
              "displayName": "Currency",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Total",
              "displayName": "Total",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Payment ID",
              "displayName": "Payment ID",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Event ID",
              "displayName": "Event ID",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            }
          ]
        },
        "options": {}
      },
      "id": "sheets-ledger",
      "name": "Log to Invoice Ledger",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.5,
      "position": [
        2100,
        180
      ],
      "onError": "continueErrorOutput"
    },
    {
      "parameters": {
        "resource": "message",
        "operation": "post",
        "select": "channel",
        "channelId": {
          "mode": "name",
          "value": "#billing"
        },
        "text": "={{ 'Invoice issue for Stripe payment ' + ($('Payment Succeeded').first().json.data.object.id || 'unknown') + ': ' + ($json.error ? ('a step FAILED, so this invoice may be missing or incomplete (execution ' + $execution.id + '): ' + ($json.error.message || $json.error) + ($json.message ? ': ' + $json.message : '')) : 'no customer email on file, so the invoice was not emailed.') }}",
        "otherOptions": {}
      },
      "id": "slack-alert",
      "name": "Alert Billing Channel",
      "type": "n8n-nodes-base.slack",
      "typeVersion": 2.2,
      "position": [
        1660,
        820
      ],
      "onError": "stopWorkflow"
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "cond-has-email",
              "leftValue": "={{ !!$('Build Invoice Payload').item.json.customerEmail }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "if-has-email",
      "name": "Has Customer Email?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        1880,
        400
      ]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "cond-has-customer",
              "leftValue": "={{ !!$('Payment Succeeded').first().json.data.object.customer }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "has-stripe-customer",
      "name": "Has Stripe Customer?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        980,
        180
      ]
    }
  ],
  "connections": {
    "Payment Succeeded": {
      "main": [
        [
          {
            "node": "Set Invoice Defaults",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Set Invoice Defaults": {
      "main": [
        [
          {
            "node": "Has Billable Amount?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Has Billable Amount?": {
      "main": [
        [
          {
            "node": "Check Ledger for Event",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Skip Zero-Amount Payment",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Fetch Stripe Customer": {
      "main": [
        [
          {
            "node": "Build Invoice Payload",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Build Invoice Payload",
            "type": "main",
            "index": 0
          },
          {
            "node": "Alert Billing Channel",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build Invoice Payload": {
      "main": [
        [
          {
            "node": "PDFops Generate Invoice",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Alert Billing Channel",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "PDFops Generate Invoice": {
      "main": [
        [
          {
            "node": "Archive to S3",
            "type": "main",
            "index": 0
          },
          {
            "node": "Has Customer Email?",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Alert Billing Channel",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Archive to S3": {
      "main": [
        [
          {
            "node": "Log to Invoice Ledger",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Alert Billing Channel",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Has Customer Email?": {
      "main": [
        [
          {
            "node": "Email Invoice to Customer",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Alert Billing Channel",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check Ledger for Event": {
      "main": [
        [
          {
            "node": "Already Invoiced?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Already Invoiced?": {
      "main": [
        [
          {
            "node": "Skip Duplicate Event",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Has Stripe Customer?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Email Invoice to Customer": {
      "main": [
        [],
        [
          {
            "node": "Alert Billing Channel",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Log to Invoice Ledger": {
      "main": [
        [],
        [
          {
            "node": "Alert Billing Channel",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Has Stripe Customer?": {
      "main": [
        [
          {
            "node": "Fetch Stripe Customer",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Build Invoice Payload",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1"
  },
  "meta": {
    "templateCredsSetupCompleted": false
  }
}
