Suscribirse al contenido
En este ejemplo, demostramos cómo gestionar el acceso basado en suscripciones al contenido utilizando la API de OneEntry. Verificamos si un usuario tiene una suscripción activa y, en función de eso, le otorgamos acceso al contenido premium o le solicitamos que se suscriba.
✅ Propósito del escenario:
- Solo los usuarios con una suscripción tienen acceso al contenido.
- La verificación se basa en Orders, User.
- Aquellos que no están autorizados o no han realizado una compra recibirán una oferta para suscribirse.
✅ Lo que necesitas:
- Un PROJECT_URL y APP_TOKEN válidos para la autenticación con la API de OneEntry.
- Formulario con marcador "subscriptions", atributos "expired_date" y "subscription_time" y tipo "Order form".
- Usuario registrado.
📌 Importante:
- Estos ejemplos no incluyen manejo de errores.
- Puedes gestionar errores utilizando un bloque try-catch o empleando una construcción como await Promise.catch((error) => error).
Escenario
1. Importar defineOneEntry desde el SDK y definir la url y el token
Ejemplo:
import { defineOneEntry } from 'oneentry';
const PROJECT_URL = 'your-project-url';
const APP_TOKEN = 'your-app-token';
2. Creando un cliente API con la función defineOneEntry()
Ejemplo:
const { Users, Orders, Pages, Payments, AuthProvider, Forms } = defineOneEntry(PROJECT_URL, {
token: APP_TOKEN,
});
3. Preparando datos para la autorización del usuario
Ejemplo:
[
{
"marker": "email_reg",
"value": "your-user@email.com"
},
{
"marker": "password_reg",
"value": "123456"
}
]
4. Autorización y obtención de datos del usuario AuthProvider.auth()
Ejemplo:
const authResponse = await AuthProvider.auth('email', {
authData,
});
Resultado:
{
"userIdentifier": "your-user@email.com",
"authProviderIdentifier": "email",
"accessToken": "eyJhbGciOiJIUzI1NiIsInR...pZCI6MTYsImF1dGhQ"
"refreshToken": "1745494429101-...-2834edf8"
}
5. Obtenemos una lista de pedidos del usuario con Orders.getAllOrdersByMarker()
Ejemplo:
const orders = await Orders.getAllOrdersByMarker('subscriptions');
Resultado:
{
"items": [
{
"id": 95,
"storageId": 2,
"createdDate": "2025-08-29T13:32:04.663Z",
"statusIdentifier": "active",
"formIdentifier": "subscription",
"formData": [
{
"marker": "expired_date",
"type": "date",
"value": {
"fullDate": "2026-05-07T00:00:00.000Z",
"formattedValue": "03-05-2026 00:00",
"formatString": "DD-MM-YYYY HH:mm"
}
}
],
"attributeSetIdentifier": "subscriptions",
"totalSum": "100.00",
"currency": "",
"paymentAccountIdentifier": "cash",
"paymentAccountLocalizeInfos": {
"title": "Cash"
},
"products": [
{
"id": 3,
"title": "1 month",
"sku": "",
"previewImage": null,
"price": 100,
"quantity": 1
}
],
"isCompleted": false
},
{
"id": 94,
"storageId": 2,
"createdDate": "2025-08-29T13:29:30.068Z",
"statusIdentifier": "active",
"formIdentifier": "subscription",
"formData": [
{
"marker": "expired_date",
"type": "date",
"value": {
"fullDate": "2026-05-07T00:00:00.000Z",
"formattedValue": "07-05-2026 00:00",
"formatString": "DD-MM-YYYY HH:mm"
}
}
],
"attributeSetIdentifier": "subscriptions",
"totalSum": "100.00",
"currency": "",
"paymentAccountIdentifier": "cash",
"paymentAccountLocalizeInfos": {
"title": "Cash"
},
"products": [
{
"id": 3,
"title": "1 month",
"sku": "",
"previewImage": null,
"price": 100,
"quantity": 1
}
],
"isCompleted": false
},
{
"id": 91,
"storageId": 2,
"createdDate": "2025-04-30T21:48:40.628Z",
"statusIdentifier": "active",
"formIdentifier": "subscription",
"formData": [
{
"type": "date",
"marker": "expired_date",
"value": {
"fullDate": "2025-05-07T00:00:00.000Z",
"formattedValue": "07-05-2025 00:00",
"formatString": "DD-MM-YYYY HH:mm"
}
},
{
"type": "list",
"marker": "subscription_time",
"value": [
{
"title": "1 month",
"value": "1",
"extended": {
"type": "real",
"value": "100"
}
}
]
}
],
"attributeSetIdentifier": "subscriptions",
"totalSum": "100.00",
"currency": "",
"paymentAccountIdentifier": "cash",
"paymentAccountLocalizeInfos": {
"title": "Cash"
},
"products": [
{
"id": 3,
"title": "1 month",
"sku": "",
"previewImage": null,
"price": 100,
"quantity": 1
}
],
"isCompleted": false
}
],
"total": 3
}
6. Verificando si hay una suscripción activa
Ejemplo:
const now = new Date();
const hasActiveSubscription = orders.items?.some(
(order: any) =>
new Date(
order.formData.find(
(d: { marker: string }) => d.marker === 'expired_date',
).value.fullDate,
) > now,
);
Resultado:
true
7. Si la suscripción está activa, proporcionamos acceso; de lo contrario, creamos un pedido y generamos el pago
Ejemplo:
let content = null;
if (hasActiveSubscription) {
// ✅ Subscription active → show content
content = await Pages.getPageByUrl('premium_page');
console.log('🎉 Доступ открыт:', content);
} else {
// ❌ No subscription → create an order and generate payment
const body = {
formIdentifier: 'subscription',
paymentAccountIdentifier: 'cash',
formData: [
{
type: 'date',
marker: 'expired_date',
value: {
fullDate: '2025-05-07T00:00:00.000Z',
formattedValue: '07-05-2025 00:00',
formatString: 'DD-MM-YYYY HH:mm',
},
},
{
type: 'list',
marker: 'subscription_time',
value: [
{
title: '1 month',
value: '1',
extended: {
type: 'real',
value: '100',
},
},
],
},
],
products: [
{
productId: 3,
quantity: 1,
},
],
};
const order = await Orders.createOrder('subscriptions', body);
const payment = await Payments.createSession(order.id, 'session', false);
// console.log('💸 Proceed to pay for your subscription:', payment)
}
Resultado:
{
"id": 7,
"parentId": null,
"pageUrl": "premium_page",
"depth": 0,
"localizeInfos": {
"title": "Premium page",
"menuTitle": "Premium page",
"htmlContent": "",
"plainContent": ""
},
"isVisible": true,
"blocks": [],
"type": "common_page",
"templateIdentifier": null,
"attributeSetIdentifier": null,
"attributeValues": {},
"moduleFormConfigs": [],
"isSync": false
}
Ejemplo final
// 1. Import defineOneEntry from SDK and define PROJECT_URL and APP_TOKEN
import { defineOneEntry } from 'oneentry';
const PROJECT_URL = 'your-project-url';
const APP_TOKEN = 'your-app-token';
// 2. Creating an API client
const { Users, Orders, Pages, Payments, AuthProvider, Forms } =
defineOneEntry(PROJECT_URL, {
token: APP_TOKEN,
});
// 3. Preparing data for user authorization
const form = await Forms.getFormByMarker('subscription');
// expired_date - Date
// subscription_time - list
const authData = [
{
marker: 'email_reg',
value: 'your-user@email.com',
},
{
marker: 'password_reg',
value: '123456',
},
];
// 4. Authorization and obtaining user data
const authResponse = await AuthProvider.auth('email', {
authData,
});
const user = await Users.getUser();
// 5. We get a list of user orders
const orders = await Orders.getAllOrdersByMarker('subscriptions');
// 6. Checking for an active subscription
const now = new Date();
const hasActiveSubscription = orders.items?.some(
(order: any) =>
new Date(
order.formData.find(
(d: { marker: string }) => d.marker === 'expired_date',
).value.fullDate,
) > now,
);
// 7. If the subscription is active, we provide access, otherwise we create an order and generate payment
let content = null;
if (hasActiveSubscription) {
// ✅ Subscription active → show content
content = await Pages.getPageByUrl('premium_page');
console.log('🎉 Access is open:', content);
} else {
// ❌ No subscription → create an order and generate payment
const body = {
formIdentifier: 'subscription',
paymentAccountIdentifier: 'cash',
formData: [
{
type: 'date',
marker: 'expired_date',
value: {
fullDate: '2025-05-07T00:00:00.000Z',
formattedValue: '07-05-2025 00:00',
formatString: 'DD-MM-YYYY HH:mm',
},
},
{
type: 'list',
marker: 'subscription_time',
value: [
{
title: '1 month',
value: '1',
extended: {
type: 'real',
value: '100',
},
},
],
},
],
products: [
{
productId: 3,
quantity: 1,
},
],
};
const order = await Orders.createOrder('subscriptions', body);
const payment = await Payments.createSession(order.id, 'session', false);
console.log('💸 Proceed to pay for your subscription:', payment);
}