Suscribirse al contenido
✅ Propósito del escenario:
- Solo los usuarios con una suscripción tienen acceso al contenido.
- La verificación se basa en Pedidos, Usuario.
- Aquellos que no están autorizados o no han comprado recibirán una oferta para suscribirse.
✅ Lo que necesitas:
- Una PROJECT_URL y APP_TOKEN válidos para la autenticación con la API de OneEntry.
📌 Importante:
- No manejamos errores en estos ejemplos.
- Puedes manejar errores en trycatch o en una construcción como "await Promise.catch((error) => error)"
Escenario
1. Importar oneEntry y definir url y token
Ejemplo:
import { defineOneEntry } from 'oneentry';
const PROJECT_URL = 'your-project-url';
const APP_TOKEN = 'your-app-token';
2. Crear un cliente API con la función defineOneEntry()
Ejemplo:
const { Users, Orders, Pages, Payments, AuthProvider, Forms } = defineOneEntry(PROJECT_URL, {
token: APP_TOKEN,
});
3. Preparar 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": 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 mes",
"value": "1",
"extended": {
"type": "real",
"value": "100"
}
}
]
}
],
"attributeSetIdentifier": "subscriptions",
"totalSum": "100.00",
"currency": "",
"paymentAccountIdentifier": "cash",
"paymentAccountLocalizeInfos": {
"title": "Efectivo"
},
"products": [
{
"id": 3,
"title": "1 mes",
"sku": "",
"previewImage": null,
"price": 100,
"quantity": 1
}
],
"isCompleted": false
}
],
"total": 1
}
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) {
// ✅ Suscripción activa → mostrar contenido
content = await Pages.getPageByUrl('premium_page');
console.log('🎉 Acceso abierto:', content);
} else {
// ❌ Sin suscripción → crear un pedido y generar el pago
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 mes',
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('💸 Proceder a pagar por tu suscripción:', payment)
}
Resultado:
{
"id": 7,
"parentId": null,
"pageUrl": "premium_page",
"depth": 0,
"localizeInfos": {
"title": "Página premium",
"menuTitle": "Página premium",
"htmlContent": "",
"plainContent": ""
},
"isVisible": true,
"forms": [],
"blocks": [],
"type": "common_page",
"templateIdentifier": null,
"attributeSetIdentifier": null,
"attributeValues": {},
"isSync": false
}
Ejemplo final
// 1. Importar oneEntry y definir PROJECT_URL y APP_TOKEN
import { defineOneEntry } from 'oneentry';
const PROJECT_URL = 'your-project-url';
const APP_TOKEN = 'your-app-token';
// 2. Crear un cliente API
const { Users, Orders, Pages, Payments, AuthProvider, Forms } =
defineOneEntry(PROJECT_URL, {
token: APP_TOKEN,
});
// 3. Preparar datos para la autorización del usuario
// const form = await Forms.getFormByMarker('subscription');
// expired_date - Fecha
// subscription_time - lista
const authData = [
{
marker: 'email_reg',
value: 'your-user@email.com',
},
{
marker: 'password_reg',
value: '123456',
},
];
// 4. Autorización y obtención de datos del usuario
const authResponse = await AuthProvider.auth('email', {
authData,
});
const user = await Users.getUser();
// 5. Obtenemos una lista de pedidos del usuario
const orders = await Orders.getAllOrdersByMarker('subscriptions');
// 6. Verificando si hay una suscripción activa
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. Si la suscripción está activa, proporcionamos acceso; de lo contrario, creamos un pedido y generamos el pago
let content = null;
if (hasActiveSubscription) {
// ✅ Suscripción activa → mostrar contenido
content = await Pages.getPageByUrl('premium_page');
console.log('🎉 Acceso abierto:', content);
} else {
// ❌ Sin suscripción → crear un pedido y generar el pago
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 mes',
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('💸 Proceder a pagar por tu suscripción:', payment);
}