cybairfly / amio-sdk-js

Server-side javascript library for Amio.io API.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

amio-sdk-js

CircleCI npm version

Server-side library implementing Amio API for instant messengers. It covers API calls and webhooks.

We'll be more than happy if you report any issues or even create pull requests ;-). Let us know how to improve this lib, thank you!

Installation

npm install amio-sdk-js --save

API

API - setup & usage

const AmioApi = require('amio-sdk-js').AmioApi

const amioApi = new AmioApi({
    accessToken: 'get access token from https://app.amio.io/administration/settings/api'
})

// example request
amioApi.messages.send({/* message */})

API - error handling

Amio API errors keep the structure described in the docs.

try{
  // ...
} catch(err){
    if (err.amioApiError) {
      console.error(err.jsonify(), err) 
      return
    }
    
    console.error(err) 
}

API - methods

REST js Description
POST /v1/messages messages.send(message) Send a message to a contact. There are different message types for every platform (FB, Viber).

Webhooks

Central logic to handle webhooks coming from Amio is WebhookRouter. What does it do?

  • It responds OK 200 to Amio .
  • It verifies X-Hub-Signature.
  • It routes events to handlers (e.g. event message_received to a method registered in amioWebhookRouter.onMessageReceived())

Webhooks - setup & usage

  1. Setup WebhookRouter.
const WebhookRouter = require('amio-sdk-js').WebhookRouter

const amioWebhookRouter = new WebhookRouter({
    secretToken: 'get secret at https://app.amio.io/administration/channels/{{CHANNEL_ID}}/webhook'
})

// error handling, e.g. x-hub-signature is not correct
amioWebhookRouter.onError(error => console.error(error))

// assign event handlers 
amioWebhookRouter.onMessageReceived(handleMessageReceived)
amioWebhookRouter.onMessagesDelivered(handleMessageDelivered)
amioWebhookRouter.onMessagesRead(handleMessagesRead)
amioWebhookRouter.onMessageEcho(handleMessageEcho)
  1. Route incoming requests to WebhookRouter. You will probably NOT want to use a common error handler!!!
// example with Express.js 4
const express = require('express')
const router = express.Router()


router.post('/webhooks/amio-communicator', async (req, res) => {
    await amioWebhookHandler.handleEvent(req, res)
})
  1. Implement event handlers.
amioWebhookRouter.onMessageReceived((data, timestamp) => {
    console.log('a new message from contact ${data.contact.id} was received!')
})

Webhooks - event types

Facebook:

Viber:

Missing a feature?

File an issue or create a pull request. If you need a quick solution, use the prepared axios http client:

const amioHttpClient = require('amio-sdk-js').amioHttpClient

amioHttpClient.get('/v1/messages')
    .then(response => {
      // ...
    })

About

Server-side javascript library for Amio.io API.


Languages

Language:JavaScript 100.0%