Chuyển đến nội dung chính

Đăng ký nội dung

Trong ví dụ này, chúng tôi minh họa cách quản lý quyền truy cập dựa trên đăng ký vào nội dung bằng cách sử dụng API OneEntry. Chúng tôi kiểm tra xem người dùng có đăng ký hoạt động hay không và cấp quyền truy cập vào nội dung cao cấp hoặc yêu cầu họ đăng ký.

✅ Mục đích của kịch bản:

  • Chỉ những người dùng có đăng ký mới có quyền truy cập vào nội dung
  • Việc kiểm tra dựa trên Đơn hàng, Người dùng.
  • Những người không được ủy quyền hoặc chưa mua sẽ nhận được đề nghị đăng ký.

✅ Những gì bạn cần:

  • Một PROJECT_URL và APP_TOKEN hợp lệ để xác thực với API OneEntry.
  • Biểu mẫu với dấu hiệu "subscriptions", thuộc tính "expired_date" và "subscription_time" và loại "Biểu mẫu đơn hàng"
  • Người dùng đã đăng ký

📌 Quan trọng:

  • Những ví dụ này không bao gồm xử lý lỗi.
  • Bạn có thể quản lý lỗi bằng cách sử dụng khối try-catch hoặc bằng cách sử dụng cấu trúc như await Promise.catch((error) => error).

📚 Xem trong tài liệu:

📦 Tham khảo SDK:

Thử nghiệm trực tiếp

Chạy phương pháp này một cách tương tác trong JS SDK sandbox — kết nối URL Dự án và Mã thông báo Ứng dụng của bạn khi truy cập lần đầu, sau đó mở:

  • Đăng ký nội dung — Trong ví dụ này, chúng tôi minh họa cách quản lý quyền truy cập dựa trên đăng ký vào nội dung bằng cách sử dụng API OneEntry. Chúng tôi kiểm tra xem người dùng có đăng ký hoạt động hay không và cấp quyền truy cập vào nội dung cao cấp hoặc yêu cầu họ đăng ký.

Kịch bản

1. Nhập defineOneEntry từ SDK và định nghĩa PROJECT_URL và APP_TOKEN

Ví dụ:

import { defineOneEntry } from 'oneentry';

const PROJECT_URL = 'your-project-url';
const APP_TOKEN = 'your-app-token';

2. Tạo một khách hàng API với defineOneEntry()

Ví dụ:

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

3. Lấy biểu mẫu

Ví dụ:

const form = await Forms.getFormByMarker('subscription');
console.log(form);
// expired_date - Date
// subscription_time - list
Kết quả:
{
"id": 6,
"attributeSetId": 8,
"type": "order",
"localizeInfos": {
"title": "Subscription",
"titleForSite": "Subscription",
"successMessage": "Message about successful data processing",
"unsuccessMessage": "Message about unsuccessful data processing",
"urlAddress": "",
"database": "0",
"script": "0"
},
"version": 21,
"position": 1,
"identifier": "subscription",
"processingType": "script",
"templateId": null,
"attributes": [
{
"type": "date",
"marker": "expired_date",
"position": 2,
"settings": {},
"isVisible": true,
"listTitles": [],
"validators": {},
"initialValue": null,
"localizeInfos": {
"title": "Expired date"
},
"additionalFields": {}
},
{
"type": "list",
"marker": "subscription_time",
"position": 5,
"settings": {},
"isVisible": true,
"listTitles": [
{
"title": "1 month",
"value": "1",
"extended": {
"type": "real",
"value": "100"
},
"position": 1
},
{
"title": "6 months",
"value": "6",
"extended": {
"type": "real",
"value": "500"
},
"position": 2
},
{
"title": "1 year",
"value": "12",
"extended": {
"type": "real",
"value": "999"
},
"position": 3
}
],
"validators": {},
"initialValue": null,
"localizeInfos": {
"title": "Subscription time"
},
"additionalFields": {}
}
],
"total": "1",
"moduleFormConfigs": []
}

4. Chuẩn bị dữ liệu cho việc xác thực người dùng

Ví dụ:

const authData = [
{ marker: 'email_reg', value: 'your-email' },
{ marker: 'password_reg', value: 'your-password' },
];
Kết quả:
[
{
"marker": "email_reg",
"value": "kvasssukr.net@gmail.com"
},
{
"marker": "password_reg",
"value": "123456"
}
]

5. Xác thực và lấy dữ liệu người dùng với AuthProvider.auth()

Ví dụ:

const authResponse = await AuthProvider.auth('email', { authData });
console.log(authResponse);

const user = await Users.getUser();
console.log(user);
Kết quả:
{
"id": 39,
"total": "1",
"identifier": "kvasssukr.net@gmail.com",
"authProviderIdentifier": "email",
"formData": [
{
"marker": "name_reg",
"type": "string",
"value": "Ivan"
},
{
"marker": "phone_reg",
"type": "string",
"value": "+10000000001"
},
{
"marker": "email_notification_reg",
"type": "string",
"value": "test@example.com"
}
],
"formIdentifier": "reg",
"groups": [
1
],
"state": {},
"rating": {},
"moduleFormConfigs": []
}

