UNPKG

lazada-iop-client

Version:

Lazada IOP Client SDK for Node JS

496 lines (495 loc) 14.9 kB
"use strict"; var __assign = (this && this.__assign) || function () { __assign = Object.assign || function (t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; var __createBinding = (this && this.__createBinding) || (Object.create ? function (o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if ( !desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable) ) { desc = { enumerable: true, get: function () { return m[k]; }, }; } Object.defineProperty(o, k2, desc); } : function (o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; }); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? function (o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); } : function (o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function (o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function () { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [], }, f, y, t, g = Object.create( (typeof Iterator === "function" ? Iterator : Object).prototype ); return ( (g.next = verb(0)), (g["throw"] = verb(1)), (g["return"] = verb(2)), typeof Symbol === "function" && (g[Symbol.iterator] = function () { return this; }), g ); function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while ((g && ((g = 0), op[0] && (_ = 0)), _)) try { if ( ((f = 1), y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) ) return t; if (((y = 0), t)) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if ( !((t = _.trys), (t = t.length > 0 && t[t.length - 1])) && (op[0] === 6 || op[0] === 2) ) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var __importDefault = (this && this.__importDefault) || function (mod) { return mod && mod.__esModule ? mod : { default: mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); var crypto = __importStar(require("crypto")); var axios_1 = __importDefault(require("axios")); var form_data_1 = __importDefault(require("form-data")); var SDK_VERSION = "lazop-sdk-js-20250422"; var AUTH_URL = "https://auth.lazada.com/oauth/authorize"; var APIGateway = { SG: "https://api.lazada.sg/rest", MY: "https://api.lazada.com.my/rest", VN: "https://api.lazada.vn/rest", TH: "https://api.lazada.co.th/rest", PH: "https://api.lazada.com.ph/rest", ID: "https://api.lazada.co.id/rest", }; var LazadaClient = /** @class */ (function () { function LazadaClient(_a) { var apiKey = _a.apiKey, apiSecret = _a.apiSecret, region = _a.region, callbackUrl = _a.callbackUrl, _b = _a.debug, debug = _b === void 0 ? false : _b; if (!APIGateway[region]) throw new Error("Unsupported region: ".concat(region)); this.apiKey = apiKey; this.apiSecret = apiSecret; this.region = region; this.callbackUrl = callbackUrl; this.debug = debug; this.sysParams = { app_key: this.apiKey, sign_method: "sha256", }; this.apiParams = {}; this.fileParams = {}; } LazadaClient.prototype.generateTimestamp = function () { return Date.now(); }; LazadaClient.prototype.getSysParams = function () { return __assign(__assign({}, this.sysParams), { timestamp: this.generateTimestamp(), }); }; LazadaClient.prototype.setAccessToken = function (token) { this.sysParams.access_token = token; return this; }; LazadaClient.prototype.changeRegion = function (region) { if (!APIGateway[region]) throw new Error("Unsupported region: ".concat(region)); this.region = region; return this; }; LazadaClient.prototype.addAPIParam = function (key, val) { this.apiParams[key] = val; return this; }; LazadaClient.prototype.addFileParam = function (key, val) { this.fileParams[key] = val; return this; }; LazadaClient.prototype.setCallbackUrl = function (url) { this.callbackUrl = url; }; LazadaClient.prototype.makeAuthURL = function () { var params = new URLSearchParams({ response_type: "code", force_auth: "true", country: this.region.toLowerCase(), redirect_uri: this.callbackUrl, client_id: this.apiKey, }); return "".concat(AUTH_URL, "?").concat(params.toString()); }; LazadaClient.prototype.requestToken = function (code) { return __awaiter(this, void 0, void 0, function () { var timestamp, sysParams, params, sign, allParams, urlParams, fullUrl, response, err_1; var _a; return __generator(this, function (_b) { switch (_b.label) { case 0: timestamp = this.generateTimestamp(); sysParams = this.getSysParams(); params = __assign(__assign({}, sysParams), { code: code, app_key: this.apiKey, sign_method: "sha256", timestamp: timestamp, }); sign = this.sign("/auth/token/create", params); allParams = __assign(__assign({}, params), { sign: sign }); urlParams = new URLSearchParams( Object.entries(allParams).map(function (_a) { var k = _a[0], v = _a[1]; return [k, String(v)]; }) ); fullUrl = "https://auth.lazada.com/rest/auth/token/create?".concat( urlParams.toString() ); if (this.debug) { console.log("🛠️ Lazada Token Request Debug:"); console.log("URL:", fullUrl); console.log("Params:", allParams); console.log("Sign:", sign); } _b.label = 1; case 1: _b.trys.push([1, 3, , 4]); return [4 /*yield*/, axios_1.default.get(fullUrl)]; case 2: response = _b.sent(); return [2 /*return*/, response.data]; case 3: err_1 = _b.sent(); if (this.debug) { console.error( "❌ Lazada API Error:", ((_a = err_1.response) === null || _a === void 0 ? void 0 : _a.data) || err_1.message ); } throw err_1; case 4: return [2 /*return*/]; } }); }); }; LazadaClient.prototype.sign = function (path, parameters) { var sortedKeys = Object.keys(parameters).sort(); var paramStr = path; if (this.debug) { console.log("🔐 SIGNING DEBUG:"); console.log("Path:", path); console.log("Sorted Params:"); sortedKeys.forEach(function (key) { console.log(" ".concat(key, ": ").concat(parameters[key])); }); } sortedKeys.forEach(function (key) { paramStr += key + String(parameters[key]); }); var signature = crypto .createHmac("sha256", this.apiSecret) .update(paramStr) .digest("hex") .toUpperCase(); if (this.debug) { console.log("🔏 Signature Base String:", paramStr); console.log("🔑 Signature Result:", signature); } return signature; }; LazadaClient.prototype.getServerURL = function () { var url = APIGateway[this.region]; if (!url) throw new Error('Region "'.concat(this.region, '" is not supported.')); return url; }; LazadaClient.prototype.execute = function (apiPath_1) { return __awaiter( this, arguments, void 0, function (apiPath, apiMethod, bodyParams) { var sysParams, sign, allParams, urlParams, fullUrl, config, form_1, response, err_2; var _a; if (apiMethod === void 0) { apiMethod = "GET"; } if (bodyParams === void 0) { bodyParams = {}; } return __generator(this, function (_b) { switch (_b.label) { case 0: sysParams = this.getSysParams(); sign = this.sign( apiPath, __assign(__assign({}, sysParams), this.apiParams) ); allParams = __assign( __assign(__assign({}, sysParams), this.apiParams), { sign: sign } ); urlParams = new URLSearchParams( Object.entries(allParams).map(function (_a) { var k = _a[0], v = _a[1]; return [k, String(v)]; }) ); fullUrl = "" .concat(this.getServerURL()) .concat(apiPath, "?") .concat(urlParams.toString()); if (this.debug) { console.log("🛠️ Lazada Request Debug:"); console.log("URL:", fullUrl); console.log("Method:", apiMethod); console.log("Sys Params:", sysParams); console.log("API Params:", this.apiParams); console.log("Sign:", sign); } config = { method: apiMethod, url: fullUrl, headers: {}, }; if (apiMethod === "POST") { form_1 = new form_data_1.default(); Object.entries(this.apiParams).forEach(function (_a) { var key = _a[0], val = _a[1]; return form_1.append(key, String(val)); }); Object.entries(bodyParams).forEach(function (_a) { var key = _a[0], val = _a[1]; return form_1.append(key, String(val)); }); Object.entries(this.fileParams).forEach(function (_a) { var filename = _a[0], buffer = _a[1]; return form_1.append("image", buffer, filename); }); config.data = form_1; config.headers = form_1.getHeaders(); } _b.label = 1; case 1: _b.trys.push([1, 3, 4, 5]); return [4 /*yield*/, (0, axios_1.default)(config)]; case 2: response = _b.sent(); return [2 /*return*/, response.data]; case 3: err_2 = _b.sent(); if (this.debug) { console.error( "❌ Lazada API Error:", ((_a = err_2.response) === null || _a === void 0 ? void 0 : _a.data) || err_2.message ); } throw err_2; case 4: this.apiParams = {}; this.fileParams = {}; return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); } ); }; return LazadaClient; })(); exports.default = LazadaClient;