All integrations

Bitrix24: SendHarbor as an SMS provider

A local application registers SendHarbor as an SMS provider. CRM cards and automation rules then send SMS through your connected phone, and delivery statuses come back to Bitrix24.

Bitrix24 registers SMS providers only from an application. An inbound webhook gets the error Application context required. A local application is enough: it works only in your Bitrix24 and needs no Marketplace publication.

The application needs a small relay on any server with HTTPS. The relay receives messages from Bitrix24 and status webhooks from SendHarbor. SendHarbor itself stays a hosted service.

What you need

No account or key yet? The quick start creates an account, connects your Android phone and shows ready code for this tool with your key. Quick start on your phone

How it works

  1. Bitrix24 sends each message to the relay.
  2. The relay queues it in SendHarbor and answers Bitrix24 with 200.
  3. SendHarbor sends signed status webhooks to the relay.
  4. The relay updates the message status in Bitrix24.

Steps

  1. Start the relay

    Save the code below as sendharbor-bitrix24.mjs on your server. It needs no packages and listens on 127.0.0.1:8788. Publish it at your HTTPS address with a reverse proxy that passes the request body unchanged.

    sendharbor-bitrix24.mjs
    // SendHarbor relay for Bitrix24: an SMS provider through a local application.
    // Node.js 24, no dependencies. Start: node --env-file=relay.env sendharbor-bitrix24.mjs
    import { createServer } from 'node:http';
    import { createHmac, timingSafeEqual } from 'node:crypto';
    import { readFileSync, writeFileSync, renameSync } from 'node:fs';
    
    const env = process.env;
    const SENDHARBOR_URL = 'https://sendharbor.app';
    const CODE = 'sendharbor';
    // SendHarbor phase -> Bitrix24 status. Other phases leave the Bitrix24 status as it is.
    const STATUS = { sent: 'sent', delivered: 'delivered', failed: 'failed', expired: 'undelivered', cancelled: 'undelivered' };
    const ENDPOINT = `https://${env.B24_DOMAIN}/rest/`;
    
    let state = { auth: null, sequences: {} };
    try { state = JSON.parse(readFileSync(env.STATE_FILE, 'utf8')); } catch {}
    function save() {
      writeFileSync(env.STATE_FILE + '.tmp', JSON.stringify(state), { mode: 0o600 });
      renameSync(env.STATE_FILE + '.tmp', env.STATE_FILE);
    }
    function same(a, b) {
      const x = Buffer.from(String(a ?? '')), y = Buffer.from(String(b ?? ''));
      return x.length > 0 && x.length === y.length && timingSafeEqual(x, y);
    }
    // Bitrix24 posts form fields such as auth[access_token].
    function nested(form, name) {
      return Object.fromEntries([...form].filter(([key]) => key.startsWith(name + '['))
        .map(([key, value]) => [key.slice(name.length + 1, -1), value]));
    }
    
    let refreshing = null;
    function refresh() {
      refreshing ??= (async () => {
        const url = new URL('https://oauth.bitrix.info/oauth/token/');
        url.search = new URLSearchParams({ grant_type: 'refresh_token', client_id: env.B24_CLIENT_ID,
          client_secret: env.B24_CLIENT_SECRET, refresh_token: state.auth.refresh_token });
        const body = await (await fetch(url, { signal: AbortSignal.timeout(10000) })).json();
        if (!body.access_token || (body.client_endpoint && body.client_endpoint !== ENDPOINT)) throw new Error('token refresh failed');
        state.auth = { ...state.auth, access_token: body.access_token, refresh_token: body.refresh_token };
        save();
      })().finally(() => { refreshing = null; });
      return refreshing;
    }
    async function bitrix(method, params, retry = true) {
      const response = await fetch(ENDPOINT + method, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ...params, auth: state.auth.access_token }),
        signal: AbortSignal.timeout(10000),
      });
      const body = await response.json().catch(() => ({}));
      if (body.error === 'expired_token' && retry) { await refresh(); return bitrix(method, params, false); }
      if (!response.ok || body.error) throw new Error(`${method}: ${body.error || response.status}`);
      return body.result;
    }
    
    async function install(form) {
      const auth = nested(form, 'auth');
      if (!auth.access_token || !auth.refresh_token || auth.client_endpoint !== ENDPOINT) return [400, 'unexpected installation data'];
      const { access_token, refresh_token, application_token, member_id } = auth;
      state.auth = { access_token, refresh_token, application_token, member_id };
      save();
      try {
        await bitrix('messageservice.sender.add', { CODE, TYPE: 'SMS', NAME: 'SendHarbor',
          HANDLER: `${env.RELAY_URL}/bitrix24/send?key=${encodeURIComponent(env.RELAY_KEY)}` });
      } catch (error) {
        if (!error.message.includes('ERROR_SENDER_ALREADY_INSTALLED')) throw error;
      }
      console.log('provider registered');
      return [200, '{"status":"success"}'];
    }
    
    async function send(form) {
      if (!state.auth) return [503, 'the application is not installed'];
      const id = form.get('message_id') || '', phone = (form.get('message_to') || '').replace(/[\s().-]/g, '');
      if (form.get('code') !== CODE || !/^[A-Za-z0-9_-]{1,100}$/.test(id)) return [400, 'unexpected message'];
      if (!/^\+[1-9]\d{6,14}$/.test(phone)) return [400, 'use the +15551234567 phone format'];
      const token = nested(form, 'auth').application_token;
      if (token && !same(token, state.auth.application_token)) return [403, 'unknown application'];
      const response = await fetch(SENDHARBOR_URL + '/api/messages', {
        method: 'POST',
        headers: { Authorization: 'Bearer ' + env.SENDHARBOR_API_KEY, 'Content-Type': 'application/json' },
        body: JSON.stringify({ deviceId: env.SENDHARBOR_DEVICE_ID, phone, text: form.get('message_body') || '',
          idempotencyKey: `b24:${state.auth.member_id}:${id}`, externalId: 'b24:' + id }),
        signal: AbortSignal.timeout(15000),
      });
      return response.status === 202 ? [200, ''] : [502, 'SendHarbor answered ' + response.status];
    }
    
    async function webhook(raw, headers) {
      if (!env.SENDHARBOR_WEBHOOK_SECRET) return [503, 'SENDHARBOR_WEBHOOK_SECRET is not set'];
      const timestamp = String(headers['x-sms-timestamp'] ?? '');
      if (!/^\d{10,11}$/.test(timestamp) || Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) return [401, 'stale timestamp'];
      const expected = 'sha256=' + createHmac('sha256', env.SENDHARBOR_WEBHOOK_SECRET).update(timestamp + '.').update(raw).digest('hex');
      if (!same(headers['x-sms-signature'], expected)) return [401, 'invalid signature'];
      const event = JSON.parse(raw.toString('utf8')), data = event.data || {};
      if (event.type !== 'message.status' || !String(data.externalId).startsWith('b24:')) return [204, ''];
      const id = data.externalId.slice(4), status = STATUS[data.status?.phase], sequence = data.status?.sequence ?? 0;
      if (!status || !state.auth || sequence <= (state.sequences[id] ?? -1)) return [204, ''];
      await bitrix('messageservice.message.status.update', { CODE, MESSAGE_ID: id, STATUS: status });
      state.sequences[id] = sequence;
      save();
      return [204, ''];
    }
    
    createServer(async (req, res) => {
      const reply = (code, body = '') => res.writeHead(code, { 'Content-Type': 'text/plain; charset=utf-8' }).end(body);
      try {
        const url = new URL(req.url, 'http://relay');
        if (req.method === 'GET' && url.pathname === '/health') return reply(200, 'ok');
        if (req.method !== 'POST') return reply(405, 'POST only');
        const chunks = [];
        let size = 0;
        for await (const chunk of req) {
          if ((size += chunk.length) > 262144) return reply(413, 'too large');
          chunks.push(chunk);
        }
        const raw = Buffer.concat(chunks);
        if (url.pathname === '/sendharbor') return reply(...await webhook(raw, req.headers));
        if (!same(url.searchParams.get('key'), env.RELAY_KEY)) return reply(403, 'wrong key');
        const form = new URLSearchParams(raw.toString('utf8'));
        if (url.pathname === '/bitrix24/install') return reply(...await install(form));
        if (url.pathname === '/bitrix24/send') return reply(...await send(form));
        if (url.pathname === '/bitrix24/app') return reply(200, 'The SendHarbor SMS provider is installed.');
        reply(404, 'not found');
      } catch (error) {
        console.error(error.message);
        reply(503, 'temporarily unavailable');
      }
    }).listen(8788, '127.0.0.1', () => console.log('relay listening on 127.0.0.1:8788'));

    Put the settings into relay.env, readable only by the user that runs the relay:

    relay.env
    SENDHARBOR_API_KEY=REPLACE_WITH_YOUR_KEY
    SENDHARBOR_DEVICE_ID=REPLACE_WITH_PHONE_ID
    SENDHARBOR_WEBHOOK_SECRET=
    RELAY_URL=https://relay.example.com
    RELAY_KEY=REPLACE_WITH_A_LONG_RANDOM_STRING
    B24_DOMAIN=example.bitrix24.com
    B24_CLIENT_ID=
    B24_CLIENT_SECRET=
    STATE_FILE=/var/lib/sendharbor-bitrix24/state.json
    SettingValue
    RELAY_URLThe public HTTPS address of the relay, without a slash at the end.
    RELAY_KEYA long random string. It protects the addresses that Bitrix24 calls.
    B24_DOMAINYour Bitrix24 address without https://.
    SENDHARBOR_WEBHOOK_SECRETFilled in at step 3.
    B24_CLIENT_ID, B24_CLIENT_SECRETFilled in at step 2.
    STATE_FILEWhere the relay keeps the Bitrix24 tokens. Back it up and keep it private.
    Terminal
    node -e "console.log(require('crypto').randomBytes(32).toString('base64url'))"  # RELAY_KEY
    chmod 600 relay.env
    node --env-file=relay.env sendharbor-bitrix24.mjs

    Check: your HTTPS address with /health at the end answers ok.

  2. Create the local application

    In Bitrix24, open Developer resources → Other → Local application. Choose a server application, give it the messageservice permission and fill in the two addresses:

    FieldAddress
    Your handler pathhttps://relay.example.com/bitrix24/app?key=RELAY_KEY
    Initial installation pathhttps://relay.example.com/bitrix24/install?key=RELAY_KEY

    Leave Application completes the installation itself turned off and save. Bitrix24 sends the tokens to the relay, and the relay registers the SendHarbor provider.

    Copy the application ID and key that Bitrix24 shows after saving into B24_CLIENT_ID and B24_CLIENT_SECRET, then restart the relay. It needs them to renew the access token, which lasts one hour.

    Check: the relay log says provider registered.

  3. Connect status webhooks

    In the SendHarbor workspace, open API and webhooks. Enter your relay address with /sendharbor at the end into Your project webhook URL, tick Enable project connection and click Save settings.

    Put the secret that is shown once into SENDHARBOR_WEBHOOK_SECRET, restart the relay and click Send test event.

    Check: the delivery log in SendHarbor shows the test event as delivered.

  4. Send a test SMS

    Open a CRM contact with your own number, choose SMS and select SendHarbor as the sender.

    Check: the SMS arrives, the message appears in the workspace and Bitrix24 shows delivered once the carrier reports delivery.

The request the relay sends

Each Bitrix24 message has its own key, so a repeated request sends no second SMS. The externalId links status webhooks back to the Bitrix24 message.

POST /api/messages
{
  "deviceId": "DEVICE_ID",
  "phone": "+15551234567",
  "text": "Your request 1042 has been received.",
  "idempotencyKey": "b24:a223c6b3710f85df22e9377d6c4f7553:65575980fa531ac284c2ee68f81ebebd",
  "externalId": "b24:65575980fa531ac284c2ee68f81ebebd"
}

Statuses in Bitrix24

SendHarborBitrix24
sentsent
delivereddelivered
failedfailed
expired, cancelledundelivered
queued, submitted, sending, unknownNo change.

Events can arrive out of order. The relay ignores an event older than the last one it applied for the same message.

Sources