Thumbnail
WhatsApp Business API | Integration for Slack
New

Easy steps to follow for integrating your existing slack team account with WhatsApp.

Introduction

A. Create a slack app:

1. Login into api.slack.com

2. Click your Apps in top right corner of your window https://slack.com/

3. Click create new app button

4. Enter the app name and select the slack workspace which you are going to use for agent conversation with the WhatsApp users. If you do not have any existing workspace, create a new one on https://slack.com/

B. Create slash command to initialize the channel to receive or send messages from/to whatsapp:

1. Navigate to the slack app you created above

2. From the Features section under left sidebar, click slash command

3. Click create new command button to create new slash command

C. Obtaining permissions to access your workspace through app:

1. From the Features section under left sidebar, click oauth & permission

2. Navigate to scope section and add necessary scope required for bot and user token as shown in the screenshot below

3. Once you added the necessary scope for the app you created. Click install/reinstall app button in the top section on that page.

4. On clicking that it will ask your workspace to allow the necessary scopes you asked for. Also, it will ask for the channel where you want to install the app. Select any channel where you want to receive/send messages to WhatsApp.

D. Event subscriptions to receive request to your webhook:

1. Navigate to Event subscriptions under left sidebar

2. Enable events from your slack by clicking toggle button on

3. Provide your server webhook url which will be triggered from the slack events. (go to section E to create the webhook needed)

4. You will get verified success when your url is triggered and challenge value should be exact

5. Under subscribe to events on behalf of users, add the needed events as in the screenshot below

6. Once you done subscribing click save changes button to complete your setup from slack end

E. NodeJS server setup to connect slack app with tyntec's WhatsApp Business API

1. Setup a basic node server. Create a file named index.js and paste the code given below.

2. Install the required dependencies. Express, cors, body-parser, mongoose, request

const express = require('express');
const app = express();
const cors = require('cors');
const bodyParser = require('body-parser');
const PORT = process.env.PORT || 4000;
app.use(cors())
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }))
app.get('/',(req, res)=>{
 res.status(200).send('server running')
})
app.listen(PORT, () => {
 console.log(`server started at port ${PORT}`)
})

3. Run the server with node index.js

4. Connect the mongodb with your code using mongoose as shown below

mongoose.connect('use your mongodb url here',{useNewUrlParser:true})
.then(success=>{
 console.log('Db connection success')
})
.catch(error=>{
 console.log('failed to establish db connection')
})

Right now code of your index.js look like this

'use strict'
const express = require('express');
const app = express();
const cors = require('cors');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const PORT = process.env.PORT || 4000;
mongoose.connect('use your mongodb url here',{useNewUrlParser:true})
.then(success=>{
 console.log('Db connection success')
})
.catch(error=>{
 console.log('failed to establish db connection')
})
app.use(cors())
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }))
app.get('/',(req, res)=>{
 res.status(200).send('server running')
})
require('./routes/route')(app);
app.listen(PORT, () => {
 console.log(`server started port ${PORT}`)
})

5. Create a new folder routes and add route.js file inside that and paste the code below

'use strict';
const Slack = require('./slack')
const Whatsapp = require('./whatsapp')
module.exports = (app) => {
 app.use('/tyntec,Whatsapp)
 app.use('/slack,Slack)
};

6. Create a file slack.js inside route which will hold slack routes and paste the code

const Router = require("express").Router();
Router.route('/')
 .post(async function (req, res) {
 try {
 // Fetch channel id and store in database.
 res.status(200).send("send your message to slack admin")
 } catch (error) {
 console.log("error in wataap.js", error)
 }
 });
Router.route('/receive')
 .post(async function (req, res) {
// do your coding stuff here
Let url = "https://api.tyntec.com/chat-api/v2/messages"
Let options = {
 url: url,
 headers: {
 'content-type': 'application/json',
 'apikey': 'XX---your api key'
 },
 json: true,
 body: {
 "to": to,
 "channels": [
 "whatsapp"
 ],
 "whatsapp": {
 "from": "XX--Your tyntec number",
 "contentType": "text",
 "text": text //msg goes here
 }
 }
 };
// use request dependencies and above data to send request
through POST method and finally send the success status to slack
res.sendStatus(200)
 });
module.exports = Router

7. Create a file whatsapp.js inside route which will hold tyntec's WhatsApp routes and paste the code.

'use strict'
const Router = require("express").Router();
Router.route('/webhook')
.post(async function (req, res) {
 try {
// This will trigger from tyntec when someone messages to your whatsapp
number. Use the below api to pass the message to slack
var url = "https://slack.com/api/chat.postMessage"
 var options = {
 url: url,
 headers: {
 'content-type': 'application/json',
 'Authorization': 'Bearer XX--your slack oauth app token'
 },
 json: true,
 body: {
 "channel":channelId //you stored previously on chat
initiation
 "text":”your message from whatsapp”,
 "as_user": false,
 "username": “whatsapp_user_name”,
 "thread_ts": thread, //This field is not required when
//user messages for the first time. Please refer to section F for
//further details.
 }
 };
// use request dependencies and above data to send request through POST
//method and finally send success status to tyntec
 res.status(200).send("Success");
 } catch (error) {
 console.log("error in wataap.js", error)
 }
})
module.exports = Router

F. Thread Usage

1. Every user conversation would be triggered in a separate thread. One thread for one whatsapp number (user)

2. To handle this, you have to store the thread id against each whatsapp number when the first message is received

3. All further messages from existing whatsapp number would be a part of the same thread. So you need to attach thread id along with other required params as mentioned in E7 (whatsapp.js)

G. Connect tyntec's WhatsApp API with your webhook

1. Ask tyntec's support team to add your endpoint to your active WhatsApp number. This is for the purpose of receiving the message from WhatsApp to your webhook.

 

All done. Please note that you need to use your slash command (defined in section B) on the connected channel to initialize the connection. Once anyone drops a message on whatsapp, you will receive the same on this channel.