6. Chúng tôi lấy danh sách đơn hàng của người dùng với Orders.getAllOrdersByMarker()

Ví dụ:

const orders = await Orders.getAllOrdersByMarker('subscriptions');

if ('statusCode' in orders) {
throw new Error(orders.message);
}
Kết quả:
{
"items": [
{
"id": 119,
"storageId": 2,
"createdDate": "2026-06-06T11:50:12.995Z",
"statusIdentifier": "active",
"statusLocalizeInfos": {
"title": "Active"
},
"formIdentifier": "subscription",
"formData": [
{
"type": "date",
"marker": "expired_date",
"value": {
"fullDate": "2026-05-07T00:00:00.000Z",
"formattedValue": "07-05-2026 00:00",
"formatString": "DD-MM-YYYY HH:mm"
}
},
{
"type": "list",
"marker": "subscription_time",
"value": [
"1"
]
}
],
"attributeSetIdentifier": "subscriptions",
"paymentStrategy": "once",
"totalSum": "400",
"totalSumRaw": "400",
"currency": "USD",
"paymentAccountIdentifier": "cash",
"paymentAccountLocalizeInfos": {
"title": "Cash"
},
"products": [
{
"id": 15,
"title": "Orange ball",
"sku": null,
"previewImage": "[]",
"price": 400,
"quantity": 1,
"isGift": false
}
],
"paymentUrl": null,
"discountConfig": {
"orderDiscounts": [],
"productDiscounts": [],
"coupon": null,
"settings": {
"allowStacking": false,
"maxDiscountValue": null,
"allowGiftStacking": false,
"maxBonusPaymentPercent": null,
"minBonusAmount": null,
"minOrderAmountForBonus": null,
"giftRefundPolicy": "KEEP_GIFT"
},
"additionalDiscountsMarkers": [],
"totalRaw": 400,
"totalSumWithDiscount": 400,
"excludedGiftProductIds": [],
"bonus": {
"availableBalance": 0,
"maxBonusDiscount": 0,
"minBonusAmount": null,
"minOrderAmountForBonus": null,
"bonusApplied": 0
},
"bonusApplied": 0,
"totalDue": 400
},
"isPartial": false,
"isCompleted": false
}
],
"total": 1
}

7. Kiểm tra xem có đăng ký hoạt động hay không

Ví dụ:

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,
);

8. Nếu đăng ký đang hoạt động, chúng tôi cung cấp quyền truy cập, nếu không chúng tôi tạo một đơn hàng và tạo thanh toán

Ví dụ:

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: '2026-05-07T00:00:00.000Z',
formattedValue: '07-05-2026 00:00',
formatString: 'DD-MM-YYYY HH:mm',
},
},
{
// A `list` field takes an array of the selected option values
// (plain strings), not option objects. '1' = the "1 month" option.
type: 'list',
marker: 'subscription_time',
value: ['1'],
},
],
products: [
{
productId: 15,
quantity: 1,
},
],
};
const order = await Orders.createOrder('subscriptions', body);

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

const payment = await Payments.createSession(order.id, 'session', false);
console.log('💸 Proceed to pay for your subscription:', payment);
}

Ví dụ cuối cùng

// 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 with [defineOneEntry()](/docs/index/#Installation)
const { Users, Orders, Pages, Payments, AuthProvider, Forms } = defineOneEntry(
PROJECT_URL,
{
token: APP_TOKEN,
},
);

// 3. Get form
const form = await Forms.getFormByMarker('subscription');
console.log(form);
// expired_date - Date
// subscription_time - list

// 4. Preparing data for user authorization
const authData = [
{ marker: 'email_reg', value: 'your-email' },
{ marker: 'password_reg', value: 'your-password' },
];

// 5. Authorization and obtaining user data with [AuthProvider.auth()](/docs/auth-provider/auth)
const authResponse = await AuthProvider.auth('email', { authData });
console.log(authResponse);

const user = await Users.getUser();
console.log(user);

// 6. We get a list of user orders with [Orders.getAllOrdersByMarker()](/docs/orders/getAllOrdersByMarker)
const orders = await Orders.getAllOrdersByMarker('subscriptions');

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

// 7. 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,
);

// 8. 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: '2026-05-07T00:00:00.000Z',
formattedValue: '07-05-2026 00:00',
formatString: 'DD-MM-YYYY HH:mm',
},
},
{
// A `list` field takes an array of the selected option values
// (plain strings), not option objects. '1' = the "1 month" option.
type: 'list',
marker: 'subscription_time',
value: ['1'],
},
],
products: [
{
productId: 15,
quantity: 1,
},
],
};
const order = await Orders.createOrder('subscriptions', body);

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

const payment = await Payments.createSession(order.id, 'session', false);
console.log('💸 Proceed to pay for your subscription:', payment);
}