How do you encode api key to base64 for freshdesk?

I have my freshdesk api key in iparams. I need to encode it in base64 in order to submit via API. I can’t see a way to do this.

This page suggests “encode” but I get “ReferenceError: encode is not defined”.

base64key=encode(payload.iparams.apikey)

I also tried Buffer as shown below per this stackoverflow article but I get “ReferenceError: Buffer is not defined”.

Buffer.from(payload.iparams.apikey).toString(‘base64’)

Any suggestions?

Here is one way which can help you @stevemc,

From frontend

Let’s say this is a input field

      <fw-input
        label="Freshdesk API Key"
        icon-right="magic-wand"
        placeholder="Freshdesk Portal > Profile > Copy API Key"
        required="true"
        minlength="5"
        size="30"
        class="secure-field"
      ></fw-input>
let apiKey = document.querySelector('.secure-field');

function postConfigs() {
        return {
          __meta: {
            secure: ['apiKey']
          },
          api_key: apiKey.value,
        };
      }

      async function validate() {
        var URL = `https://${domain.value}/api/v2/tickets`;
        var base64Encoded = btoa(apiKey.value);
        var options = {
          headers: {
            Authorization: `Basic ${base64Encoded}`,
            'Content-Type': 'application/json'
          }
        };
        try {
          let { status } = await client.request.get(URL, options);
          if (status == 200) return true;
        } catch (error) {
          console.error(error);
          return false;
        }
      }

In backend, as in server.js

You can use a npm package, for example this one - safe-buffer - npm
And try to use Buffer.from(..) by listing the npm package in the manifest.

Native Node packages are blocked because of the security concerns of the platform. Hope those help.

2 Likes

Though Saif did answer the question, I wanted to spell out the solution in a little more detail:

  1. Install safr-buffer module
    npm install safr-buffer

  2. Add following to the manifest.json:
    “dependencies”: {
    “safe-buffer”: “5.2.1”
    }

  3. Add following to top of your server.js:
    var Buffer = require(‘safe-buffer’).Buffer

  4. use following to base64 encode a string:
    base64Key=Buffer.from(“some string”).toString(‘base64’)

That’s it. now use base64Key in your Authorization header
header = "Authorization: Basic " + base64Key

4 Likes

Appreciate you adding more details, @stevemc !

1 Like

This topic was automatically closed after 14 days. New replies are no longer allowed.