=============== LIBRARY RULES =============== From library maintainers: - Base URL: https://api.qpay.com.br - Autentique requests com Bearer token no header Authorization - Inclua X-Workspace-Id em TODAS as requisições (exceto auth e públicas) - Use Idempotency-Key em POST para evitar duplicação de pagamentos - Valores monetários são SEMPRE em centavos (R$10.00 = 1000) - Moeda padrão é BRL (Real Brasileiro) - Dados de cartão DEVEM ser tokenizados antes do pagamento (PCI DSS) - NUNCA armazene números de cartão - use tokens - PIX: criar pagamento → processar → retorna QR Code - Cartão: tokenizar → criar pagamento → processar - Valide assinatura de webhooks com HMAC-SHA256 - Webhooks têm retry automático (6 tentativas) - Assinaturas suportam trial period e múltiplos intervalos - Checkout público não requer autenticação - Payment links suportam valor fixo, mínimo ou definido pelo cliente ### Implement Complete Checkout Flow using JavaScript Source: https://context7.com/qpaydev/qpay-docs/llms.txt This snippet demonstrates how to implement the complete checkout flow using JavaScript and the axios library. It covers fetching payment link details, creating a checkout session, and completing the checkout with a payment method. Ensure you have axios installed and necessary browser APIs like `navigator.userAgent` and `document.referrer` available. ```javascript const axios = require('axios'); // Client-side checkout implementation async function completeCheckoutFlow(linkSlug, customerData) { try { // Step 1: Get payment link details (no authentication required) const linkResponse = await axios.get( `https://api.qpay.com.br/api/public/checkout/links/${linkSlug}` ); const linkData = linkResponse.data; console.log('Payment Link:', linkData.linkId); console.log('Amount:', linkData.amountType); console.log('Allowed Methods:', linkData.allowedPaymentMethods); // Step 2: Create checkout session const sessionResponse = await axios.post( 'https://api.qpay.com.br/api/public/checkout/sessions', { linkId: linkData.linkId, customerEmail: customerData.email, amount: linkData.amountType === 'CUSTOMER_CHOOSES' ? 5000 : undefined, customerData: { name: customerData.name, phone: customerData.phone, cpf: customerData.cpf }, utmParams: { utm_source: 'google', utm_medium: 'cpc', utm_campaign: 'product_launch' }, metadata: { browser: navigator.userAgent, referrer: document.referrer } } ); const session = sessionResponse.data; console.log('Session Created:', session.sessionId); console.log('Amount:', session.amount); console.log('Expires At:', session.expiresAt); // Step 3: Complete checkout with payment method const completeResponse = await axios.post( `https://api.qpay.com.br/api/public/checkout/sessions/${session.sessionId}/complete`, { paymentMethod: 'PIX', paymentData: {} } ); const result = completeResponse.data; console.log('Payment ID:', result.paymentId); console.log('Redirect URL:', result.redirectUrl); // Redirect customer to success page window.location.href = result.redirectUrl; return result; } catch (error) { console.error('Checkout error:', error.response?.data); throw error; } } // Example usage completeCheckoutFlow('curso-nodejs-completo', { email: 'cliente@example.com', name: 'João Silva', phone: '+5511987654321', cpf: '12345678900' }); ``` -------------------------------- ### Configure and Handle QPay Webhooks in Node.js Source: https://context7.com/qpaydev/qpay-docs/llms.txt This Node.js example demonstrates how to set up an Express server to receive and process QPay webhooks. It includes functions for creating webhook subscriptions, validating incoming signatures using HMAC-SHA256, and handling different event types. Ensure you securely store your webhook secret and implement robust error handling. ```javascript const express = require('express'); const crypto = require('crypto'); const axios = require('axios'); const app = express(); app.use(express.json()); const WEBHOOK_SECRET = process.env.QPAY_WEBHOOK_SECRET; // Create webhook subscription async function createWebhook() { const response = await axios.post( 'https://api.qpay.com.br/v1/webhooks', { url: 'https://myapp.com/api/webhooks/qpay', eventTypes: [ 'payment.approved', 'payment.failed', 'payment.refunded', 'subscription.created', 'subscription.canceled', 'subscription.renewed', 'billing_cycle.paid', 'billing_cycle.failed' ], description: 'Production webhook for all payment events', metadata: { environment: 'production', version: '1.0' } }, { headers: { 'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIs...', 'x-workspace-id': 'wks_abc123', 'Content-Type': 'application/json' } } ); console.log('Webhook ID:', response.data.webhookId); console.log('Secret:', response.data.secret); // Save this securely! return response.data; } // Validate webhook signature function validateWebhookSignature(request, secret) { const signature = request.headers['x-qpay-signature']; const timestamp = request.headers['x-qpay-timestamp']; const body = JSON.stringify(request.body); if (!signature || !timestamp) return false; const [algorithm, receivedHash] = signature.split('='); if (algorithm !== 'sha256') return false; const payload = `${timestamp}.${body}`; const expectedHash = crypto .createHmac('sha256', secret) .update(payload) .digest('hex'); return crypto.timingSafeEqual( Buffer.from(receivedHash), Buffer.from(expectedHash) ); } // Webhook handler with idempotency const processedEvents = new Set(); app.post('/api/webhooks/qpay', async (req, res) => { // Validate signature if (!validateWebhookSignature(req, WEBHOOK_SECRET)) { console.error('Invalid webhook signature'); return res.status(401).json({ error: 'Invalid signature' }); } const event = req.body; // Check for duplicate events if (processedEvents.has(event.id)) { console.log(`Event ${event.id} already processed`); return res.status(200).json({ received: true, duplicate: true }); } processedEvents.add(event.id); setTimeout(() => processedEvents.delete(event.id), 24 * 60 * 60 * 1000); // Respond immediately res.status(200).json({ received: true }); // Process event asynchronously try { switch (event.type) { case 'payment.approved': await handlePaymentApproved(event.data); break; case 'payment.failed': await handlePaymentFailed(event.data); break; case 'subscription.created': await handleSubscriptionCreated(event.data); break; case 'subscription.canceled': await handleSubscriptionCanceled(event.data); break; case 'billing_cycle.paid': await handleBillingCyclePaid(event.data); break; default: console.log(`Unhandled event: ${event.type}`); } } catch (error) { console.error('Error processing webhook:', error); } }); async function handlePaymentApproved(payment) { console.log(`✓ Payment approved: ${payment.paymentId}`); console.log(` Amount: R$ ${(payment.amount / 100).toFixed(2)}`); console.log(` Customer: ${payment.customerId}`); // Update order status, send confirmation email, etc. } async function handlePaymentFailed(payment) { console.log(`✗ Payment failed: ${payment.paymentId}`); // Notify customer, retry logic, etc. } async function handleSubscriptionCreated(subscription) { console.log(`New subscription: ${subscription.subscriptionId}`); // Activate service, send welcome email, etc. } async function handleSubscriptionCanceled(subscription) { console.log(`Subscription canceled: ${subscription.subscriptionId}`); console.log(` Reason: ${subscription.cancellationReason.type}`); // Deactivate service, send cancellation email, etc. } async function handleBillingCyclePaid(cycle) { console.log(`Billing cycle paid: ${cycle.id}`); // Extend service period, send invoice, etc. } app.listen(3000, () => { console.log('Webhook server running on port 3000'); }); ``` -------------------------------- ### POST /v1/payments Source: https://context7.com/qpaydev/qpay-docs/llms.txt Create a new payment with specified details including amount, currency, merchant, customer, and payment method. Supports credit card payments with installments and an idempotency key for request safety. ```APIDOC ## POST /v1/payments ### Description Creates a new payment transaction. This endpoint allows for detailed configuration of payment parameters such as amount, currency, customer, and payment method. It is crucial to include an `Idempotency-Key` header to prevent duplicate transactions. ### Method POST ### Endpoint `/v1/payments` ### Parameters #### Header Parameters - **Authorization** (string) - Required - Bearer token for authentication. - **Idempotency-Key** (string) - Required - Unique key to ensure request idempotency. - **X-Workspace-Id** (string) - Required - The ID of the workspace. #### Request Body - **amount** (object) - Required - The payment amount and currency. - **amount** (integer) - Required - The amount in cents. - **currency** (string) - Required - The currency code (e.g., 'BRL'). - **merchantId** (string) - Required - The ID of the merchant. - **customerId** (string) - Required - The ID of the customer. - **paymentMethod** (object) - Required - Details about the payment method. - **type** (string) - Required - The type of payment method (e.g., 'CREDIT_CARD'). - **details** (object) - Required - Specific details for the payment method. - **cardToken** (string) - Required - The token representing the credit card. - **installments** (integer) - Optional - The number of installments for the payment. - **brand** (string) - Optional - The brand of the credit card (e.g., 'visa'). - **description** (string) - Optional - A description for the payment. - **metadata** (object) - Optional - Additional metadata for the transaction. - **orderId** (string) - Optional - The associated order ID. - **campaign** (string) - Optional - The associated campaign name. ### Request Example ```json { "amount": { "amount": 30000, "currency": "BRL" }, "merchantId": "mer_550e8400-e29b-41d4-a716-446655440000", "customerId": "customer_456", "paymentMethod": { "type": "CREDIT_CARD", "details": { "cardToken": "token_from_previous_step", "installments": 3, "brand": "visa" } }, "description": "Compra parcelada em 3x", "metadata": { "orderId": "456", "campaign": "black_friday" } } ``` ### Response #### Success Response (200 or 201) - **paymentId** (string) - The unique identifier for the created payment. - **status** (string) - The initial status of the payment. #### Response Example ```json { "paymentId": "pay_abcdef12-3456-7890-abcd-ef1234567890", "status": "PENDING" } ``` ``` -------------------------------- ### Webhook Handler Logic Source: https://context7.com/qpaydev/qpay-docs/llms.txt An example implementation of a webhook handler that processes incoming events, validates signatures, handles idempotency by tracking processed events, and asynchronously dispatches event processing to specific handler functions. ```APIDOC ## Webhook Handler Logic ### Description This outlines the server-side logic for handling incoming webhook events. Key aspects include signature validation, idempotency to prevent duplicate processing, immediate acknowledgment to QPay, and asynchronous processing of the event data. ### Method POST ### Endpoint Your configured webhook URL (e.g., `https://myapp.com/api/webhooks/qpay`) ### Parameters #### Headers (Incoming Request) - **x-qpay-signature** (string) - Required - The signature provided by QPay. - **x-qpay-timestamp** (string) - Required - The timestamp of the request. #### Request Body - **id** (string) - Unique ID of the event. - **type** (string) - The type of event (e.g., `payment.approved`). - **data** (object) - The payload specific to the event type. ### Idempotency Handling - A mechanism (e.g., a `Set` in memory or a persistent store) should be used to track event IDs that have already been processed. - If an event ID is encountered again within a reasonable timeframe (e.g., 24 hours), it should be treated as a duplicate, acknowledged, and not processed again. - Processed event IDs should eventually be removed to prevent memory leaks. ### Asynchronous Processing - After validating the signature and checking for duplicates, the webhook handler should respond to QPay with a `200 OK` status immediately. - The actual processing of the event data (e.g., updating database records, sending emails) should occur asynchronously in a separate process or using background jobs to avoid long response times. ### Request Example (Incoming Webhook Event) ```json { "id": "evt_1a2b3c4d5e", "type": "payment.approved", "data": { "paymentId": "pay_xyz789", "amount": 5000, "customerId": "cust_abc123" } } ``` ### Response (from your webhook endpoint) #### Success Response (200) - **received** (boolean) - `true` if the event was received and acknowledged. - **duplicate** (boolean) - `true` if the event was a duplicate and skipped processing. #### Error Response (401) - **error** (string) - "Invalid signature" if the signature validation fails. #### Response Example (Successful Acknowledgment) ```json { "received": true } ``` #### Response Example (Duplicate Acknowledgment) ```json { "received": true, "duplicate": true } ``` #### Response Example (Invalid Signature) ```json { "error": "Invalid signature" } ``` ``` -------------------------------- ### GET /v1/customers/{customerId}/payment-methods/{paymentMethodId} Source: https://github.com/qpaydev/qpay-docs/blob/main/customers/payment-methods.md Retrieves a specific payment method for a customer. ```APIDOC ## GET /v1/customers/{customerId}/payment-methods/{paymentMethodId} ### Description Retrieves a specific payment method for a customer. ### Method GET ### Endpoint /v1/customers/{customerId}/payment-methods/{paymentMethodId} #### Path Parameters - **customerId** (string) - Required - The ID of the customer. - **paymentMethodId** (string) - Required - The ID of the payment method to retrieve. #### Query Parameters None #### Request Body None ### Request Example ``` GET /v1/customers/cus_550e8400-e29b-41d4-a716-446655440000/payment-methods/pm_550e8400-e29b-41d4-a716-446655440000 ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier of the payment method. - **customerId** (string) - The ID of the customer. - **tokenId** (string) - The token representing the payment method. - **isDefault** (boolean) - Indicates if this is the default payment method. - **nickname** (string) - The nickname of the payment method. - **createdAt** (string) - The timestamp when the payment method was added. #### Response Example ```json { "id": "pm_550e8400-e29b-41d4-a716-446655440000", "customerId": "cus_550e8400-e29b-41d4-a716-446655440000", "tokenId": "tok_6defd938-7332-4a97-a3ab-57b494348d0d", "isDefault": true, "nickname": "Primary card", "createdAt": "2023-10-27T10:00:00Z" } ``` ``` -------------------------------- ### Create Subscription with Trial Period (Python) Source: https://context7.com/qpaydev/qpay-docs/llms.txt Sets up a new subscription with a specified trial period. Requires a valid QPAY_TOKEN and QPAY_WORKSPACE_ID environment variables. It takes customer ID and plan amount as input and returns the created subscription details. ```python import requests import os class QPaySubscriptions: def __init__(self): self.base_url = 'https://api.qpay.com.br' self.headers = { 'Authorization': f'Bearer {os.getenv("QPAY_TOKEN")}', 'x-workspace-id': os.getenv('QPAY_WORKSPACE_ID'), 'Content-Type': 'application/json' } def create_subscription_with_trial(self, customer_id, plan_amount): response = requests.post( f'{self.base_url}/v1/subscriptions', headers=self.headers, json={ 'customerId': customer_id, 'plan': { 'amount': plan_amount, 'currency': 'BRL', 'interval': 'MONTH', 'intervalCount': 1, 'trialPeriodDays': 14 }, 'startTrial': True, 'paymentMethod': 'CREDIT_CARD', 'customerPaymentMethodId': '550e8400-e29b-41d4-a716-446655440003', 'metadata': { 'campaign': 'summer_promo_2024', 'source': 'landing_page' } } ) response.raise_for_status() subscription = response.json() print(f"Subscription Created: {subscription['subscriptionId']}") print(f"Status: {subscription['status']}") print(f"Trial Ends: {subscription['trialPeriod']['endDate']}") print(f"Days Remaining: {subscription['trialPeriod']['daysRemaining']}") return subscription def cancel_subscription(self, subscription_id, immediately=False): response = requests.post( f'{self.base_url}/v1/subscriptions/{subscription_id}/cancel', headers=self.headers, json={ 'reason': 'CUSTOMER_REQUEST', 'details': 'Cliente solicitou cancelamento', 'immediately': immediately, 'cancelledBy': 'CUSTOMER' } ) response.raise_for_status() result = response.json() print(f"Subscription {subscription_id} canceled") print(f"Status: {result['status']}") print(f"Cancellation Reason: {result['cancellationReason']['type']}") return result # Usage qpay = QPaySubscriptions() subscription = qpay.create_subscription_with_trial( customer_id='550e8400-e29b-41d4-a716-446655440001', plan_amount=4990 # R$ 49.90 ) ``` -------------------------------- ### POST /v1/subscriptions Source: https://context7.com/qpaydev/qpay-docs/llms.txt Creates a new subscription with an optional trial period. This endpoint allows for setting up recurring billing for customers, including defining the plan details, trial duration, and payment method. ```APIDOC ## POST /v1/subscriptions ### Description Creates a new subscription with an optional trial period. This endpoint allows for setting up recurring billing for customers, including defining the plan details, trial duration, and payment method. ### Method POST ### Endpoint /v1/subscriptions ### Parameters #### Query Parameters None #### Request Body - **customerId** (string) - Required - The ID of the customer for whom the subscription is being created. - **plan** (object) - Required - Details of the subscription plan. - **amount** (integer) - Required - The subscription amount in cents. - **currency** (string) - Required - The currency of the amount (e.g., 'BRL'). - **interval** (string) - Required - The billing interval (e.g., 'MONTH'). - **intervalCount** (integer) - Required - The number of intervals between billing cycles. - **trialPeriodDays** (integer) - Optional - The number of days for the trial period. - **startTrial** (boolean) - Optional - Whether to start the trial period immediately. - **paymentMethod** (string) - Required - The payment method to use (e.g., 'CREDIT_CARD'). - **customerPaymentMethodId** (string) - Required - The ID of the customer's payment method. - **metadata** (object) - Optional - Additional key-value pairs for metadata. - **campaign** (string) - Optional - The campaign associated with the subscription. - **source** (string) - Optional - The source of the subscription. ### Request Example ```json { "customerId": "550e8400-e29b-41d4-a716-446655440001", "plan": { "amount": 4990, "currency": "BRL", "interval": "MONTH", "intervalCount": 1, "trialPeriodDays": 14 }, "startTrial": true, "paymentMethod": "CREDIT_CARD", "customerPaymentMethodId": "550e8400-e29b-41d4-a716-446655440003", "metadata": { "campaign": "summer_promo_2024", "source": "landing_page" } } ``` ### Response #### Success Response (200) - **subscriptionId** (string) - The ID of the created subscription. - **status** (string) - The current status of the subscription. - **trialPeriod** (object) - Information about the trial period. - **endDate** (string) - The end date of the trial period. - **daysRemaining** (integer) - The number of days remaining in the trial period. #### Response Example ```json { "subscriptionId": "sub_abc123", "status": "TRIALING", "trialPeriod": { "endDate": "2024-08-15T00:00:00Z", "daysRemaining": 14 } } ``` ### Error Handling - `response.raise_for_status()` will raise an exception for unsuccessful status codes. ``` -------------------------------- ### GET /v1/customers/{customerId}/payment-methods Source: https://github.com/qpaydev/qpay-docs/blob/main/customers/payment-methods.md Lists all payment methods associated with a customer. Optionally include deleted payment methods. ```APIDOC ## GET /v1/customers/{customerId}/payment-methods ### Description Lists all payment methods associated with a customer. Optionally include deleted payment methods. ### Method GET ### Endpoint /v1/customers/{customerId}/payment-methods #### Path Parameters - **customerId** (string) - Required - The ID of the customer. #### Query Parameters - **includeDeleted** (boolean) - Optional - Defaults to false. If true, includes payment methods that have been marked as deleted. #### Request Body None ### Request Example ``` GET /v1/customers/cus_550e8400-e29b-41d4-a716-446655440000/payment-methods?includeDeleted=true ``` ### Response #### Success Response (200) - An array of payment method objects. - **id** (string) - The unique identifier of the payment method. - **customerId** (string) - The ID of the customer. - **tokenId** (string) - The token representing the payment method. - **isDefault** (boolean) - Indicates if this is the default payment method. - **nickname** (string) - The nickname of the payment method. - **createdAt** (string) - The timestamp when the payment method was added. - **deletedAt** (string or null) - The timestamp when the payment method was deleted, or null if not deleted. #### Response Example ```json [ { "id": "pm_550e8400-e29b-41d4-a716-446655440000", "customerId": "cus_550e8400-e29b-41d4-a716-446655440000", "tokenId": "tok_6defd938-7332-4a97-a3ab-57b494348d0d", "isDefault": true, "nickname": "Primary card", "createdAt": "2023-10-27T10:00:00Z", "deletedAt": null }, { "id": "pm_abcdef01-2345-6789-abcd-ef0123456789", "customerId": "cus_550e8400-e29b-41d4-a716-446655440000", "tokenId": "tok_another_token_here", "isDefault": false, "nickname": "Backup card", "createdAt": "2023-10-27T10:05:00Z", "deletedAt": null } ] ``` ``` -------------------------------- ### GET /v1/subscriptions/{subscription_id} Source: https://context7.com/qpaydev/qpay-docs/llms.txt Retrieves detailed information for a specific subscription, including billing cycle history. ```APIDOC ## GET /v1/subscriptions/{subscription_id} ### Description Retrieves detailed information for a specific subscription, including billing cycle history. ### Method GET ### Endpoint /v1/subscriptions/{subscription_id} ### Parameters #### Path Parameters - **subscription_id** (string) - Required - The ID of the subscription to retrieve. #### Query Parameters None ### Request Example ```http GET /v1/subscriptions/sub_xyz789 ``` ### Response #### Success Response (200) - **billingCycles** (array) - An array of billing cycle objects. - **paidAt** (string) - The timestamp when the billing cycle was paid. #### Response Example ```json { "subscriptionId": "sub_xyz789", "customerId": "cust_abc456", "plan": { "amount": 4990, "interval": "MONTH" }, "currentPeriodStart": "2024-07-15T00:00:00Z", "currentPeriodEnd": "2024-08-15T00:00:00Z", "billingCycles": [ { "paidAt": "2024-07-15T00:00:00Z" } ] } ``` ### Error Handling - `error.response?.data` contains detailed error information. ``` -------------------------------- ### GET /v1/subscriptions Source: https://context7.com/qpaydev/qpay-docs/llms.txt Retrieves a list of subscriptions. Supports filtering by status and pagination. Can be used to monitor active subscriptions or those with payment issues. ```APIDOC ## GET /v1/subscriptions ### Description Retrieves a list of subscriptions. Supports filtering by status and pagination. Can be used to monitor active subscriptions or those with payment issues. ### Method GET ### Endpoint /v1/subscriptions ### Parameters #### Path Parameters None #### Query Parameters - **status** (string) - Optional - Filters subscriptions by their status (e.g., 'ACTIVE', 'PAST_DUE'). - **page** (integer) - Optional - The page number for pagination. - **limit** (integer) - Optional - The number of items per page. ### Request Example ```http GET /v1/subscriptions?status=ACTIVE&page=1&limit=50 ``` ### Response #### Success Response (200) - **data** (array) - An array of subscription objects. - **subscriptionId** (string) - The ID of the subscription. - **customerId** (string) - The ID of the customer. - **plan** (object) - Details of the subscription plan. - **amount** (integer) - The subscription amount in cents. - **interval** (string) - The billing interval. - **currentPeriodStart** (string) - The start date of the current billing period. - **currentPeriodEnd** (string) - The end date of the current billing period. - **total** (integer) - The total number of subscriptions matching the query. - **page** (integer) - The current page number. - **totalPages** (integer) - The total number of pages available. #### Response Example ```json { "data": [ { "subscriptionId": "sub_xyz789", "customerId": "cust_abc456", "plan": { "amount": 4990, "interval": "MONTH" }, "currentPeriodStart": "2024-07-15T00:00:00Z", "currentPeriodEnd": "2024-08-15T00:00:00Z" } ], "total": 100, "page": 1, "totalPages": 5 } ``` ### Error Handling - `error.response?.data` contains detailed error information. ``` -------------------------------- ### GET /v1/payments Source: https://context7.com/qpaydev/qpay-docs/llms.txt Retrieves a paginated list of payments with filtering capabilities. You can filter by various criteria including merchant ID, status, date range, amount range, and payment method type. ```APIDOC ## GET /v1/payments ### Description Retrieves a list of payments, supporting pagination and advanced filtering. This endpoint is useful for generating payment reports or managing payment history. ### Method GET ### Endpoint `/v1/payments` ### Parameters #### Query Parameters - **merchantId** (string) - Optional - Filter payments by merchant ID. - **status** (string) - Optional - Filter payments by status (e.g., 'APPROVED', 'PENDING', 'DECLINED'). - **createdAfter** (string) - Optional - Filter payments created after a specific ISO 8601 timestamp. - **createdBefore** (string) - Optional - Filter payments created before a specific ISO 8601 timestamp. - **amountMin** (string) - Optional - Filter payments with a minimum amount (in cents). - **amountMax** (string) - Optional - Filter payments with a maximum amount (in cents). - **currency** (string) - Optional - Filter payments by currency code (e.g., 'BRL'). - **paymentMethodType** (string) - Optional - Filter payments by the type of payment method (e.g., 'CREDIT_CARD'). - **page** (integer) - Optional - The page number for pagination. - **pageSize** (integer) - Optional - The number of items per page. #### Header Parameters - **Authorization** (string) - Required - Bearer token for authentication. - **X-Workspace-Id** (string) - Required - The ID of the workspace. ### Request Example ```javascript // Example using JavaScript with axios const axios = require('axios'); const listPayments = async (filters) => { const params = new URLSearchParams({ merchantId: filters.merchantId || 'mer_550e8400-e29b-41d4-a716-446655440000', status: filters.status, createdAfter: filters.createdAfter, createdBefore: filters.createdBefore, amountMin: filters.amountMin, amountMax: filters.amountMax, currency: filters.currency || 'BRL', paymentMethodType: filters.paymentMethodType }); try { const response = await axios.get( `https://api.qpay.com.br/v1/payments?${params}`, { headers: { 'Authorization': 'Bearer YOUR_ACCESS_TOKEN', 'X-Workspace-Id': 'YOUR_WORKSPACE_ID' } } ); return response.data; } catch (error) { console.error('Error listing payments:', error.response?.data); throw error; } }; // Usage: // listPayments({ // status: 'APPROVED', // createdAfter: '2024-01-01T00:00:00Z', // paymentMethodType: 'CREDIT_CARD' // }); ``` ### Response #### Success Response (200) - An array of payment objects, each containing details like `paymentId`, `amount`, `status`, `paymentMethod`, `createdAt`, etc. #### Response Example ```json [ { "paymentId": "pay_a1b2c3d4-e5f6-7890-abcd-ef1234567890", "amount": { "amount": 5000, "currency": "BRL" }, "status": "APPROVED", "paymentMethod": { "type": "CREDIT_CARD", "brand": "visa" }, "createdAt": "2024-01-15T10:30:00.000Z", "merchantId": "mer_550e8400-e29b-41d4-a716-446655440000" } // ... more payment objects ] ``` ``` -------------------------------- ### Customer Management API Source: https://github.com/qpaydev/qpay-docs/blob/main/customers/customers.md This section details the API endpoints for creating, retrieving, listing, updating, and deactivating customers. ```APIDOC ## POST /v1/customers ### Description Creates a new customer in the QPay system. ### Method POST ### Endpoint /v1/customers ### Parameters #### Request Body - **fullName** (string) - Required - The full name of the customer. - **email** (string) - Required - The email address of the customer. - **phone** (string) - Optional - The phone number of the customer. - **country** (string) - Optional - The country code of the customer (e.g., 'BR'). - **documents** (array) - Optional - A list of customer documents. - **type** (string) - Required - The type of document (e.g., 'CPF'). - **number** (string) - Required - The document number. - **country** (string) - Required - The country code of the document. - **addresses** (array) - Optional - A list of customer addresses. - **type** (string) - Required - The type of address (e.g., 'BILLING'). - **line1** (string) - Required - The first line of the address. - **line2** (string) - Optional - The second line of the address. - **city** (string) - Required - The city of the address. - **state** (string) - Required - The state of the address. - **postalCode** (string) - Required - The postal code of the address. - **country** (string) - Required - The country code of the address. - **metadata** (object) - Optional - Additional metadata for the customer. ### Request Example ```json { "fullName": "João Silva", "email": "joao.silva@example.com", "phone": "+5511999999999", "country": "BR", "documents": [ { "type": "CPF", "number": "12345678901", "country": "BR" } ], "addresses": [ { "type": "BILLING", "line1": "Av. Faria Lima, 1000", "line2": "Andar 12", "city": "São Paulo", "state": "SP", "postalCode": "01451-001", "country": "BR" } ], "metadata": { "segment": "enterprise" } } ``` ### Response #### Success Response (200) - **customerId** (string) - The unique identifier for the created customer. #### Response Example ```json { "customerId": "cus_abcdef123456789012" } ``` ## GET /v1/customers/{customer_id} ### Description Retrieves the details of a specific customer. ### Method GET ### Endpoint /v1/customers/{customer_id} ### Parameters #### Path Parameters - **customer_id** (string) - Required - The unique identifier of the customer to retrieve. ### Response #### Success Response (200) - Returns the customer object with all their details. #### Response Example ```json { "customerId": "cus_abcdef123456789012", "fullName": "João Silva", "email": "joao.silva@example.com", "phone": "+5511999999999", "country": "BR", "documents": [ { "type": "CPF", "number": "12345678901", "country": "BR" } ], "addresses": [ { "type": "BILLING", "line1": "Av. Faria Lima, 1000", "line2": "Andar 12", "city": "São Paulo", "state": "SP", "postalCode": "01451-001", "country": "BR" } ], "metadata": { "segment": "enterprise" }, "createdAt": "2023-10-27T10:00:00Z", "updatedAt": "2023-10-27T10:00:00Z", "lifecycleStatus": "ACTIVE" } ``` ## GET /v1/customers ### Description Lists customers with optional filtering and pagination. ### Method GET ### Endpoint /v1/customers ### Parameters #### Query Parameters - **limit** (integer) - Optional - The maximum number of customers to return (default: 20). - **offset** (integer) - Optional - The number of customers to skip (default: 0). - **lifecycleStatus** (string) - Optional - Filter customers by lifecycle status (e.g., 'ACTIVE', 'INACTIVE'). - **email** (string) - Optional - Filter customers by email address. ### Response #### Success Response (200) - **total** (integer) - The total number of customers matching the query. - **customers** (array) - A list of customer objects. #### Response Example ```json { "total": 150, "customers": [ { "customerId": "cus_abcdef123456789012", "fullName": "João Silva", "email": "joao.silva@example.com", "lifecycleStatus": "ACTIVE" }, { "customerId": "cus_ghijkl0987654321", "fullName": "Maria Souza", "email": "maria.souza@example.com", "lifecycleStatus": "INACTIVE" } ] } ``` ## PATCH /v1/customers/{customer_id} ### Description Updates an existing customer's information. ### Method PATCH ### Endpoint /v1/customers/{customer_id} ### Parameters #### Path Parameters - **customer_id** (string) - Required - The unique identifier of the customer to update. #### Request Body - Fields to update (e.g., `fullName`, `email`, `phone`, `country`, `documents`, `addresses`, `metadata`). ### Request Example ```json { "phone": "+5511987654321", "metadata": { "segment": "premium" } } ``` ### Response #### Success Response (200) - Returns the updated customer object. #### Response Example ```json { "customerId": "cus_abcdef123456789012", "fullName": "João Silva", "email": "joao.silva@example.com", "phone": "+5511987654321", "country": "BR", "metadata": { "segment": "premium" }, "updatedAt": "2023-10-27T10:30:00Z" } ``` ## POST /v1/customers/{customer_id}/deactivate ### Description Deactivates a customer. ### Method POST ### Endpoint /v1/customers/{customer_id}/deactivate ### Parameters #### Path Parameters - **customer_id** (string) - Required - The unique identifier of the customer to deactivate. #### Request Body - **reason** (string) - Optional - The reason for deactivation. ### Request Example ```json { "reason": "Customer requested deactivation." } ``` ### Response #### Success Response (200) - Returns a success message indicating deactivation. #### Response Example ```json { "message": "Customer deactivated successfully." } ``` ``` -------------------------------- ### Create Checkout Configuration with cURL Source: https://context7.com/qpaydev/qpay-docs/llms.txt Configures customizable checkout pages with branding and payment options using a POST request. Requires an Authorization header and a JSON payload specifying details like name, logo, colors, URLs, and payment methods. The response includes the created checkout configuration ID. ```bash curl -X POST https://api.qpay.com.br/api/v1/checkout-configs \ -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIs..." \ -H "Content-Type: application/json" \ -d '{ "name": "Loja Virtual - Checkout Principal", "description": "Configuração de checkout para produtos digitais", "logoUrl": "https://minhaloja.com.br/assets/logo.png", "primaryColor": "#0030b9", "backgroundColor": "#ffffff", "successUrl": "https://minhaloja.com.br/obrigado", "cancelUrl": "https://minhaloja.com.br/cancelado", "notificationUrl": "https://minhaloja.com.br/api/webhooks/qpay", "collectShipping": false, "collectBilling": true, "allowedPaymentMethods": ["CREDIT_CARD", "PIX", "BOLETO"], "requireCustomerInfo": { "name": true, "email": true, "phone": true, "cpf": true }, "customFields": [ { "name": "referral_code", "label": "Código de Indicação", "required": false } ], "metadata": { "environment": "production", "version": "2.0" } }' ``` -------------------------------- ### POST /api/v1/payment-links Source: https://context7.com/qpaydev/qpay-docs/llms.txt Generate shareable payment links with flexible pricing options. This endpoint allows for creating links for fixed amounts, customer-chosen amounts, or minimum amount contributions. ```APIDOC ## POST /api/v1/payment-links ### Description Generate shareable payment links with flexible pricing options. This endpoint allows for creating links for fixed amounts, customer-chosen amounts, or minimum amount contributions. ### Method POST ### Endpoint /api/v1/payment-links ### Parameters #### Query Parameters None #### Request Body - **checkoutConfigId** (string) - Optional - The ID of a pre-configured checkout. If not provided, default checkout settings will be used. - **urlSlug** (string) - Optional - A custom slug for the payment link URL. - **amountType** (string) - Required - The type of amount setting. Options: "FIXED", "CUSTOMER_CHOOSES", "MIN_AMOUNT". - **fixedAmount** (integer) - Required if amountType is "FIXED" - The fixed amount for the payment link in cents. - **currency** (string) - Required if amountType is "FIXED" - The currency for the fixed amount (e.g., "BRL"). - **maxUses** (integer) - Optional - The maximum number of times this link can be used. - **expiresAt** (string) - Optional - The date and time when the link expires (ISO 8601 format). - **customMessage** (string) - Optional - A custom message to display to the payer. - **allowedPaymentMethods** (array) - Optional - List of payment methods allowed for this link. - **metadata** (object) - Optional - Key-value pairs for additional metadata. *Note: If amountType is "CUSTOMER_CHOOSES", only `urlSlug`, `customMessage`, `allowedPaymentMethods`, and `metadata` are applicable from the list above. If amountType is "MIN_AMOUNT", `minAmount`, `currency`, `urlSlug`, `customMessage`, `allowedPaymentMethods`, and `metadata` are applicable.* ### Request Example (Fixed Amount) ```json { "checkoutConfigId": "chk_config_abc123", "urlSlug": "curso-nodejs-completo", "amountType": "FIXED", "fixedAmount": 29900, "currency": "BRL", "maxUses": 100, "expiresAt": "2024-12-31T23:59:59Z", "customMessage": "Curso completo de Node.js - Acesso vitalício + certificado", "allowedPaymentMethods": ["CREDIT_CARD", "PIX"], "metadata": { "product_sku": "CURSO-NODE-001", "category": "education" } } ``` ### Request Example (Customer Chooses Amount) ```json { "urlSlug": "doar-projeto-social", "amountType": "CUSTOMER_CHOOSES", "customMessage": "Doe qualquer valor para apoiar nosso projeto social", "metadata": { "campaign": "christmas_2024" } } ``` ### Response #### Success Response (201 Created) - **linkId** (string) - The unique identifier for the generated payment link. - **fullUrl** (string) - The complete, shareable URL for the payment link. - **checkoutConfigId** (string) - The ID of the checkout configuration used. - **urlSlug** (string) - The custom slug of the link. - **amountType** (string) - The type of amount setting. - **fixedAmount** (integer) - The fixed amount (if applicable). - **currency** (string) - The currency (if applicable). - **expiresAt** (string) - The expiration date/time. #### Response Example ```json { "linkId": "paylink_def456", "fullUrl": "https://api.qpay.com.br/pay/xyz789", "checkoutConfigId": "chk_config_abc123", "urlSlug": "curso-nodejs-completo", "amountType": "FIXED", "fixedAmount": 29900, "currency": "BRL", "expiresAt": "2024-12-31T23:59:59Z" } ``` ```