Pedir entradas para un evento
Crea un pedido de entradas para un evento.
Qué hace este ejemplo:
- Inicia la sesión del usuario
- Obtiene el formulario de entradas y despliega el horario en franjas horarias
- Crea un pedido para la entrada seleccionada y una sesión de pago para él
Requisitos previos:
- Un PROJECT_URL y un APP_TOKEN válidos para la API de OneEntry.
- Un usuario registrado con el que iniciar sesión
- Un formulario con el marcador "tickets_form" y los campos "schedule" y "tickets"
- Un almacenamiento de pedidos configurado con el marcador "tickets"
Notas:
- Los ejemplos manejan los errores de forma mínima: lanzan una excepción cuando una llamada devuelve un objeto de error.
- Por defecto (
isShell: true), el SDK devuelve un objeto de error en lugar de lanzar una excepción, así que comprueba el resultado, p. ej.,'statusCode' in result. ConisShell: falselanza la excepción y los errores se manejan con try/catch. Consulta Errors.
Documentación de la plataforma:
Referencia del SDK:
Pruébalo en vivo
Ejecuta este ejemplo en el sandbox del SDK de JS. Conecta tu Project URL y App Token en la primera visita y luego abre:
Escenario
1. Importar defineOneEntry y definir PROJECT_URL y APP_TOKEN
import { defineOneEntry } from 'oneentry';
const PROJECT_URL = 'https://your-project.oneentry.cloud';
const APP_TOKEN = 'your-app-token';
2. Crear un cliente de API con defineOneEntry()
const { AuthProvider, Forms, Orders, Payments } = defineOneEntry(PROJECT_URL, {
token: APP_TOKEN,
});
3. Autentica al usuario con 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. Obtener el formulario desde la plataforma OneEntry con Forms.getFormByMarker() para construirlo en el 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": []
}
El atributo schedule contiene una regla de recurrencia compacta, no una lista de franjas. Conviértela en pares [start, end] concretos para las fechas que renderizas con expandTimeIntervals; consulta Intervalos de tiempo:
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. Crear un pedido en el almacenamiento de pedidos con 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. Crear una sesión de pago con 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. Obtener la sesión de pago por ID de pedido con 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
}
]
Ejemplo 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);