Nível 2 — Node.js / TypeScript

Cliente Node.js

A VorkPay expõe uma API REST padrão. Não há SDK oficial — basta um ficheiro com algumas funções fetch. Copia o exemplo abaixo para o teu projecto.

ℹ️ Em alternativa, podes descarregar um ZIP completo Node.js (cliente + webhook handler + exemplos) em Dashboard → Integrações → Node.js.

1. Variáveis de ambiente

VORKPAY_SECRET_KEY=vps_live_...
VORKPAY_WEBHOOK_SECRET=whsec_...

2. Cliente (lib/vorkpay.ts)

const BASE = "https://vorkpay.com/api/v1"

async function vp<T>(path: string, init: RequestInit = {}): Promise<T> {
  const res = await fetch(`${BASE}${path}`, {
    ...init,
    headers: {
      Authorization: `Bearer ${process.env.VORKPAY_SECRET_KEY}`,
      "Content-Type": "application/json",
      ...(init.headers || {}),
    },
  })
  if (!res.ok) {
    const body = await res.text().catch(() => "")
    throw new Error(`VorkPay ${res.status}: ${body}`)
  }
  return res.json() as Promise<T>
}

export const vorkpay = {
  init: (orderId: string, amount: number) =>
    vp<{ transactionId: string; amount: number; currency: string }>("/payments/init", {
      method: "POST",
      body: JSON.stringify({ orderId, amount }),
    }),

  mbway: (transactionId: string, phoneNumber: string) =>
    vp<{ status: string }>("/payments/mbway", {
      method: "POST",
      body: JSON.stringify({ transactionId, phoneNumber }),
    }),

  multibanco: (transactionId: string) =>
    vp<{ entity: string; reference: string; expiresAt: string; amount: number }>("/payments/multibanco", {
      method: "POST",
      body: JSON.stringify({ transactionId }),
    }),

  status: (transactionId: string) =>
    vp<{
      transactionId: string
      status: "pending" | "paid" | "failed" | "cancelled"
      paymentMethod: string | null
      paidAt: string | null
      mb?: { entity: string; reference: string; expiresAt: string }
    }>(`/payments/status?transactionId=${transactionId}`),
}

3. Criar pagamento

import { vorkpay } from "./lib/vorkpay"

const payment = await vorkpay.init("ORDER-123", 49.90)
console.log(payment.transactionId) // txn_xxx

4. MB WAY com polling

await vorkpay.mbway(payment.transactionId, "912345678")

// Polling até estar pago (máx ~4 minutos)
async function waitForPayment(txId: string, maxAttempts = 48) {
  for (let i = 0; i < maxAttempts; i++) {
    const s = await vorkpay.status(txId)
    if (s.status === "paid") return s
    if (s.status === "failed" || s.status === "cancelled") return s
    await new Promise(r => setTimeout(r, 5000))
  }
  throw new Error("Pagamento expirou")
}

const result = await waitForPayment(payment.transactionId)
console.log(result.status) // "paid"

5. Referência Multibanco

const mb = await vorkpay.multibanco(payment.transactionId)

console.log(mb.entity)    // "24000"
console.log(mb.reference) // "123456789"
console.log(mb.expiresAt) // ISO timestamp

// Mostra ao cliente: entidade + referência + valor

Métodos disponíveis

FunçãoDescrição
vorkpay.init(orderId, amount)Criar transacção
vorkpay.mbway(txId, phone)Accionar pagamento MB WAY
vorkpay.multibanco(txId)Gerar referência Multibanco
vorkpay.status(txId)Consultar estado