You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NodeJS调用M-Pesa API获取授权令牌:过时Buffer方法的替代方案

Replacing Deprecated new Buffer() in Node.js for M-Pesa API Auth

Hey there! That deprecated new Buffer() call is a common gotcha—good catch on noticing it. The Node.js team phased it out because it had ambiguous behavior that could lead to security issues, but there's a straightforward, safer replacement you should use instead.

The Proper Replacement: Buffer.from()

For your specific use case—converting a combined string (consumer key + secret) into a Buffer to generate the Basic auth header—Buffer.from() is the official, recommended replacement. It’s explicit, safe, and works with all supported Node.js versions (v6 and later).

Updated Code for M-Pesa Access Token

Here’s how to adjust your original code to use the non-deprecated syntax:

var request = require('request');
var consumer_key = "YOUR_APP_CONSUMER_KEY";
var consumer_secret = "YOUR_APP_CONSUMER_SECRET";
var url = "https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials";
// Replace new Buffer() with Buffer.from()
var auth = "Basic " + Buffer.from(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
  }
);

Why This Works

Buffer.from() takes your input string directly and creates a Buffer containing its UTF-8 encoded bytes (the default encoding, which is exactly what you need here). This eliminates the ambiguous behavior of the old new Buffer() constructor—for example, it no longer creates an uninitialized buffer if passed a number, which was a potential security risk.

Quick Note on Other Buffer Methods

If you ever need to create a buffer of a specific size (not your case here), use:

  • Buffer.alloc(size): Creates a buffer initialized with zeros (safe, recommended for most cases)
  • Buffer.allocUnsafe(size): Creates an uninitialized buffer (faster, but requires manually overwriting data to avoid exposing old memory content)

内容的提问来源于stack exchange,提问作者Timothy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 09:28:13