Spusher API

Berichten kunnen eenvoudig verstuurd worden via de Spusher API.

Voor het toevoegen van een subscribe link wordt HMAC gebruikt met SHA256 voor het signeren van de link.

De link kun je plaatsen als QR code voor niet mobiele apparaten en direct als link of button op mobiel.

import { createHmac } from 'crypto'; import { URL } from 'url'; import { stringify } from 'querystring'; /** * Get a signed url for subscribing to a channel * @param {String} secret The secret for the channel * @param {String} channel The id of the channel * @param {String} [userId] Optionally link an id of the user for direct messaging * @param {Number} validTo The time until which this link will be valid in milliseconds elapsed since January 1, 1970 * @returns {String} */ function getSignedUrl({ secret, channel, userId, validTo }) { const params = { validTo, ...(userId ? { userId } : {}) }; const digest = createHmac('sha256', secret) .update(channel) .update(Object.keys(params) .filter(key => key !== 'digest') .sort((a, b) => a.localeCompare(b)) .map(key => params[key]) .join('') ) .digest('hex'); const url = new URL(`/channels/${channel}`, 'https://spusher.nl'); url.hash = '#' + stringify({ ...params, digest }); return url.toString(); }

Versturen van berichten

Het versturen van berichten kan met behulp van het posten van een JSON payload naar de url https://europe-west1-spusher-781ad.cloudfunctions.net/v1

import axios from 'axios'; async function sendMessage() { const channel = process.env.SPUSHER_CHANNEL; const secret = process.env.SPUSHER_SECRET; const api = axios.create({ baseURL: 'https://europe-west1-spusher-781ad.cloudfunctions.net/v1', headers: { authorization: `Bearer ${secret}` } }); try { await api.post(`/${channel}/post`, { body: 'Hello world!', link: '/' }); } catch (e) { if (e.isAxiosError) { throw `Axios request to ${e.config.url} failed with ${e.toString()}`; } else { throw e; } } }