UNPKG

whatsapp-business

Version:

Node.js connector for the WhatsApp Business APIs with TypeScript support, integration tests and more.

299 lines (298 loc) 14 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 __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; return g = { next: verb(0), "throw": verb(1), "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 __rest = (this && this.__rest) || function (s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.WABAClient = void 0; var fs_1 = __importDefault(require("fs")); var form_data_1 = __importDefault(require("form-data")); var errorHandler_1 = require("./utils/errorHandler"); var restClient_1 = require("./utils/restClient"); /** * Connector for the Whatsapp Cloud API. * * documentation: https://developers.facebook.com/docs/whatsapp/cloud-api/guides */ var WABAClient = /** @class */ (function () { function WABAClient(_a) { var apiToken = _a.apiToken, phoneId = _a.phoneId, accountId = _a.accountId; this.phoneId = phoneId; this.accountId = accountId; this.restClient = (0, restClient_1.createRestClient)({ apiToken: apiToken, baseURL: "https://graph.facebook.com/v19.0", errorHandler: function (error) { var _a; return (0, errorHandler_1.WABAErrorHandler)(((_a = error === null || error === void 0 ? void 0 : error.response) === null || _a === void 0 ? void 0 : _a.data) || error); }, }); } /* * *BUSINESS PROFILE ENDPOINTS (https://developers.facebook.com/docs/whatsapp/cloud-api/reference/business-profiles) */ /** * * Retrieves your business profile. Customers can view your business profile by clicking your business's name or number in a conversation thread. * * @param fields you can specify which data you want to get from your business. If not passed, defaults to all fields. */ WABAClient.prototype.getBusinessProfile = function (fields) { return this.restClient.get("".concat(this.phoneId, "/whatsapp_business_profile"), { fields: (fields === null || fields === void 0 ? void 0 : fields.join(",")) || "about,address,description,email,profile_picture_url,websites,vertical", }); }; /** * @param payload provide the fields that you wish to update. */ WABAClient.prototype.updateBusinessProfile = function (payload) { return this.restClient.post("".concat(this.phoneId, "/whatsapp_business_profile"), __assign(__assign({}, payload), { messaging_product: "whatsapp" })); }; /* * * MEDIA ENDPOINTS (https://developers.facebook.com/docs/whatsapp/cloud-api/reference/media) * */ /** * All media files sent through this endpoint are encrypted and persist for 30 days, unless they are deleted earlier. * * A successful response returns an object with the uploaded media's ID. */ WABAClient.prototype.uploadMedia = function (_a) { var file = _a.file, type = _a.type; var formData = new form_data_1.default(); formData.append("type", type); formData.append("file", fs_1.default.createReadStream(file)); formData.append("messaging_product", "whatsapp"); return this.restClient.post("".concat(this.phoneId, "/media"), formData, { headers: { "Content-Type": "multipart/form-data" }, }); }; /** * Retrieves your media’s URL. Use the returned URL to download the media file. Note that clicking this URL (i.e. performing a generic GET) will not return the media; you must include an access token. * * A successful response includes an object with a media url. The URL is only valid for 5 minutes. */ WABAClient.prototype.getMedia = function (mediaId) { return this.restClient.get(mediaId); }; WABAClient.prototype.deleteMedia = function (mediaId) { return this.restClient.delete(mediaId); }; /** * @param mediaUrl your media’s URL * @param pathToSaveFile the path where you want to store the media */ WABAClient.prototype.downloadMedia = function (mediaUrl, pathToSaveFile) { return __awaiter(this, void 0, void 0, function () { var response, err_1; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); return [4 /*yield*/, this.restClient.get(mediaUrl, {}, { baseURL: "", responseType: "stream" })]; case 1: response = _a.sent(); return [2 /*return*/, response.pipe(fs_1.default.createWriteStream(pathToSaveFile))]; case 2: err_1 = _a.sent(); return [2 /*return*/, Promise.reject(err_1)]; case 3: return [2 /*return*/]; } }); }); }; /* * * MESSAGES ENDPOINTS (https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages) * */ /** * Yu can use the API to send the following free-form messages types: * Text * Reaction * Media * Location * Contacts * Interactive * Address * messages * template * * For more information refer here: https://developers.facebook.com/docs/whatsapp/cloud-api/guides/send-messages * * If you are working with template messages refer here: https://developers.facebook.com/docs/whatsapp/cloud-api/guides/send-message-templates * */ WABAClient.prototype.sendMessage = function (payload) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { return [2 /*return*/, this.restClient.post("".concat(this.phoneId, "/messages"), __assign(__assign({}, payload), { messaging_product: "whatsapp" }))]; }); }); }; /** * When you receive an incoming message from Webhooks, * you can use the /messages endpoint to mark the message as * read by changing its status to read. Messages marked as read display two blue check marks alongside their timestamp. */ WABAClient.prototype.markMessageAsRead = function (message_id) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { return [2 /*return*/, this.restClient.post("".concat(this.phoneId, "/messages"), { messaging_product: "whatsapp", status: "read", message_id: message_id, })]; }); }); }; /* * * PHONE NUMBERS ENDPOINTS (https://developers.facebook.com/docs/whatsapp/cloud-api/reference/phone-numbers) * */ WABAClient.prototype.getBusinessPhoneNumbers = function () { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { return [2 /*return*/, this.restClient.get("".concat(this.accountId, "/phone_numbers"))]; }); }); }; WABAClient.prototype.getSingleBusinessPhoneNumber = function (phoneNumberId) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { return [2 /*return*/, this.restClient.get(phoneNumberId)]; }); }); }; /** * You may want us to verify a customer's identity before we deliver your message to them. * You can have us do this by enabling the identity change check setting on your business phone number. */ WABAClient.prototype.updateIdentityCheckState = function (_a) { var enable_identity_key_check = _a.enable_identity_key_check; return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_b) { return [2 /*return*/, this.restClient.post("".concat(this.phoneId, "/settings"), { user_identity_change: { enable_identity_key_check: enable_identity_key_check, }, })]; }); }); }; WABAClient.prototype.requestPhoneNumberVerificationCode = function (_a) { var phoneNumberId = _a.phoneNumberId, payload = __rest(_a, ["phoneNumberId"]); return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_b) { return [2 /*return*/, this.restClient.post("".concat(phoneNumberId, "/request_code"), payload)]; }); }); }; WABAClient.prototype.verifyPhoneNumberCode = function (_a) { var phoneNumberId = _a.phoneNumberId, payload = __rest(_a, ["phoneNumberId"]); return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_b) { return [2 /*return*/, this.restClient.post("/".concat(phoneNumberId, "/verify_code"), payload)]; }); }); }; WABAClient.prototype.registerPhone = function (_a) { var phoneNumberId = _a.phoneNumberId, payload = __rest(_a, ["phoneNumberId"]); return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_b) { return [2 /*return*/, this.restClient.post("".concat(phoneNumberId, "/register"), __assign({ messaging_product: "whatsapp" }, payload))]; }); }); }; WABAClient.prototype.deregisterPhone = function (phoneNumber) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { return [2 /*return*/, this.restClient.post("".concat(phoneNumber, "/deregister"))]; }); }); }; WABAClient.prototype.setupTwoStepAuth = function (_a) { var phoneNumberId = _a.phoneNumberId, payload = __rest(_a, ["phoneNumberId"]); return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_b) { return [2 /*return*/, this.restClient.post(phoneNumberId, payload)]; }); }); }; /* * * HEALTH ENDPOINTS (https://developers.facebook.com/docs/whatsapp/cloud-api/health-status) * */ /** * * @param nodeId is optional, defaults to the account_id */ WABAClient.prototype.getHealthStatus = function (nodeId) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { return [2 /*return*/, this.restClient.get("".concat(this.accountId, "?fields=health_status"))]; }); }); }; return WABAClient; }()); exports.WABAClient = WABAClient;