Pular para o conteúdo principal

Pedir ingressos para eventos

Cria um pedido de ingressos para eventos.

O que este exemplo faz:

  • Autentica o usuário
  • Obtém o formulário de ingressos e expande a programação em horários
  • Cria um pedido para o ingresso selecionado e uma sessão de pagamento para ele

Pré-requisitos:

  • Um PROJECT_URL e um APP_TOKEN válidos para a API do OneEntry.
  • Um usuário cadastrado para fazer login
  • Um formulário com o marcador "tickets_form" e os campos "schedule" e "tickets"
  • Um armazenamento de pedidos configurado com o marcador "tickets"

Observações:

  • Os exemplos tratam erros de forma mínima: lançam uma exceção quando uma chamada retorna um objeto de erro.
  • Por padrão (isShell: true), o SDK retorna um objeto de erro em vez de lançar uma exceção, então verifique o resultado, por exemplo 'statusCode' in result. Com isShell: false, ele lança a exceção, e você trata os erros com try/catch. Veja Erros.

Documentação da plataforma:

Referência do SDK:

Experimente ao vivo​

Execute este exemplo no sandbox do JS SDK. Conecte a URL do seu projeto e o App Token na primeira visita e, em seguida, abra:

Cenário​

1. Importar defineOneEntry e definir PROJECT_URL e APP_TOKEN​

import { defineOneEntry } from 'oneentry';

const PROJECT_URL = 'https://your-project.oneentry.cloud';
const APP_TOKEN = 'your-app-token';

2. Criar um cliente da API com defineOneEntry()​

const { AuthProvider, Forms, Orders, Payments } = defineOneEntry(PROJECT_URL, {
token: APP_TOKEN,
});

3. Autenticar o usuário com AuthProvider.auth()​

const authData = [
{ marker: 'email_reg', value: 'your-email' },
{ marker: 'password_reg', value: 'your-password' },
];
const authResponse = await AuthProvider.auth('email', { authData });

if ('statusCode' in authResponse) {
throw new Error(authResponse.message);
}

console.log(authResponse);
Resultado:
{
"userIdentifier": "john@example.com",
"authProviderIdentifier": "email",
"accessToken": "eyJhbGciOiJIUzI1NiIsInR...pZCI6MTYsImF1dGhQ",
"refreshToken": "1745494429101-...-2834edf8"
}

4. Obter o formulário da OneEntry Platform com Forms.getFormByMarker() para montá-lo no frontend​

const form = await Forms.getFormByMarker('tickets_form');

if ('statusCode' in form) {
throw new Error(form.message);
}
console.log(form);
Resultado:
{
"id": 9,
"attributeSetId": 12,
"type": "order",
"localizeInfos": {
"title": "Tickets",
"titleForSite": "Tickets",
"successMessage": "",
"unsuccessMessage": "",
"urlAddress": "",
"database": "0",
"script": "0"
},
"version": 6,
"position": 1,
"identifier": "tickets_form",
"processingType": "script",
"templateId": null,
"attributes": [
{
"type": "timeInterval",
"marker": "schedule",
"position": 1,
"settings": {},
"isVisible": true,
"listTitles": [],
"validators": {},
"initialValue": null,
"localizeInfos": {
"title": "Schedule",
"intervals": [
{
"id": "ef9cf848-7373-4b81-98bd-7ad33aa951e2",
"range": [
"2025-04-26T21:00:00.000Z",
"2025-04-26T21:00:00.000Z"
],
"external": [],
"intervals": [
{
"id": "f2042e47-c650-4fc6-ae1c-efdb109b450f",
"end": {
"hours": 21,
"minutes": 30
},
"start": {
"hours": 16,
"minutes": 30
},
"period": 90
}
],
"inEveryWeek": true,
"inEveryMonth": true
}
]
},
"additionalFields": {}
},
{
"type": "entity",
"marker": "tickets",
"position": 2,
"settings": {},
"isVisible": true,
"listTitles": [
{
"title": "Tickets",
"value": {
"id": 8,
"depth": 0,
"isPinned": false,
"parentId": null,
"position": "0|hzzzz3:"
}
},
{
"title": "Bronze",
"value": {
"id": "p-8-10",
"depth": 1,
"isPinned": false,
"parentId": 8,
"position": 1,
"selected": true
}
},
{
"title": "Silver",
"value": {
"id": "p-8-11",
"depth": 1,
"isPinned": false,
"parentId": 8,
"position": 2,
"selected": true
}
},
{
"title": "Gold",
"value": {
"id": "p-8-12",
"depth": 1,
"isPinned": false,
"parentId": 8,
"position": 3,
"selected": true
}
}
],
"validators": {
"requiredValidator": {
"strict": true
}
},
"initialValue": null,
"localizeInfos": {
"title": "Tickets"
},
"additionalFields": {}
}
],
"total": "1",
"moduleFormConfigs": []
}

O atributo schedule traz uma regra de recorrência compacta, não uma lista de horários. Converta-a em pares concretos [start, end] para as datas que você renderiza com expandTimeIntervals; veja Intervalos de tempo:

