Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
languagejs
themeMidnight
titleDeno - Typescript sample to use webhook
linenumberstrue
// Af10 REST/API test script
// howHow to 1: SeeStart commentsngrok, linesee 18belown, add runneeded scriptinfo, fromstart linethis 3script
// deno run --allow-net webhook_test.ts

import { soxa } from 'https://deno.land/x/soxa/mod.ts';
import { listenAndServe, ServerRequest } from "https://deno.land/std/http/server.ts";

// Needed for authentication
const api_key: string = '<your api_key>'
const username: string = '<username>';
const password: string = '<password>';

let url = 'https://www.autoflex10.dev/autoflex/servoy-service/velocity/webservice_v2'

// 1: Start ngrok, 2: paste ngrok URL on let callback = '...' 3: run script
// ngrok http --region eu 8855
let callback = 'https://<your_ngrok_id>.eu.ngrok.io'
if (debug) {
  callback = 'http://localhost:8855'
}

// Token for Af10 REST/API
let token = await getToken();

// Call GET /authenticate, with parameters
async function getToken() {
  const config = {
    params: {
      api_key,
      username,
      password
    }
  }
  console.log('GET /authenticate');
  const result = await soxa.get(`${url}/authenticate`, config);
  if (result.status == 200) {
    if (result.data?.token) {
      console.log(result.data);
      return result.data?.token;
    }
  }
}

// Call POST /backup/owner, with the required params
async function postOwnerBackup() {
  console.log('POST /backup/owner');
  soxa.post(`${url}/backup/owner`, { webhook_url: callback }, {
    headers: {
      token
    }
  }).then(async (res) => {
    if (res.status === 202) {  // 202, request not yet finished
      listenAndServe
      const options = { port: 8855 };
      listenAndServe(options, async (req: ServerRequest) => {
        req.respond({});
        const secret = req.url.split('=')[1];
        console.log(`Callback received with secret-id: ${secret}`);
        getSecret(secret);
      });
      //Start server to get the callback
    }
    if (res.data.successCode == 202) {
      console.log(res.data);
      console.log('Waiting for webhook call...');
    }
  }).catch((err) => {
    console.log('error:', err)
  })
}

// Call GET /webhook with secret
async function getSecret(secret: string) {
  const result = await soxa.get(`${url}/webhook`, {
    headers: {
      token
    }, params: { id: secret }
  });
  if (result.status === 200) {
    if (result.data?.data?.url)
    console.log(`The secret url: ${result.data?.data?.url}`);
    Deno.exit()
  }
}

// Start this show!
postOwnerBackup();

...