Criar assinatura
curl --request POST \
--url https://api.sandbox.z2pay.com/v1/subscriptions \
--header 'Content-Type: application/json' \
--header 'x-api-key: <api-key>' \
--data '
{
"customerId": "<string>",
"planId": "<string>",
"items": [],
"currency": "<string>",
"splitConfig": [
{
"recipientId": "<string>",
"value": 1.01,
"type": "sale",
"processingFee": true,
"liable": true
}
],
"collectionMethod": "charge_automatically",
"collectionTiming": "prepaid",
"invoiceGenerationMode": "just_in_time",
"paymentBehavior": "allow_incomplete",
"enrollmentInstallments": 6,
"enrollmentItems": [
{
"description": "<string>",
"amount": 1,
"quantity": 1
}
],
"maxCycles": 1,
"metadata": {},
"referenceCode": "<string>",
"startAt": "2023-11-07T05:31:56Z"
}
'const options = {
method: 'POST',
headers: {'x-api-key': '<api-key>', 'Content-Type': 'application/json'},
body: JSON.stringify({
customerId: '<string>',
planId: '<string>',
items: [],
currency: '<string>',
splitConfig: [
{
recipientId: '<string>',
value: 1.01,
type: 'sale',
processingFee: true,
liable: true
}
],
collectionMethod: 'charge_automatically',
collectionTiming: 'prepaid',
invoiceGenerationMode: 'just_in_time',
paymentBehavior: 'allow_incomplete',
enrollmentInstallments: 6,
enrollmentItems: [{description: '<string>', amount: 1, quantity: 1}],
maxCycles: 1,
metadata: {},
referenceCode: '<string>',
startAt: '2023-11-07T05:31:56Z'
})
};
fetch('https://api.sandbox.z2pay.com/v1/subscriptions', options)
.then(res => res.json())
.then(res => console.log(res))
.catch(err => console.error(err));import requests
url = "https://api.sandbox.z2pay.com/v1/subscriptions"
payload = {
"customerId": "<string>",
"planId": "<string>",
"items": [],
"currency": "<string>",
"splitConfig": [
{
"recipientId": "<string>",
"value": 1.01,
"type": "sale",
"processingFee": True,
"liable": True
}
],
"collectionMethod": "charge_automatically",
"collectionTiming": "prepaid",
"invoiceGenerationMode": "just_in_time",
"paymentBehavior": "allow_incomplete",
"enrollmentInstallments": 6,
"enrollmentItems": [
{
"description": "<string>",
"amount": 1,
"quantity": 1
}
],
"maxCycles": 1,
"metadata": {},
"referenceCode": "<string>",
"startAt": "2023-11-07T05:31:56Z"
}
headers = {
"x-api-key": "<api-key>",
"Content-Type": "application/json"
}
response = requests.post(url, json=payload, headers=headers)
print(response.text){
"id": "sub_hsm2kigu74htdxj3nw2z6f9xw",
"number": {
"sequence": 43
},
"referenceCode": "CONTRATO-2026-0042",
"customerId": "cust_c72q6ogr9iko0we85mqal04te",
"customerEmail": "maria.silva@example.com",
"customerName": "Maria Silva",
"customerDocument": "12345678909",
"currency": "BRL",
"status": "active",
"billingGroupId": null,
"currentPeriodStart": "2025-06-29T03:00:00.000Z",
"currentPeriodEnd": "2025-07-29T03:00:00.000Z",
"nextInvoiceAt": "2025-07-29T03:00:00.000Z",
"recurrence": {
"interval": 1,
"unit": "month",
"anchor": "subscription_start",
"collectionTiming": "prepaid"
},
"collectionMethod": "charge_automatically",
"collectionTiming": "prepaid",
"invoiceGenerationMode": "just_in_time",
"cancelAtPeriodEnd": false,
"canceledAt": null,
"endedAt": null,
"cancellationReason": null,
"pausedAt": null,
"pauseResumesAt": null,
"pauseReason": null,
"trialEnd": null,
"incompleteExpiresAt": null,
"trialRemindersFired": [],
"maxCycles": null,
"issuedCycles": 0,
"completedCycles": 0,
"defaultPaymentMethodRef": {
"id": "crd_tsj66oabsygc9kwvvzt8189f9",
"type": "card"
},
"splitConfig": null,
"paymentBehavior": "allow_incomplete",
"latestInvoiceId": null,
"paymentUpdateToken": null,
"paymentUpdateMethods": null,
"metadata": {},
"createdAt": "2025-06-29T13:45:30.000Z",
"updatedAt": "2025-06-29T13:45:30.000Z"
}{
"error": {
"code": "VALIDATION_ERROR",
"message": "Validation failed",
"issues": [
{
"path": "status",
"message": "Status inválido. Valores aceitos: pending, waiting_payment, paid, refused, canceled, refunded"
},
{
"path": "startDate",
"message": "Data deve ser ISO 8601 com timezone (ex.: 2026-06-24T00:00:00Z)"
}
]
}
}{
"error": {
"code": "UNAUTHORIZED",
"message": "Invalid API key"
}
}{
"error": {
"code": "NOT_FOUND",
"message": "Subscription not found"
}
}{
"error": {
"code": "CONFLICT",
"message": "No refundable payment found"
}
}{
"error": "Idempotency key already used with a different request body"
}Assinaturas
Criar assinatura
Instancia o contrato recorrente de um cliente, a partir de um plano ou de itens avulsos.
POST
/
subscriptions
Criar assinatura
curl --request POST \
--url https://api.sandbox.z2pay.com/v1/subscriptions \
--header 'Content-Type: application/json' \
--header 'x-api-key: <api-key>' \
--data '
{
"customerId": "<string>",
"planId": "<string>",
"items": [],
"currency": "<string>",
"splitConfig": [
{
"recipientId": "<string>",
"value": 1.01,
"type": "sale",
"processingFee": true,
"liable": true
}
],
"collectionMethod": "charge_automatically",
"collectionTiming": "prepaid",
"invoiceGenerationMode": "just_in_time",
"paymentBehavior": "allow_incomplete",
"enrollmentInstallments": 6,
"enrollmentItems": [
{
"description": "<string>",
"amount": 1,
"quantity": 1
}
],
"maxCycles": 1,
"metadata": {},
"referenceCode": "<string>",
"startAt": "2023-11-07T05:31:56Z"
}
'const options = {
method: 'POST',
headers: {'x-api-key': '<api-key>', 'Content-Type': 'application/json'},
body: JSON.stringify({
customerId: '<string>',
planId: '<string>',
items: [],
currency: '<string>',
splitConfig: [
{
recipientId: '<string>',
value: 1.01,
type: 'sale',
processingFee: true,
liable: true
}
],
collectionMethod: 'charge_automatically',
collectionTiming: 'prepaid',
invoiceGenerationMode: 'just_in_time',
paymentBehavior: 'allow_incomplete',
enrollmentInstallments: 6,
enrollmentItems: [{description: '<string>', amount: 1, quantity: 1}],
maxCycles: 1,
metadata: {},
referenceCode: '<string>',
startAt: '2023-11-07T05:31:56Z'
})
};
fetch('https://api.sandbox.z2pay.com/v1/subscriptions', options)
.then(res => res.json())
.then(res => console.log(res))
.catch(err => console.error(err));import requests
url = "https://api.sandbox.z2pay.com/v1/subscriptions"
payload = {
"customerId": "<string>",
"planId": "<string>",
"items": [],
"currency": "<string>",
"splitConfig": [
{
"recipientId": "<string>",
"value": 1.01,
"type": "sale",
"processingFee": True,
"liable": True
}
],
"collectionMethod": "charge_automatically",
"collectionTiming": "prepaid",
"invoiceGenerationMode": "just_in_time",
"paymentBehavior": "allow_incomplete",
"enrollmentInstallments": 6,
"enrollmentItems": [
{
"description": "<string>",
"amount": 1,
"quantity": 1
}
],
"maxCycles": 1,
"metadata": {},
"referenceCode": "<string>",
"startAt": "2023-11-07T05:31:56Z"
}
headers = {
"x-api-key": "<api-key>",
"Content-Type": "application/json"
}
response = requests.post(url, json=payload, headers=headers)
print(response.text){
"id": "sub_hsm2kigu74htdxj3nw2z6f9xw",
"number": {
"sequence": 43
},
"referenceCode": "CONTRATO-2026-0042",
"customerId": "cust_c72q6ogr9iko0we85mqal04te",
"customerEmail": "maria.silva@example.com",
"customerName": "Maria Silva",
"customerDocument": "12345678909",
"currency": "BRL",
"status": "active",
"billingGroupId": null,
"currentPeriodStart": "2025-06-29T03:00:00.000Z",
"currentPeriodEnd": "2025-07-29T03:00:00.000Z",
"nextInvoiceAt": "2025-07-29T03:00:00.000Z",
"recurrence": {
"interval": 1,
"unit": "month",
"anchor": "subscription_start",
"collectionTiming": "prepaid"
},
"collectionMethod": "charge_automatically",
"collectionTiming": "prepaid",
"invoiceGenerationMode": "just_in_time",
"cancelAtPeriodEnd": false,
"canceledAt": null,
"endedAt": null,
"cancellationReason": null,
"pausedAt": null,
"pauseResumesAt": null,
"pauseReason": null,
"trialEnd": null,
"incompleteExpiresAt": null,
"trialRemindersFired": [],
"maxCycles": null,
"issuedCycles": 0,
"completedCycles": 0,
"defaultPaymentMethodRef": {
"id": "crd_tsj66oabsygc9kwvvzt8189f9",
"type": "card"
},
"splitConfig": null,
"paymentBehavior": "allow_incomplete",
"latestInvoiceId": null,
"paymentUpdateToken": null,
"paymentUpdateMethods": null,
"metadata": {},
"createdAt": "2025-06-29T13:45:30.000Z",
"updatedAt": "2025-06-29T13:45:30.000Z"
}{
"error": {
"code": "VALIDATION_ERROR",
"message": "Validation failed",
"issues": [
{
"path": "status",
"message": "Status inválido. Valores aceitos: pending, waiting_payment, paid, refused, canceled, refunded"
},
{
"path": "startDate",
"message": "Data deve ser ISO 8601 com timezone (ex.: 2026-06-24T00:00:00Z)"
}
]
}
}{
"error": {
"code": "UNAUTHORIZED",
"message": "Invalid API key"
}
}{
"error": {
"code": "NOT_FOUND",
"message": "Subscription not found"
}
}{
"error": {
"code": "CONFLICT",
"message": "No refundable payment found"
}
}{
"error": "Idempotency key already used with a different request body"
}POST /subscriptions
Faz parte do recurso Assinaturas — o conceito, os dez estados e a máquina de
transições estão lá.
Cria a assinatura e coloca o motor de cobrança para funcionar. A partir daqui, quem emite fatura e
quem cobra é a Z2Pay, no ritmo da recorrência configurada.
Informe exatamente um entre
customerId e customer. Enviar os dois, ou nenhum, responde
400. O customer inline cria o cadastro na hora ou reaproveita um existente, casando primeiro
pelo documento e depois pelo e-mail — é o atalho para quem ainda não tem o cust_.Informe
planId, items, ou os dois. Sem nenhum dos dois não há o que cobrar. Com os dois, os
itens recorrentes do plano entram e os de items se somam a eles.Quando todos os itens são avulsos, recurrence e currency passam a ser obrigatórios: não há
preço de onde derivá-los.O estado inicial não se escolhe
Não existe campostatus no corpo. O estado em que a assinatura nasce é decidido pela combinação
que você envia, avaliada nesta ordem:
| O que você envia | Nasce como |
|---|---|
defaultPaymentMethodRef de Pix Automático (o QR da autorização já pagou a 1ª fatura) | active |
enrollmentItems | pending_enrollment |
trialSpec com requiresPaymentMethod e sem forma de pagamento | incomplete, com prazo |
trialSpec nos demais casos | trialing |
Nada disso, com defaultPaymentMethodRef | active |
Nada disso, sem defaultPaymentMethodRef | incomplete, sem prazo |
trialing vence a forma de pagamento. Com trialSpec, a assinatura entra em teste mesmo com
o cartão já cadastrado — e a primeira fatura só nasce quando o teste acaba. Se você esperava
cobrança imediata, não envie trialSpec.pending_enrollment tem prazo; incomplete quase nunca. A adesão precisa ser paga dentro da
janela da conta (7 dias por padrão) ou a assinatura é cancelada. Já a incomplete só expira
quando nasceu de um teste com requiresPaymentMethod — cerca de 23 horas. A incomplete comum
fica parada até alguém agir. Ver Do incomplete ao active.Formas de pagamento
EmdefaultPaymentMethodRef, o type diz o meio e o resto diz qual:
- cartão novo — tokenize com o Tokenizer SDK e envie o
tok_emtoken. O cartão é salvo na carteira do cliente antes de virar o padrão; - cartão já salvo — envie o
crd_emcardId. Ele precisa pertencer ao cliente da assinatura, senão responde409; - PIX ou boleto — só o
type, semtokennemcardId; - Pix Automático —
type: "pix_automatic"e a autorizaçãopxa_emid. A autorização precisa estaractive(o pagador já pagou o QR e autorizou), ser do cliente da assinatura e não servir outra assinatura; a assinatura, ter a mesma periodicidade dela. O QR quita a 1ª fatura — a do 1º ciclo, se o valor for o do ciclo; senão, uma adesão desse valor, e as mensalidades começam no ciclo seguinte. As regras e o fluxo completo estão em Pix Automático.
Duas combinações são recusadas com
409:enrollmentItemssemdefaultPaymentMethodRef— a adesão precisa de como ser cobrada;trialSpecjunto comenrollmentItems— são opostos: um adia a cobrança, o outro a antecipa.
Com
pix_automatic, a autorização precisa estar pronta, senão a resposta é 409 e nada é
criado:- ainda
pending— espere o webhookpix_authorization.activated; - ativa, mas com o pagamento do QR ainda não confirmado — a ativação e o pagamento chegam do
banco com segundos de diferença; tente de novo em seguida. O mesmo
409vale para um QR estornado, e aí a autorização não serve mais para abrir assinatura; - de outro cliente, encerrada ou já vinculada a outra assinatura.
pix_automatic é recusado com 409 quando a assinatura não cabe no que se debita sozinho, e
nenhuma assinatura é criada:- recorrência diária — só semanal, mensal (inclusive trimestral e semestral) e anual;
collectionTiming: "postpaid"ouinvoiceGenerationMode: "upfront"— o débito sai da fatura emitida antes do vencimento, e ela só existe com cobrança no início do ciclo e uma fatura por ciclo. OmaxCyclesem si é aceito;trialSpeccomdurationDaysmaior que zero — período de teste e Pix Automático não se combinam;frequencyda autorização diferente da recorrência da assinatura.
referenceCode é o seu identificador do contrato. Volta nas respostas e é filtrável por
correspondência exata na listagem. Não é único: a Z2Pay não recusa
dois contratos com o mesmo código.upfront emite tudo de uma vez. Com invoiceGenerationMode: "upfront", todas as maxCycles
faturas nascem na criação, cada uma com o seu vencimento — e maxCycles passa a ser obrigatório.
O padrão, just_in_time, emite uma fatura por ciclo, na virada.Exemplo
curl -X POST https://api.sandbox.z2pay.com/v1/subscriptions \
-H "x-api-key: SUA_CHAVE_DE_SANDBOX" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: e6c9b2a4-1f3d-4a7b-9c2e-0d8f1a2b3c4d" \
-d '{
"customerId": "cust_eqjzf65crxsrywqdfptanl7yp",
"planId": "plan_lhutpqeq2ml3stia4vn90xars",
"referenceCode": "contrato-2026-0042",
"defaultPaymentMethodRef": {
"type": "card",
"cardId": "crd_d6bvtkpr7fd4jrb3tbpm8ohqi"
}
}'
Resposta 201
{
"id": "sub_x33m4yn6brazh71en4mki6f5c",
"number": { "sequence": 42 },
"referenceCode": "contrato-2026-0042",
"customerId": "cust_eqjzf65crxsrywqdfptanl7yp",
"status": "active",
"currency": "BRL",
"collectionMethod": "charge_automatically",
"collectionTiming": "prepaid",
"invoiceGenerationMode": "just_in_time",
"recurrence": {
"interval": 1,
"unit": "month",
"anchor": "subscription_start",
"collectionTiming": "prepaid"
},
"cancelAtPeriodEnd": false,
"maxCycles": null,
"currentPeriodStart": "2026-08-10T12:00:00.000Z",
"currentPeriodEnd": "2026-09-10T12:00:00.000Z",
"nextInvoiceAt": "2026-09-10T12:00:00.000Z",
"items": [
{
"id": "subi_wq3n8fk52hbdzr7m0aeypvcjt",
"subscriptionId": "sub_x33m4yn6brazh71en4mki6f5c",
"planItemId": "pli_oaimno59ai3uuqwq0ti7gxs0j",
"priceVersionId": "price_l1r8693wk6ksbd9044bwvwu93",
"name": "Assinatura Pro",
"unitAmount": 9900,
"quantity": 1
}
]
}
O exemplo está abreviado — o playground ao lado mostra o corpo inteiro.
Body
application/json
O que fazer quando a primeira cobrança da assinatura não é aprovada. allow_incomplete (default) cria a assinatura mesmo assim, com a fatura em aberto e a régua de cobrança seguindo. error_if_incomplete cancela a assinatura quando a primeira cobrança falha — use quando não fizer sentido manter um contrato que nunca chegou a ser pago.
Available options:
allow_incomplete, error_if_incomplete Response
Assinatura criada