import { expandTimeIntervals } from 'oneentry';

const field = form.attributes.find((a) => a.marker === 'schedule');

const slots = (field?.localizeInfos.intervals ?? []).flatMap((schedule) =>
expandTimeIntervals(schedule, { from: '2025-04-01', to: '2025-04-30' }),
);

5. Criar um pedido no armazenamento de pedidos com Orders.createOrder()​

const body = {
formIdentifier: 'tickets_form',
paymentAccountIdentifier: 'cash',
formData: [{ type: 'entity', marker: 'tickets', value: ['p-8-10'] }],
products: [{ productId: 10, quantity: 1 }],
};
const order = await Orders.createOrder('tickets', body);

if ('statusCode' in order) {
throw new Error(order.message);
}
Resultado:
{
"id": 123,
"formIdentifier": "tickets_form",
"paymentAccountIdentifier": "cash",
"formData": [
{
"type": "entity",
"marker": "tickets",
"value": [
"p-8-10"
]
}
],
"products": [
{
"productId": 10,
"quantity": 1
}
],
"currency": "USD",
"totalSum": 100,
"bonusApplied": 0,
"totalDue": 100,
"discountConfig": {
"orderDiscounts": [],
"productDiscounts": [],
"coupon": null,
"settings": {
"allowStacking": false,
"maxDiscountValue": null,
"allowGiftStacking": false,
"maxBonusPaymentPercent": null,
"minBonusAmount": null,
"minOrderAmountForBonus": null,
"giftRefundPolicy": "KEEP_GIFT"
},
"additionalDiscountsMarkers": [],
"totalRaw": 100,
"totalSumWithDiscount": 100,
"excludedGiftProductIds": [],
"bonus": {
"availableBalance": 0,
"maxBonusDiscount": 0,
"minBonusAmount": null,
"minOrderAmountForBonus": null,
"bonusApplied": 0
},
"bonusApplied": 0,
"totalDue": 100
},
"statusIdentifier": "new",
"statusLocalizeInfos": {
"title": "new"
},
"createdDate": "2026-06-06T11:54:31.545Z"
}

6. Criar uma sessão de pagamento com Payments.createSession()​

const paymentSession = await Payments.createSession(order.id, 'session', false);

if ('statusCode' in paymentSession) {
throw new Error(paymentSession.message);
}

console.log(paymentSession);
Resultado:
{
"id": 71,
"createdDate": "2026-06-06T11:54:31.857Z",
"updatedDate": "2026-06-06T11:54:31.857Z",
"type": "session",
"status": "waiting",
"paymentAccountId": 1,
"orderId": 123,
"amount": null,
"paymentUrl": null
}

7. Obter a sessão de pagamento pelo ID do pedido com Payments.getSessionByOrderId()​

const sessionByOrderId = await Payments.getSessionByOrderId(order.id);

if ('statusCode' in sessionByOrderId) {
throw new Error(sessionByOrderId.message);
}

console.log(sessionByOrderId);
Resultado:
[
{
"id": 71,
"createdDate": "2026-06-06T11:54:31.857Z",
"updatedDate": "2026-06-06T11:54:31.857Z",
"type": "session",
"status": "waiting",
"paymentAccountId": 1,
"orderId": 123,
"amount": null,
"paymentUrl": null
}
]

Exemplo final​

// 1. Import defineOneEntry and define PROJECT_URL and APP_TOKEN
import { defineOneEntry } from 'oneentry';

const PROJECT_URL = 'https://your-project.oneentry.cloud';
const APP_TOKEN = 'your-app-token';

// 2. Create an API client
const { AuthProvider, Forms, Orders, Payments } = defineOneEntry(PROJECT_URL, {
token: APP_TOKEN,
});

// 3. Sign in
const authData = [
{ marker: 'email_reg', value: 'your-email' },
{ marker: 'password_reg', value: 'your-password' },
];
const authResponse = await AuthProvider.auth('email', { authData });

if ('statusCode' in authResponse) {
throw new Error(authResponse.message);
}

console.log(authResponse);

// 4. Get the form to build it on the frontend
const form = await Forms.getFormByMarker('tickets_form');

if ('statusCode' in form) {
throw new Error(form.message);
}
console.log(form);

// 5. Create an order in the order storage
const body = {
formIdentifier: 'tickets_form',
paymentAccountIdentifier: 'cash',
formData: [{ type: 'entity', marker: 'tickets', value: ['p-8-10'] }],
products: [{ productId: 10, quantity: 1 }],
};
const order = await Orders.createOrder('tickets', body);

if ('statusCode' in order) {
throw new Error(order.message);
}

// 6. Create a payment session
const paymentSession = await Payments.createSession(order.id, 'session', false);

if ('statusCode' in paymentSession) {
throw new Error(paymentSession.message);
}

console.log(paymentSession);

// 7. Get the payment session by order ID
const sessionByOrderId = await Payments.getSessionByOrderId(order.id);

if ('statusCode' in sessionByOrderId) {
throw new Error(sessionByOrderId.message);
}

console.log(sessionByOrderId);