{
  "name": "Payment Gateway - IPN Handler",
  "nodes": [
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "payment-ipn",
        "options": {}
      },
      "name": "Webhook",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 1,
      "position": [
        0,
        0
      ]
    },
    {
      "parameters": {
        "jsCode": "const headers = $json.headers || {}; const sig = headers['x-nowpayments-sig'] || headers['X-NOWPAYMENTS-SIG'] || ''; const body = $json.body || {}; function sortObject(obj){ return Object.keys(obj).sort().reduce((r,k)=>{ const v = obj[k]; r[k] = v && typeof v === 'object' && !Array.isArray(v) ? sortObject(v) : v; return r; },{}); } let valid = false; const secret = $env.NOWPAYMENTS_IPN_SECRET || ''; if (secret && sig) { const crypto = require('crypto'); const payload = JSON.stringify(sortObject(body)); const hmac = crypto.createHmac('sha512', secret); hmac.update(payload); const expected = hmac.digest('hex'); valid = expected === sig; } return { json: { ...$json, ipnValid: valid } };"
      },
      "name": "Validate IPN Signature",
      "type": "n8n-nodes-base.code",
      "typeVersion": 1,
      "position": [
        120,
        0
      ]
    },
    {
      "parameters": {
        "conditions": {
          "boolean": [
            {
              "value1": "={{$json.ipnValid}}",
              "operation": "isTrue"
            }
          ]
        }
      },
      "name": "Is Signature Valid",
      "type": "n8n-nodes-base.if",
      "typeVersion": 1,
      "position": [
        200,
        0
      ]
    },
    {
      "parameters": {
        "conditions": {
          "string": [
            {
              "value1": "={{$json.body.payment_status}}",
              "operation": "equal",
              "value2": "finished"
            },
            {
              "value1": "={{$json.body.payment_status}}",
              "operation": "equal",
              "value2": "confirmed"
            }
          ]
        },
        "combineOperation": "any"
      },
      "name": "Check Status",
      "type": "n8n-nodes-base.if",
      "typeVersion": 1,
      "position": [
        380,
        0
      ]
    },
    {
      "parameters": {
        "url": "={{($env.API_URL || 'https://academicchain-ledger.onrender.com')}}/api/credits/add",
        "method": "POST",
        "jsonParameters": true,
        "options": {},
        "bodyParametersUi": {
          "parameter": [
            {
              "name": "orderId",
              "value": "={{$json.body.order_id}}"
            },
            {
              "name": "amount",
              "value": "={{$json.body.price_amount}}"
            },
            {
              "name": "currency",
              "value": "={{$json.body.price_currency}}"
            }
          ]
        },
        "headerParametersUi": {
          "parameter": [
            {
              "name": "x-acl-auth-key",
              "value": "={{$env.ACL_AUTH_KEY || ''}}"
            },
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        }
      },
      "name": "Add Credits",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 1,
      "position": [
        580,
        0
      ]
    },
    {
      "parameters": {
        "subject": "Payment Received",
        "text": "Payment {{$json.body.payment_id}} confirmed. Amount: {{$json.body.price_amount}} {{$json.body.price_currency}}",
        "toEmail": "admin@academicchain.com"
      },
      "name": "Send Email",
      "type": "n8n-nodes-base.emailSend",
      "typeVersion": 1,
      "position": [
        780,
        0
      ]
    },
    {
      "parameters": {
        "message": "\ud83d\udcb0 Payment Confirmed: {{$json.body.payment_id}}",
        "options": {
          "level": "info"
        }
      },
      "name": "Registro de \u00e9xito",
      "type": "n8n-nodes-base.logger",
      "typeVersion": 1,
      "position": [
        780,
        200
      ]
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "{\"success\": true, \"message\": \"IPN processed successfully\", \"orderId\": \"{{$json.body.order_id}}\", \"paymentId\": \"{{$json.body.payment_id}}\"}",
        "options": {
          "responseCode": 200
        }
      },
      "name": "Responder \u00e9xito",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1,
      "position": [
        980,
        0
      ]
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "{\"success\": false, \"message\": \"Invalid IPN signature\"}",
        "options": {
          "responseCode": 401
        }
      },
      "name": "Reject Invalid",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1,
      "position": [
        380,
        200
      ]
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "{\"success\": true, \"message\": \"IPN ignored (status not finished/confirmed)\"}",
        "options": {
          "responseCode": 200
        }
      },
      "name": "Ignore Status",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1,
      "position": [
        580,
        200
      ]
    }
  ],
  "connections": {
    "Webhook": {
      "main": [
        [
          {
            "node": "Validate IPN Signature",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Validate IPN Signature": {
      "main": [
        [
          {
            "node": "Is Signature Valid",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Is Signature Valid": {
      "main": [
        [
          {
            "node": "Check Status",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Reject Invalid",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check Status": {
      "main": [
        [
          {
            "node": "Add Credits",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Ignore Status",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Add Credits": {
      "main": [
        [
          {
            "node": "Send Email",
            "type": "main",
            "index": 0
          },
          {
            "node": "Registro de \u00e9xito",
            "type": "main",
            "index": 0
          },
          {
            "node": "Responder \u00e9xito",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}