/** * JPSIS Pay — SDK de micro-transações para os sistemas (MikroSDN, MikroERP, RadioBox…) * rodando na cloud dedicada. Roda no BACKEND do sistema. * * Usa os mesmos arquivos do jpsis-client.ts (/etc/jpsis/license.json + license.key): * o sistema se autentica com o certificado da licença — não existe chave de API para guardar. * * Dependência única: `jose` (npm i jose). * * const pay = new JpsisPay(); * * // 1) logo após o login SSO (jpsis.finishLogin): * const { payToken } = await pay.openSession(login.accessToken); // guarde na sessão do usuário (12 h) * * // 2) quando o usuário comprar algo: * const charge = await pay.charge({ payToken, amount: 150, description: "Relatório avançado", reference: "rel-8812" }); * if (charge.status === "succeeded") liberar(); // pagamento rápido: já pago * else mostrarConfirmacao(charge); // tela de confirmação DENTRO do sistema * * // 3) quando ele clicar em "Pagar" na sua tela: * await pay.confirm({ payToken, chargeId: charge.id, quickPay: { limit: 2000 } }); // quickPay é opcional */ import { randomUUID } from "node:crypto"; import { readFileSync } from "node:fs"; import { importPKCS8, SignJWT } from "jose"; export type ChargeStatus = "requires_confirmation" | "succeeded" | "canceled" | "expired" | "refunded" | "partially_refunded"; export type Charge = { id: string; object: "charge"; status: ChargeStatus; /** centavos (R$ 1,50 = 150) */ amount: number; amount_refunded: number; currency: "brl"; description: string; reference: string; user_id: string; license_id: string; capture_method: "allowance" | "confirmation" | null; metadata: Record; expires_at: string; succeeded_at: string | null; created_at: string; }; export type WalletInfo = { object: "wallet"; user_id: string; balance: number; currency: "brl"; quick_pay: { limit: number; max_per_charge: number; period: "day" | "week" | "month"; remaining: number } | null; /** Página da carteira no hub, para o usuário adicionar saldo. */ topup_url: string; }; export class JpsisPayError extends Error { constructor( public code: string, message: string, public status: number, ) { super(message); } } type Conf = { instanceId: string; hubUrl: string; privateKey: string }; export class JpsisPay { private conf: Conf; private keyPem: string; constructor(opts: { configPath?: string } = {}) { this.conf = JSON.parse(readFileSync(opts.configPath ?? "/etc/jpsis/license.json", "utf8")); this.keyPem = readFileSync(this.conf.privateKey, "utf8"); } private url(path: string) { return this.conf.hubUrl.replace(/\/$/, "") + path; } /** client_assertion (RFC 7523) — igual ao jpsis-client.ts. */ private async assertion(audience: string) { const key = await importPKCS8(this.keyPem, "RS256"); return new SignJWT({}) .setProtectedHeader({ alg: "RS256", typ: "JWT" }) .setIssuer(this.conf.instanceId) .setSubject(this.conf.instanceId) .setAudience(audience) .setIssuedAt() .setExpirationTime("2m") .setJti(randomUUID()) .sign(key); } private async post(path: string, body: Record): Promise { const url = this.url(path); const res = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ ...body, client_id: this.conf.instanceId, client_assertion_type: "urn:ietf:params:oauth:client-assertion-type:jwt-bearer", client_assertion: await this.assertion(url), }), }); const json = (await res.json().catch(() => ({}))) as T & { error?: string; error_description?: string }; if (!res.ok) throw new JpsisPayError(json.error ?? "http_error", json.error_description ?? res.statusText, res.status); return json; } /** Troca o access_token do login SSO por um pay_token de 12 h. Guarde-o na sessão do usuário. */ async openSession(accessToken: string) { const r = await this.post<{ pay_token: string; expires_in: number; user_id: string }>("/api/pay/v1/session", { access_token: accessToken }); return { payToken: r.pay_token, expiresAt: new Date(Date.now() + r.expires_in * 1000), userId: r.user_id }; } /** Saldo do usuário + pagamento rápido ativo para este sistema. */ wallet(payToken: string) { return this.post("/api/pay/v1/wallet", { pay_token: payToken }); } /** * Cria a cobrança. `reference` é a sua chave de idempotência (ex.: id do pedido): * repetir a chamada com a mesma reference devolve a mesma cobrança. */ charge(p: { payToken: string; amount: number; description: string; reference: string; metadata?: Record }) { return this.post("/api/pay/v1/charges", { pay_token: p.payToken, amount: p.amount, description: p.description, reference: p.reference, metadata: p.metadata, }); } /** * Confirma a cobrança depois que o usuário clicou em "Pagar" na SUA tela. * `quickPay` ativa o pagamento rápido: as próximas cobranças dentro do limite saem sem confirmação. */ confirm(p: { payToken: string; chargeId: string; quickPay?: { limit: number; maxPerCharge?: number; period?: "day" | "week" | "month" } }) { return this.post("/api/pay/v1/charges/confirm", { pay_token: p.payToken, charge_id: p.chargeId, quick_pay_limit: p.quickPay?.limit, quick_pay_max_per_charge: p.quickPay?.maxPerCharge, quick_pay_period: p.quickPay?.period, }); } cancel(chargeId: string) { return this.post("/api/pay/v1/charges/cancel", { charge_id: chargeId }); } /** Estorno total (sem amount) ou parcial. O valor volta para a carteira do usuário. */ refund(chargeId: string, amount?: number) { return this.post("/api/pay/v1/charges/refund", { charge_id: chargeId, amount }); } retrieve(q: { chargeId?: string; reference?: string }) { return this.post("/api/pay/v1/charges/retrieve", { charge_id: q.chargeId, reference: q.reference }); } } /* ─────────────────────────── Exemplo com Express ─────────────────────────── import express from "express"; const app = express(); const pay = new JpsisPay(); // depois do jpsis.finishLogin(...): req.session.payToken = (await pay.openSession(r.accessToken)).payToken; app.post("/api/compras", express.json(), async (req, res) => { const charge = await pay.charge({ payToken: req.session.payToken, amount: 150, description: "Relatório avançado", reference: `rel-${req.body.reportId}-${req.session.userId}`, }); res.json(charge); // o navegador abre o JpsisPaySheet se status = requires_confirmation }); app.post("/api/compras/:id/confirmar", express.json(), async (req, res) => { try { const charge = await pay.confirm({ payToken: req.session.payToken, chargeId: req.params.id, quickPay: req.body.quickPay }); res.json(charge); } catch (e) { res.status(e.status ?? 500).json({ error: e.code, message: e.message }); } }); app.get("/api/carteira", async (req, res) => res.json(await pay.wallet(req.session.payToken))); ──────────────────────────────────────────────────────────────────────────── */