@cosmosapp/pay_sdkServidor
Receitas
Receitas práticas de ponta a ponta: checkout, doações, webhooks idempotentes, reconciliação e testnet/mainnet.
Soluções de copiar e colar para cenários comuns, montadas a partir das peças documentadas ao longo do restante desta documentação.
Padrões de ponta a ponta para copiar e colar. Todos os trechos de servidor pressupõem:
import { Client, Assets } from '@cosmosapp/pay_sdk';
const client = new Client({ apiKey: process.env.COSMOS_PAY_API_KEY });1. Checkout (o servidor cria, o navegador paga, o webhook confirma)
// server: create the intent for an order
export async function startCheckout(orderId: string, total: string) {
const intent = await client.paymentIntents.createPay({
destination: process.env.MERCHANT_ACCOUNT,
amount: total,
asset: Assets.USDC,
reference: orderId, // ties the intent to your order
msg: `Order ${orderId}`,
});
return intent.toJSON(); // → send to the browser
}// browser: complete it with the user's wallet
import { WebClient } from '@cosmosapp/pay_sdk/web';
const { txHash } = await new WebClient().pay(intentPayload);
await fetch('/api/confirm', { method: 'POST', body: JSON.stringify({ id: intentPayload.id, txHash }) });// server: fulfill on the webhook (don't trust the browser alone)
client.webhooks.on('paymentIntentSucceeded', async (event) => {
await markOrderPaid(event.data.reference, event.data.id);
});2. Doação / caixa de gorjetas (valor aberto)
const intent = await client.paymentIntents.createPay({
destination: process.env.MERCHANT_ACCOUNT,
asset: Assets.USDC, // no amount → the wallet asks the user
msg: 'Support us 💜',
});
// browser: await new WebClient().pay(intent, { amount: enteredAmount });3. Tratamento idempotente de webhooks
const processed = new Set<string>(); // use your DB in production
client.webhooks.on('event', (event) => {
if (processed.has(event.id)) return; // event.id is stable, so dedupe on it
processed.add(event.id);
handle(event);
});4. Reconciliar um pagamento no servidor
// You received a txHash out-of-band (e.g. polled the browser). Finalize it:
const outcome = await client.paymentIntents.validate(intentId, { txHash });
if (!outcome.valid) {
console.warn('payment not valid:', outcome.reason); // amount/destination/memo mismatch
}5. Testnet vs mainnet
import { Assets, TestnetAssets } from '@cosmosapp/pay_sdk';
// dv_ key → testnet → use TestnetAssets.USDC
// prod_ key → mainnet → use Assets.USDC
const asset = process.env.COSMOS_PAY_API_KEY.startsWith('prod_') ? Assets.USDC : TestnetAssets.USDC;6. Catálogo: produtos + clientes
const product = await client.products.create({ name: 'Pro', amount: '49.00', assetCode: 'USDC', kind: 'recurring' });
const customer = await client.customers.create({ name: 'Acme', email: 'billing@acme.com', account: 'G...' });
// then create intents referencing the customer's account as destination/source.Referências
- Client: O ponto de entrada principal do SDK, um único cliente atômico que expõe cada recurso por meio do seu próprio gerenciador (um design atômico de cliente único).
- WebClient
- Assets: Typed asset / wallet catalog or address helper.
- TestnetAssets: Typed asset / wallet catalog or address helper.