├── README.md ├── new-voicemails-nodejs ├── .env.dist ├── .gitignore ├── README.md ├── index.js └── package.json └── webapp-nodejs ├── .gitignore ├── .npmrc.dist ├── README.md ├── index.js └── package.json /README.md: -------------------------------------------------------------------------------- 1 | # sipgate REST API examples 2 | 3 | This repository shows you how to use the [sipgate REST API](https://developer.sipgate.io/v2.0/reference). You can find more information in the [sipgate API Developer Hub](https://developer.sipgate.io). 4 | 5 | ## Examples 6 | 7 | * `webapp-nodejs`: simple Node.js web application with OAuth authentication 8 | * `new-voicemails-nodejs`: Node.js script that retrieves new sipgate voicemails -------------------------------------------------------------------------------- /new-voicemails-nodejs/.env.dist: -------------------------------------------------------------------------------- 1 | EMAIL=you@example.com 2 | PASSWORD=87654321 3 | POLLING_INTERVAL_MS=60000 -------------------------------------------------------------------------------- /new-voicemails-nodejs/.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .env 3 | -------------------------------------------------------------------------------- /new-voicemails-nodejs/README.md: -------------------------------------------------------------------------------- 1 | # Check For New sipgate Voicemails 2 | 3 | This project gives you a way to easily process all new voicemails for a sipgate user using callbacks. 4 | 5 | ## Install 6 | 7 | 1. Download this project. 8 | 2. Install NPM dependencies: `npm install` 9 | 3. Copy `.env.dist` to `.env` and fill `USERNAME` and `PASSWORD` with your credentials. 10 | 4. Run application: `npm start` -------------------------------------------------------------------------------- /new-voicemails-nodejs/index.js: -------------------------------------------------------------------------------- 1 | require("dotenv").config(); 2 | const moment = require("moment"); 3 | const request = require("request-promise-native"); 4 | 5 | const apiUrl = "https://api.sipgate.com/v1"; 6 | const NO_OP = () => {}; 7 | const email = process.env.EMAIL; 8 | const password = process.env.PASSWORD; 9 | 10 | const getAccessToken = (email, password) => 11 | request({ 12 | uri: `${apiUrl}/authorization/token`, 13 | method: "POST", 14 | body: { 15 | username: email, 16 | password 17 | }, 18 | json: true 19 | }).then(result => result.token); 20 | 21 | const getHistory = (accessToken, userId = "w0") => 22 | request({ 23 | uri: `${apiUrl}/${userId}/history`, 24 | qs: { 25 | types: "VOICEMAIL" 26 | }, 27 | headers: { 28 | "User-Agent": "Request-Promise", 29 | authorization: `Bearer ${accessToken}` 30 | }, 31 | json: true 32 | }); 33 | 34 | const getNewVoiceMails = ( 35 | since = moment(0), 36 | onPolling = NO_OP, 37 | onNewVoiceMails = NO_OP 38 | ) => { 39 | getAccessToken(email, password) 40 | .then(accessToken => { 41 | getHistory(accessToken) 42 | .then(result => { 43 | const newItems = result.items.filter( 44 | item => moment(item.created) - since > 0 45 | ); 46 | if (newItems.length > 0) { 47 | onNewVoiceMails(newItems); 48 | } 49 | 50 | const mostRecentItem = result.items 51 | .map(item => moment(item.created)) 52 | .reduce((current, acc) => moment.max(current, acc), since); 53 | onPolling(mostRecentItem); 54 | }) 55 | .catch(error => console.error("Unable to retrieve history", error)); 56 | }) 57 | .catch(error => console.error("Unable to retrieve access token", error)); 58 | }; 59 | 60 | const watchVoiceMails = (onNewVoiceMails = NO_OP) => { 61 | let mostRecentHistoryItem = moment(0); 62 | 63 | getNewVoiceMails(mostRecentHistoryItem, mostRecentItem => { 64 | mostRecentHistoryItem = mostRecentItem; 65 | setInterval( 66 | () => 67 | getNewVoiceMails( 68 | mostRecentHistoryItem, 69 | mostRecentItem => { 70 | mostRecentHistoryItem = mostRecentItem; 71 | }, 72 | onNewVoiceMails 73 | ), 74 | process.env.POLLING_INTERVAL_MS || 60000 75 | ); 76 | }); 77 | }; 78 | 79 | watchVoiceMails(voiceMails => { 80 | voiceMails.forEach(voiceMail => { 81 | console.log(`You received a new voicemail from ${voiceMail.source}, saying: "${voiceMail.transcription}". 82 | You can retrieve it from ${voiceMail.recordingUrl}.`); 83 | }); 84 | }); 85 | -------------------------------------------------------------------------------- /new-voicemails-nodejs/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "sipgate-new-voicemails", 3 | "version": "0.0.1", 4 | "private": true, 5 | "description": "Node.js script that retrieves new sipgate voicemails", 6 | "main": "index.js", 7 | "scripts": { 8 | "start": "node index.js" 9 | }, 10 | "license": "MIT", 11 | "dependencies": { 12 | "dotenv": "^4.0.0", 13 | "moment": "^2.24.0", 14 | "request": "^2.88.0", 15 | "request-promise-native": "^1.0.7" 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /webapp-nodejs/.gitignore: -------------------------------------------------------------------------------- 1 | .npmrc 2 | /node_modules 3 | -------------------------------------------------------------------------------- /webapp-nodejs/.npmrc.dist: -------------------------------------------------------------------------------- 1 | port=3000 2 | client_id=2414245-0-e24e0091-8265-11e7-93e7-e5fb754b756f 3 | client_secret=187812ce-b546-4fa9-96e8-771e9775c3cb 4 | 5 | -------------------------------------------------------------------------------- /webapp-nodejs/README.md: -------------------------------------------------------------------------------- 1 | # Simple sipgate REST API demo project 2 | 3 | This project shows how to use the [sipgate REST API](https://developer.sipgate.io/v2.0/reference). You can find the [step-by-step guide](https://developer.sipgate.io/v2.0/docs/building-a-third-party-application-using-oauth-clients) in our developer portal. 4 | 5 | ## Install 6 | 7 | 1. Download this project. 8 | 2. Install NPM dependencies: `npm install` 9 | 3. [Create your own API client using the command line.](https://developer.sipgate.io/v2.0/docs/managing-third-party-clients-using-the-command-line) 10 | 4. Copy `.npmrc.dist` to `.npmrc` and fill `client_id` and `client_secret` with your generated credentials. 11 | 5. Run application: `npm start` 12 | 6. Visit [localhost:3000](http://localhost:3000). 13 | -------------------------------------------------------------------------------- /webapp-nodejs/index.js: -------------------------------------------------------------------------------- 1 | const queryString = require('querystring'); 2 | const express = require('express'); 3 | const session = require('express-session'); 4 | const request = require('request-promise-native'); 5 | const createApiClient = require('sipgate-rest-api-client').default; 6 | 7 | // sipgate REST API settings 8 | const apiUrl = 'https://api.sipgate.com/v2'; 9 | const desiredScope = 'balance:read'; 10 | const clientId = process.env.npm_config_client_id; 11 | const clientSecret = process.env.npm_config_client_secret; 12 | 13 | if (!clientId || clientId === 'CLIENT_ID' || !clientSecret || clientSecret === 'CLIENT_SECRET') { 14 | console.log('Please provide a client id and secret in this project .npmrc file.'); 15 | process.exit(1); 16 | } 17 | 18 | // URL constants 19 | const port = process.env.npm_config_port; 20 | const appUrl = `http://localhost:${port}`; 21 | const authPath = '/authorize'; 22 | const authRedirectUrl = `${appUrl}${authPath}`; 23 | const authUrl = `https://api.sipgate.com/login/third-party/protocol/openid-connect`; 24 | const apiAuthUrl = `${authUrl}/auth?` + queryString.stringify({ 25 | client_id: clientId, 26 | redirect_uri: authRedirectUrl, 27 | scope: desiredScope, 28 | response_type: 'code', 29 | }); 30 | 31 | 32 | // Initialize express app 33 | const app = express(); 34 | app.use(session({ 35 | secret: 'sipgate-rest-api-demo', 36 | cookie: { maxAge: 60000 }, 37 | resave: false, 38 | saveUninitialized: false 39 | })); 40 | 41 | app.get('/', function (req, res) { 42 | const accessToken = req.session['accessToken']; 43 | 44 | if (!accessToken) { 45 | res.redirect(authPath); 46 | return; 47 | } 48 | 49 | const apiClient = createApiClient(apiUrl, accessToken); 50 | apiClient.getBalance() 51 | .then(function (response) { 52 | if (!(response['amount'] && response['currency'])) { 53 | throw 'Malformed response'; 54 | } 55 | 56 | const balanceFormatted = (parseInt(response['amount'], 10) / 10000).toFixed(2); 57 | res.send(`Your sipgate account balance is ${balanceFormatted} ${response['currency']}.`); 58 | }) 59 | .catch(function(reason) { 60 | if (reason === 'Unauthorized') { 61 | res.redirect(authPath); 62 | return; 63 | } 64 | res.send('Sorry, something went wrong. Please try again.'); 65 | }); 66 | }); 67 | 68 | const fetchToken = function(url, authorizationCode) { 69 | console.log({ url, authorizationCode }); 70 | return request.post({ 71 | url, 72 | form: { 73 | client_id: clientId, 74 | client_secret: clientSecret, 75 | code: authorizationCode, 76 | redirect_uri: authRedirectUrl, 77 | grant_type: 'authorization_code', 78 | }, 79 | simple: false, 80 | resolveWithFullResponse: true, 81 | }) 82 | .then(function(response) { 83 | console.log('status', response.statusCode); 84 | if ([307, 308].includes(response.statusCode)) { 85 | return fetchToken(response.headers['location'], authorizationCode); 86 | } 87 | return response; 88 | }) 89 | }; 90 | 91 | app.get(authPath, function (req, res) { 92 | 93 | const authorizationCode = req.query.code; 94 | 95 | if (!authorizationCode) { 96 | console.log("Not authenticated yet! Redirecting to " + apiAuthUrl); 97 | res.redirect(apiAuthUrl); 98 | return; 99 | } 100 | 101 | console.log("Got authorization code: " + authorizationCode); 102 | 103 | fetchToken(`${authUrl}/token`, authorizationCode) 104 | .then(function (response) { 105 | const body = response.body; 106 | const payload = JSON.parse(body); 107 | console.log("Got authorization data", payload) 108 | req.session['accessToken'] = payload['access_token']; 109 | res.redirect('/'); 110 | }) 111 | .catch(function (e) { 112 | console.log("Error getting access_token", e); 113 | res.redirect(apiAuthUrl); 114 | }); 115 | }); 116 | 117 | app.listen(port, function () { 118 | console.log(`Listening on port ${port}. Open ${appUrl} in your browser.`); 119 | }); 120 | -------------------------------------------------------------------------------- /webapp-nodejs/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "sipgate-rest-api-demo", 3 | "version": "0.0.1", 4 | "private": true, 5 | "description": "Simple sipgate REST API demo", 6 | "main": "index.js", 7 | "scripts": { 8 | "start": "node index.js", 9 | "start:dev": "nodemon index.js" 10 | }, 11 | "license": "MIT", 12 | "dependencies": { 13 | "express": "^4.17.1", 14 | "express-session": "^1.16.2", 15 | "request": "^2.88.0", 16 | "request-promise-native": "^1.0.7", 17 | "sipgate-rest-api-client": "^1.15.0" 18 | }, 19 | "devDependencies": { 20 | "nodemon": "^1.19.1" 21 | } 22 | } 23 | --------------------------------------------------------------------------------