Eventos da Assinatura
curl --request GET \
--url https://garu.com.br/api/subscriptions/{id}/events \
--header 'Authorization: Bearer <token>'import requests
url = "https://garu.com.br/api/subscriptions/{id}/events"
headers = {"Authorization": "Bearer <token>"}
response = requests.get(url, headers=headers)
print(response.text)const options = {method: 'GET', headers: {Authorization: 'Bearer <token>'}};
fetch('https://garu.com.br/api/subscriptions/{id}/events', options)
.then(res => res.json())
.then(res => console.log(res))
.catch(err => console.error(err));<?php
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://garu.com.br/api/subscriptions/{id}/events",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => [
"Authorization: Bearer <token>"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}package main
import (
"fmt"
"net/http"
"io"
)
func main() {
url := "https://garu.com.br/api/subscriptions/{id}/events"
req, _ := http.NewRequest("GET", url, nil)
req.Header.Add("Authorization", "Bearer <token>")
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
fmt.Println(string(body))
}HttpResponse<String> response = Unirest.get("https://garu.com.br/api/subscriptions/{id}/events")
.header("Authorization", "Bearer <token>")
.asString();require 'uri'
require 'net/http'
url = URI("https://garu.com.br/api/subscriptions/{id}/events")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Get.new(url)
request["Authorization"] = 'Bearer <token>'
response = http.request(request)
puts response.read_body{
"id": 123,
"subscriptionId": 123,
"eventType": "<string>",
"eventData": {},
"gatewayEventId": {},
"createdAt": "<string>"
}Assinaturas
Eventos da Assinatura
Consulte o histórico de eventos e billing history de uma assinatura
GET
/
api
/
subscriptions
/
{id}
/
events
Eventos da Assinatura
curl --request GET \
--url https://garu.com.br/api/subscriptions/{id}/events \
--header 'Authorization: Bearer <token>'import requests
url = "https://garu.com.br/api/subscriptions/{id}/events"
headers = {"Authorization": "Bearer <token>"}
response = requests.get(url, headers=headers)
print(response.text)const options = {method: 'GET', headers: {Authorization: 'Bearer <token>'}};
fetch('https://garu.com.br/api/subscriptions/{id}/events', options)
.then(res => res.json())
.then(res => console.log(res))
.catch(err => console.error(err));<?php
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://garu.com.br/api/subscriptions/{id}/events",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => [
"Authorization: Bearer <token>"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}package main
import (
"fmt"
"net/http"
"io"
)
func main() {
url := "https://garu.com.br/api/subscriptions/{id}/events"
req, _ := http.NewRequest("GET", url, nil)
req.Header.Add("Authorization", "Bearer <token>")
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
fmt.Println(string(body))
}HttpResponse<String> response = Unirest.get("https://garu.com.br/api/subscriptions/{id}/events")
.header("Authorization", "Bearer <token>")
.asString();require 'uri'
require 'net/http'
url = URI("https://garu.com.br/api/subscriptions/{id}/events")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Get.new(url)
request["Authorization"] = 'Bearer <token>'
response = http.request(request)
puts response.read_body{
"id": 123,
"subscriptionId": 123,
"eventType": "<string>",
"eventData": {},
"gatewayEventId": {},
"createdAt": "<string>"
}Visão Geral
Consulte o histórico completo de eventos de uma assinatura, incluindo pagamentos, mudanças de status, períodos de teste e cancelamentos.Exemplo de Requisição
curl -X GET https://garu.com.br/api/subscriptions/100/events \
-H "Authorization: Bearer sk_test_sua_chave"
const response = await fetch(
'https://garu.com.br/api/subscriptions/100/events',
{
headers: {
'Authorization': `Bearer ${process.env.GARU_API_KEY}`
}
}
);
const events = await response.json();
events.forEach(event => {
console.log(`${event.createdAt}: ${event.eventType}`);
});
import requests
import os
url = "https://garu.com.br/api/subscriptions/100/events"
headers = {
"Authorization": f"Bearer {os.environ['GARU_API_KEY']}"
}
response = requests.get(url, headers=headers)
events = response.json()
for event in events:
print(f"{event['createdAt']}: {event['eventType']}")
Resposta de Sucesso (200 OK)
Os eventos vêm do mais novo para o mais antigo.[
{
"id": 789,
"subscriptionId": 100,
"eventType": "billing.success",
"eventData": {
"transactionId": 4321,
"billingCycle": 2,
"amount": "49.90",
"nextBillingDate": "2024-03-15T10:00:00.000Z"
},
"gatewayEventId": "208578400",
"createdAt": "2024-02-15T10:00:01.000Z"
},
{
"id": 788,
"subscriptionId": 100,
"eventType": "billing.failed",
"eventData": {
"retryCount": 1,
"error": "Saldo/limite insuficiente"
},
"gatewayEventId": "208571022",
"createdAt": "2024-02-08T10:00:01.000Z"
}
]
Tipos de Evento
| Tipo | Descrição |
|---|---|
subscription.created | Assinatura criada |
subscription.updated | Dados da assinatura atualizados |
subscription.cancel_scheduled | Cancelamento agendado para o fim do período |
subscription.reactivated | Cancelamento agendado desfeito |
subscription.canceled | Assinatura cancelada: na hora, por falhas de pagamento ou, no Pix Automático, pela autorização recusada ou cancelada no banco |
subscription.canceled_at_period_end | Assinatura cancelada no fim do período, por um cancelamento agendado |
subscription.paused | Assinatura pausada |
subscription.resumed | Assinatura retomada após pausa |
subscription.status_updated | O status mudou por um aviso do meio de pagamento |
billing.success | Pagamento confirmado |
billing.failed | Pagamento falhou; retryCount diz quantas falhas seguidas |
billing.max_retries_exceeded | As falhas chegaram ao limite, e a assinatura foi encerrada |
billing.webhook_missed_alert | O aviso de um pagamento esperado não chegou |
billing.auto_escalated_past_due | Sem o aviso de pagamento, a assinatura foi para past_due |
payment_method_updated | O cartão da assinatura foi trocado |
notification.renewal_reminder_sent | Lembrete de renovação enviado ao cliente |
notification.trial_ending_sent | Aviso de fim do período de teste enviado ao cliente |
Campos do Evento
Exemplo: Construindo um Billing History
async function getBillingHistory(subscriptionId) {
const response = await fetch(
`https://garu.com.br/api/subscriptions/${subscriptionId}/events`,
{
headers: {
'Authorization': `Bearer ${process.env.GARU_API_KEY}`
}
}
);
const events = await response.json();
// Filtrar apenas eventos de pagamento
const payments = events.filter(e =>
e.eventType === 'billing.success' || e.eventType === 'billing.failed'
);
return payments.map(payment => ({
date: payment.createdAt,
status: payment.eventType === 'billing.success' ? 'Pago' : 'Falhou',
// Só um pagamento confirmado traz o valor, como texto: "49.90"
amount: payment.eventData.amount ?? null,
error: payment.eventData.error ?? null
}));
}
// Uso
const history = await getBillingHistory(100);
console.log('Histórico de Pagamentos:');
history.forEach(p => {
const detail = p.amount ? `R$ ${p.amount}` : p.error;
console.log(`${p.date}: ${p.status} - ${detail}`);
});
Próximos Passos
Detalhes da Assinatura
Consulte os detalhes completos da assinatura
Webhooks
Receba eventos em tempo real
Was this page helpful?