Skip to main content

Pix Payment Agent

The simplest agent you can build with CodeSpar. Create a Pix charge, generate a QR code, and send it to the customer via WhatsApp — in ~50 lines of code.

1 min read · updated
View MarkdownEdit on GitHub
TIME
~10 min
PROVIDER
OpenAIgpt-4o
SERVERS
asaastwilio

Create a Pix charge, generate the QR code, and send it to the customer via WhatsApp. The simplest agent you can build with CodeSpar — two steps, one conversation.

THE FLOW
Two steps, one conversation
1
Create Pix charge
codespar_pay
Routed to Asaas — QR code + copy-paste key
2
Send via WhatsApp
codespar_notify
Routed to Twilio — instant delivery
WHAT YOUR CUSTOMER GETS
R$ 150,00 · Pro Plan

Conversation preview

What the agent does when you call pixAgent("+5511...", 15000, "Pro Plan").

agent · payment assistant
sb_pix_a3
Create a Pix payment of R$150 for Pro Plan - Monthly and send to +5511999887766.
Vou gerar o Pix de R$ 150,00 e enviar o QR code no WhatsApp.
Pronto. Pix criado (txn_abc123) e QR code enviado para o WhatsApp do cliente. Pagamento aguardando.
codespar_payasaas✓ done620ms
codespar_notifytwilio✓ done340ms
2 tool calls · 960ms total · 2 LLM iterationsRun this cookbook in Sandbox →

Prerequisites

Install the SDK and the OpenAI provider adapter:

npm install @codespar/sdk @codespar/openai openai

Set your environment variables:

.env
CODESPAR_API_KEY=csk_live_...
OPENAI_API_KEY=sk-...

You'll need active accounts on Asaas and Twilio. CodeSpar will prompt you to authenticate both on first run.

Full agent code

pix-agent.ts
import OpenAI from "openai";
import { CodeSpar } from "@codespar/sdk";
import { getTools, handleToolCall } from "@codespar/openai";

const openai = new OpenAI();
const codespar = new CodeSpar({ apiKey: process.env.CODESPAR_API_KEY });

async function pixAgent(phone: string, amount: number, description: string) {
  const session = await codespar.create("user_123", {
    servers: ["asaas", "twilio"],
  });

  try {
    const tools = await getTools(session);

    const messages = [
      { role: "system", content: "You are a Brazilian payment assistant..." },
      {
        role: "user",
        content: `Create Pix of R$${amount / 100} for "${description}", send to ${phone}`,
      },
    ];

    let response = await openai.chat.completions.create({ model: "gpt-4o", tools, messages });
    while (response.choices[0].message.tool_calls?.length) {
      // ... handle tool calls, feed results back, call LLM again
    }

    return response.choices[0].message.content;
  } finally {
    await session.close();
  }
}

Variations

Add boleto fallback

Pass payment_methods: ["pix", "boleto"] to codespar_pay and let the customer pick at checkout.

Chain an invoice

After payment confirmation, chain codespar_invoice to issue an NF-e automatically.

Swap to Claude

Replace @codespar/openai with @codespar/claude. The agent logic is identical.

Python version

For FastAPI services or async jobs, the same flow in Python — no framework-adapter needed, session.send() runs the agent loop on the backend:

pix_agent.py
from codespar import CodeSpar

cs = CodeSpar()  # reads CODESPAR_API_KEY

def pix_agent(phone: str, amount: int, description: str) -> str:
    with cs.create("user_123", servers=["asaas", "twilio"]) as session:
        result = session.send(
            f'Create a Pix of R${amount / 100:.2f} for "{description}", '
            f"send the QR code to {phone} via WhatsApp."
        )
    return result.message

Swap CodeSpar for AsyncCodeSpar and with for async with to run inside FastAPI. See Quickstart (Python).

Next steps

Edit on GitHub

Last updated on