@warriorteam/redai-zalo-sdk
Version:
Comprehensive TypeScript/JavaScript SDK for Zalo APIs - Official Account v3.0, ZNS with Full Type Safety, Consultation Service, Broadcast Service, Group Messaging with List APIs, Social APIs, Enhanced Article Management, Promotion Service v3.0 with Multip
305 lines • 11.4 kB
JavaScript
"use strict";
/**
* Main Zalo SDK class
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.ZaloSDK = void 0;
const zalo_client_1 = require("./clients/zalo-client");
const auth_service_1 = require("./services/auth.service");
const oa_service_1 = require("./services/oa.service");
// import { MessageService } from "./services/message.service"; // Replaced by specialized services
const user_service_1 = require("./services/user.service");
// import { WebhookService } from "./services/webhook.service";
const zns_service_1 = require("./services/zns.service");
const group_message_service_1 = require("./services/group-message.service");
const group_management_service_1 = require("./services/group-management.service");
const article_service_1 = require("./services/article.service");
const video_upload_service_1 = require("./services/video-upload.service");
// Message Services
const consultation_service_1 = require("./services/consultation.service");
const transaction_service_1 = require("./services/transaction.service");
const promotion_service_1 = require("./services/promotion.service");
const general_message_service_1 = require("./services/general-message.service");
const message_management_service_1 = require("./services/message-management.service");
const broadcast_service_1 = require("./services/broadcast.service");
const purchase_service_1 = require("./services/purchase.service");
const common_1 = require("./types/common");
// import { WebhookHandlers } from "./types/webhook";
/**
* Main Zalo SDK class providing access to all Zalo APIs
*/
class ZaloSDK {
constructor(config) {
// Validate required configuration
if (!config.appId) {
throw new common_1.ZaloSDKError("appId is required in SDK configuration");
}
if (!config.appSecret) {
throw new common_1.ZaloSDKError("appSecret is required in SDK configuration");
}
// Set default configuration
this.config = {
appId: config.appId,
appSecret: config.appSecret,
timeout: config.timeout || 30000,
debug: config.debug || false,
apiBaseUrl: config.apiBaseUrl || "https://openapi.zalo.me",
retry: {
attempts: config.retry?.attempts || 3,
delay: config.retry?.delay || 1000,
...config.retry,
},
};
this.logger = new common_1.ConsoleLogger(this.config.debug);
this.client = new zalo_client_1.ZaloClient(this.config);
// Initialize services
this.auth = new auth_service_1.AuthService(this.client, this.config.appId, this.config.appSecret);
this.oa = new oa_service_1.OAService(this.client);
// this.message = new MessageService(this.client); // Replaced by specialized message services
this.user = new user_service_1.UserService(this.client);
// this.webhook = new WebhookService(this.config.appSecret, this.config.debug);
this.zns = new zns_service_1.ZNSService(this.client);
this.groupMessage = new group_message_service_1.GroupMessageService(this.client);
this.groupManagement = new group_management_service_1.GroupManagementService(this.client);
this.article = new article_service_1.ArticleService(this.client);
this.videoUpload = new video_upload_service_1.VideoUploadService(this.client);
// Initialize message services
this.consultation = new consultation_service_1.ConsultationService(this.client);
this.transaction = new transaction_service_1.TransactionService(this.client);
this.promotion = new promotion_service_1.PromotionService(this.client);
this.generalMessage = new general_message_service_1.GeneralMessageService(this.client);
this.messageManagement = new message_management_service_1.MessageManagementService(this.client);
this.broadcast = new broadcast_service_1.BroadcastService(this.client);
this.purchase = new purchase_service_1.PurchaseService(this.client);
this.logger.info("Zalo SDK initialized", {
appId: this.config.appId,
debug: this.config.debug,
timeout: this.config.timeout,
});
}
/**
* Quick method to get OA access token from authorization code
*/
async getOAAccessToken(code, redirectUri) {
const params = {
app_id: this.config.appId,
app_secret: this.config.appSecret,
code,
redirect_uri: redirectUri,
};
return this.auth.getOAAccessToken(params);
}
/**
* Quick method to get Social access token from authorization code
*/
async getSocialAccessToken(code, redirectUri, codeVerifier) {
const params = {
app_id: this.config.appId,
app_secret: this.config.appSecret,
code,
redirect_uri: redirectUri,
code_verifier: codeVerifier || "",
};
return this.auth.getSocialAccessToken(params);
}
/**
* Quick method to refresh OA access token
*/
async refreshOAAccessToken(refreshToken) {
const params = {
app_id: this.config.appId,
app_secret: this.config.appSecret,
refresh_token: refreshToken,
};
return this.auth.refreshOAAccessToken(params);
}
/**
* Quick method to refresh Social access token
*/
async refreshSocialAccessToken(refreshToken) {
const params = {
app_id: this.config.appId,
app_secret: this.config.appSecret,
refresh_token: refreshToken,
};
return this.auth.refreshSocialAccessToken(params);
}
/**
* Quick method to get OA information
*/
async getOAInfo(accessToken) {
return this.oa.getOAInfo(accessToken);
}
/**
* Quick method to get message quota
*/
async getMessageQuota(accessToken) {
return this.oa.getMessageQuota(accessToken);
}
/**
* Quick method to get Social user information
*/
async getSocialUserInfo(accessToken, fields) {
return this.auth.getSocialUserInfo(accessToken, fields);
}
/**
* Quick method to send consultation text message
*/
async sendConsultationText(accessToken, userId, text) {
return this.consultation.sendTextMessage(accessToken, { user_id: userId }, { type: "text", text });
}
/**
* Quick method to get user information
*/
async getUserInfo(accessToken, userId) {
return this.user.getUserInfo(accessToken, userId);
}
/**
* Quick method to get user list
*/
async getUserList(accessToken, request) {
return this.user.getUserList(accessToken, request);
}
/**
* Quick method to get all followers
*/
async getFollowers(accessToken) {
return this.user.getFollowers(accessToken);
}
/**
* Quick method to register webhook handlers
*/
// public registerWebhookHandlers(handlers: WebhookHandlers): void {
// this.webhook.registerHandlers(handlers);
// }
/**
* Quick method to process webhook
*/
// public async processWebhook(
// payload: string,
// signature?: string,
// timestamp?: string
// ): Promise<void> {
// return this.webhook.processWebhook(payload, signature, timestamp);
// }
/**
* Create OA authorization URL with PKCE support
* @deprecated Use auth.createOAAuthUrl() directly for full control over PKCE and state
*/
createOAAuthUrl(redirectUri, state) {
const result = this.auth.createOAAuthUrl(redirectUri, state, undefined, false);
return result.url;
}
/**
* Create OA authorization URL with full PKCE support
* Returns both URL and state for enhanced security
*/
createSecureOAAuthUrl(redirectUri, state, enablePKCE = true) {
const result = this.auth.createOAAuthUrl(redirectUri, state, undefined, enablePKCE);
return result;
}
/**
* Create Social authorization URL
*/
createSocialAuthUrl(redirectUri, state) {
return this.auth.createSocialAuthUrl(redirectUri, state);
}
/**
* Generate PKCE for Social API
*/
generatePKCE() {
return this.auth.generatePKCE();
}
/**
* Validate access token
*/
async validateAccessToken(accessToken, scope = "social") {
try {
if (scope === "oa") {
return this.oa.validateOAToken(accessToken);
}
else {
const validation = await this.auth.validateAccessToken(accessToken);
return validation.valid;
}
}
catch (error) {
this.logger.warn(`Token validation failed: ${error.message}`);
return false;
}
}
/**
* Get SDK version
*/
getVersion() {
return "1.0.0";
}
/**
* Get SDK configuration (without sensitive data)
*/
getConfig() {
const { appSecret, ...safeConfig } = this.config;
return safeConfig;
}
/**
* Enable or disable debug logging
*/
setDebug(enabled) {
this.config.debug = enabled;
// Note: ConsoleLogger debug setting is read-only, create new logger if needed
if (enabled !== this.config.debug) {
this.logger.info(`Debug mode ${enabled ? "enabled" : "disabled"}`);
}
}
/**
* Test SDK connectivity
*/
async testConnection() {
try {
// Try to make a simple request to test connectivity
const testUrl = `${this.config.apiBaseUrl}/v2.0/oa/getoa`;
await this.client.apiGet(testUrl, "test-token");
return true;
}
catch (error) {
// We expect this to fail with authentication error, not network error
if (error.message.includes("access_token") ||
error.message.includes("401")) {
return true; // Network is working, just auth failed as expected
}
this.logger.error(`Connection test failed: ${error.message}`);
return false;
}
}
/**
* Make a custom API request (advanced usage)
*/
async customRequest(method, endpoint, accessToken, data, params) {
switch (method) {
case "GET":
return this.client.apiGet(endpoint, accessToken, params);
case "POST":
return this.client.apiPost(endpoint, accessToken, data, params);
case "PUT":
return this.client.apiPut(endpoint, accessToken, data, params);
case "DELETE":
return this.client.apiDelete(endpoint, accessToken, params);
default:
throw new common_1.ZaloSDKError(`Unsupported HTTP method: ${method}`);
}
}
/**
* Upload file to Zalo API
*/
async uploadFile(endpoint, accessToken, file, filename, additionalFields) {
return this.client.apiUploadFile(endpoint, accessToken, file, filename, additionalFields);
}
/**
* Dispose SDK resources
*/
dispose() {
this.logger.info("Zalo SDK disposed");
}
}
exports.ZaloSDK = ZaloSDK;
//# sourceMappingURL=zalo-sdk.js.map