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?

4

3 回答 3

0

出于安全性和可用性考虑,不建议使用 Buffer() 和 new Buffer() 构造函数。请改用新的 Buffer.alloc()、Buffer.allocUnsafe() 或 Buffer.from() 构造方法。

在此处阅读有关 new Buffer() 替代方案的更多信息

于 2020-01-13T06:18:18.060 回答
0

我已经使用相同的方法非常成功地收到了访问令牌。这是我的代码

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
                });
            }
        },
    );
});

我希望这将有所帮助。

于 2020-06-23T20:08:40.730 回答
0

要绕过 Buffer 弃用,您需要使用Buffer.from. Request也已弃用,我现在使用Axios

这是 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
    });
于 2020-08-07T05:52:37.160 回答