• Stars
    star
    100
  • Rank 340,703 (Top 7 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 4 years ago
  • Updated 9 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

This library helps you easily create a javascript application with Whatsapp support

whatsapp-api-client library for javascript

build License GitHub release npm version

This library helps you easily create a javascript application to connect the WhatsApp API using service green-api.com. You need to get ID_INSTANCEand API_TOKEN_INSTANCE in the control panel in order to use this library. It's free for developers.

API

The API corresponds with REST API from green-api since the library wraps own methods as https calls to the service. Therefore using these docs is highly encouraged.

Installing

Library supports both browser environment without package managers and Node/Webpack apps with package manager that can handle require or import module expressions. For webpack and npm based apps:

npm i @green-api/whatsapp-api-client

For vanilla html-js website modify index.html:

<script src="https://unpkg.com/@green-api/whatsapp-api-client/lib/whatsapp-api-client.min.js"></script>

Importing

There are several ways to import the library in a project

Using common javascript

const whatsAppClient = require("@green-api/whatsapp-api-client");

Using ES6 javascript

import whatsAppClient from "@green-api/whatsapp-api-client";

Using typescript

import * as whatsAppClient from "@green-api/whatsapp-api-client";

Using browser javascript

<script src="https://unpkg.com/@green-api/whatsapp-api-client/lib/whatsapp-api-client.min.js"></script>

Authentification

Sending WhatsApp message like any other call to the API requires account registered on green-api.com and authentication completed on mobile WhatsApp app. To register account you have to proceed to the control panel. After registering you wll get own unique pair of ID_INSTANCE and API_TOKEN_INSTANCE keys.

WhatsApp mobile app authentication may be achived by using control panel. You need to scan QR-code generated within the control panel.

Examples

Please do not use 'phoneNumber' parameter when calling methods. It is deprecated. Examples below are based on 'chatId' paramemeter

Send WhatsApp message

Use common javascript

const whatsAppClient = require("@green-api/whatsapp-api-client");

const restAPI = whatsAppClient.restAPI({
  idInstance: "YOUR_ID_INSTANCE",
  apiTokenInstance: "YOUR_API_TOKEN_INSTANCE",
});

restAPI.message.sendMessage("[email protected]", null , "hello world").then((data) => {
  console.log(data);
});

or use browser js script

<script src="https://unpkg.com/@green-api/whatsapp-api-client/lib/whatsapp-api-client.min.js"></script>
<script>
  const restAPI = whatsAppClient.restAPI({
    idInstance: "YOUR_ID_INSTANCE",
    apiTokenInstance: "YOUR_API_TOKEN_INSTANCE",
  });
  restAPI.message
    .sendMessage("[email protected]", null, "hello world")
    .then((data) => {
      console.log(data);
    })
    .catch((reason) => {
      console.error(reason);
    });
</script>

Or use ES6 syntax. For node js app, you propably have to add in package.json property "type": "module". Notice that all examples below are ES6 based.

import whatsAppClient from "@green-api/whatsapp-api-client";

(async () => {
  const restAPI = whatsAppClient.restAPI({
    idInstance: "YOUR_ID_INSTANCE",
    apiTokenInstance: "YOUR_API_TOKEN_INSTANCE",
  });
  const response = await restAPI.message.sendMessage(
    "[email protected]",
    null,
    "hello world"
  );
})();

Using credentials file for ID_INSTANCE and API_TOKEN_INSTANCE keys (nodejs only!)

You might want to store yours credentials separatedly from code. The library allow you to create a text file with preferred name and location with the format:

API_TOKEN_INSTANCE = "MY_API_TOKEN_INSTANCE"
ID_INSTANCE = "MY_ID_INSTANCE"

And then pass this file as described below:

const restAPI = whatsAppClient.restAPI({
  credentialsPath: "examples\\credentials",
});

Receive notifications using webhook service REST API

import whatsAppClient from "@green-api/whatsapp-api-client";

(async () => {
  let restAPI = whatsAppClient.restAPI({
    idInstance: "YOUR_ID_INSTANCE",
    apiTokenInstance: "YOUR_API_TOKEN_INSTANCE",
  });

  try {
    // Receive WhatsApp notifications.
    console.log("Waiting incoming notifications...");
    await restAPI.webhookService.startReceivingNotifications();
    restAPI.webhookService.onReceivingMessageText((body) => {
      console.log(body);
      restAPI.webhookService.stopReceivingNotifications();
      //console.log("Notifications is about to stop in 20 sec if no messages will be queued...")
    });
    restAPI.webhookService.onReceivingDeviceStatus((body) => {
      console.log(body);
    });
    restAPI.webhookService.onReceivingAccountStatus((body) => {
      console.log(body);
    });
  } catch (ex) {
    console.error(ex.toString());
  }
})();

Send WhatsApp file

import whatsAppClient from "@green-api/whatsapp-api-client";

(async () => {
  const restAPI = whatsAppClient.restAPI({
    idInstance: "YOUR_ID_INSTANCE",
    apiTokenInstance: "YOUR_API_TOKEN_INSTANCE",
  });
  const response = await restAPI.file.sendFileByUrl(
    "[email protected]",
    null,
    "https://avatars.mds.yandex.net/get-pdb/477388/77f64197-87d2-42cf-9305-14f49c65f1da/s375",
    "horse.png",
    "horse"
  );
})();

Send WhatsApp message and receive webhook

Webhooks are event-based callbacks invoked by green-api server as responses to client API calls. Webhooks support node js and express based apps only.

import whatsAppClient from "@green-api/whatsapp-api-client";
import express from "express";
import bodyParser from "body-parser";

(async () => {
  try {
    // Set http url, where webhooks are hosted.
    // Url must have public domain address.
    await restAPI.settings.setSettings({
      webhookUrl: "MY_HTTP_SERVER:3000/webhooks",
    });

    const app = express();
    app.use(bodyParser.json());
    const webHookAPI = whatsAppClient.webhookAPI(app, "/webhooks");

    // Subscribe to webhook happened when WhatsApp delivered a message
    webHookAPI.onIncomingMessageText(
      (data, idInstance, idMessage, sender, typeMessage, textMessage) => {
        console.log(`outgoingMessageStatus data ${data.toString()}`);
      }
    );

    // Run web server with public domain address
    app.listen(3000, async () => {
      console.log(`Started. App listening on port 3000!`);

      const restAPI = whatsAppClient.restAPI({
        idInstance: MY_ID_INSTANCE,
        apiTokenInstance: MY_API_TOKEN_INSTANCE,
      });
      // Send test message that triggers webhook
      const response = await restAPI.message.sendMessage(
        "[email protected]",
        null,
        "hello world"
      );
    });
  } catch (error) {
    console.error(error);
    process.exit(1);
  }
})();

There's some cool examples too.

Deploying development environment

Any help with development and bug fixing is appreciated. In order to deploy test-ready environment please make the steps:

  1. Сlone repo with git clone
  2. Install dependencies with npm install
  3. Install globally libraries rollup for bundled builds.
  4. Add webhooks as new dev express via npm npm install express --save-dev. Dont forget to delete it before making pull request
  5. Create .env file in root folder and add environment variables using example file env.example
  6. Add "type": "module" to the package.json

Build

Compile browser and node|webpack versions with single command:

npm run build

Publish to npm if you have access

npm publish

Third-party libraries

License

Licensed on MIT terms. For additional info have look at LICENSE

More Repositories

1

whatsapp-api-client-python

This library helps you easily create a Python application with WhatsApp API.
Python
126
star
2

whatsapp-chatbot-python

This library helps you easily create a python chatbot application with WhatsApp API
Python
27
star
3

whatsapp-chatbot-js

The library to develop WhatsApp bot
JavaScript
23
star
4

whatsapp-chatbot-1c

Внешняя обработка для программы 1С:Предприятие, которая демонстрирует реализацию простого чат-бота для мессенджера WhatsApp.
1C Enterprise
18
star
5

whatsapp-api-client-1c

Внешняя обработка для программы 1С:Предприятие, которая демонстрирует основные приемы работы с WhatsApp API и является АПИ оберткой.
1C Enterprise
14
star
6

docs

Green API docs (ru, en, pt)
HTML
10
star
7

whatsapp-api-client-php

This library helps you easily create a php application with WhatsApp API
PHP
9
star
8

green-api-postman-collection

Green API Postman Collection
8
star
9

whatsapp-api-webhook-server-python

Create a python server endpoint to get WhatsApp messages webhooks
Python
7
star
10

issues

7
star
11

whatsapp-api-client-java

This library helps you easily create a Java application to send WhatsApp messages
Java
4
star
12

whatsapp-api-webhook-server-java

Create a Java server endpoint to get WhatsApp messages webhooks
Java
4
star
13

v1-docs

Green API documents v1
CSS
3
star
14

v1-whatsapp-api-client

WhatsApp API phone-free wrapper library
TypeScript
3
star
15

whatsapp-api-client-golang

Create a golang application with WhatsApp API
Go
3
star
16

v1-green-api-postman-collection

Green API Postman Collection v1
2
star
17

whatsapp-chatbot-golang

This library helps you easily create a golang chatbot application with WhatsApp API
Go
2
star
18

simple-reg-bot

Sample WhatsApp bot using docker container
TypeScript
2
star
19

partners-green-api-postman-collection

2
star
20

whatsapp-chatbot-java

Java
2
star
21

whatsapp-demo-chatbot-python

A python chatbot application built for WhatsApp
Python
1
star
22

whatsapp-api-webhook-server-golang

Create a golang server endpoint to get WhatsApp messages webhooks
Go
1
star
23

whatsapp-api-client-1c-cs

Расширение 1С: Предприятие, которое демонстрирует интеграцию мессенджера WhatsApp с Системой взаимодействия
1C Enterprise
1
star