0

When getting the access_token from the mpesa API using nodejs, you run code like below

var request = require('request'),
    consumer_key = "YOUR_APP_CONSUMER_KEY",
    consumer_secret = "YOUR_APP_CONSUMER_SECRET",
    url = "https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials"
    auth = "Basic " + new Buffer(consumer_key + ":" + consumer_secret).toString("base64");

    request(
      {
        url : url,
        headers : {
          "Authorization" : auth
        }
      },
      function (error, response, body) {
        // TODO: Use the body object to extract OAuth access token
      }
    )

The Buffer method that is used to generate the auth value used during Authorization is deprecated in Node. What's the alternative?

arnt
  • 7,178
  • 5
  • 20
  • 31

3 Answers3

0

The Buffer() and new Buffer() constructors are not recommended for use due to security and usability concerns. Please use the new Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() construction methods instead.

Read More about the alternative of new Buffer() here

Eugene Ogongo
  • 149
  • 1
  • 10
0

I have received the access token quite successfully using the same method. Here is my code

const request = require('request');

exports.mpesaAuth = asyncHandler(async(req, res, next) => {
    const auth = new Buffer(
        `${process.env.MPESA_KEY}:${process.env.MPESA_SECRET}`
    ).toString('base64');
    request({
            url: process.env.MPESA_URL,
            headers: { 'Authorization': `Basic ${auth}` }

        },
        (err, response, body) => {
            if (err) {
                console.error(err);
            } else {
                res.status(200).json({
                    success: true,
                    body
                });
            }
        },
    );
});

I hope this will help.

0

To bypass the Buffer deprecation, you need to use Buffer.from. Request is also deprecated, I now use Axios.

Here's the code in ES6:

  import axios from 'axios'
  const consumer_key = "YOUR_APP_CONSUMER_KEY";
  const consumer_secret = "YOUR_APP_CONSUMER_SECRET";
  const url = process.env.SAF_AUTH_URL;
  const Authorization = `Basic ${new Buffer.from(
    `${consumer_key}:${consumer_secret}`,
    'utf-8'
  ).toString('base64')}`;
  axios
    .get(url, {
      headers: {
        Authorization
      }
    })
    .then((response) => {
      // Handle Success
    })
    .catch((error) => {
       //Handle your error
    });
Pindo
  • 1,510
  • 4
  • 16
  • 30