如何使用Node.js消耗一个合作银行的API

136 阅读5分钟

如何使用Node.js消耗合作银行的API

合作银行是一家在东非共同体运营的金融服务机构。截至2018年12月,它已经记录了超过780万用户。

合作银行API(应用编程接口)是一个简单的REST(Representational State Transfer)API,使软件开发人员能够从他们的应用程序中处理银行提供的各种金融操作。

目标

在这篇文章中,我们将使用合作银行的API。

我们将使用Node.js REST API实现以下操作。

  • 获得一个访问令牌。
  • 向 Mpesa 发送资金。
  • 访问你的账户的迷你报表。
  • 访问您的账户的完整报表。
  • 访问您的账户余额。
  • 验证您的账户。

前提条件

要跟上本文,你需要以下条件。

  • 在你的电脑上安装[Node.js]。
  • 在你的电脑上安装[Postman]。
  • 一个代码编辑器,如Visual Studio Code。
  • 对JavaScript的基本了解。
  • 使用[Express.js]开发RESTful APIs的基本知识。

创建一个开发者账户

要创建一个合作银行的开发者账户,请按照下列步骤进行。

  • 进入[开发者页面]。

  • 在右上方,点击[注册]。

  • 在表格中填写所有需要的信息,然后点击Sign Up

  • 你将被转到登录页面,在那里你将输入你的凭证并点击Sign in

  • 成功登录后,你将被引导到[仪表板页面]。

创建一个应用程序

一旦你进入仪表板页面,你将需要创建一个应用程序。你将会为你要使用的所有功能订阅这个应用程序。

要创建一个应用程序,请遵循以下步骤。

  • 在左边的菜单上,点击[应用程序]。

  • 在新页面上,点击[添加应用程序]。

  • 输入应用程序的首选名称,为Per Token Quota ,选择unlimited ,简单描述你的应用程序,为Token Type ,选择OAuth ,然后点击Add

  • 成功添加应用程序后,你将被引导到应用程序页面。

设置开发服务器

开发服务器已经完全设置好了,现在我们将在文章的其余部分实现这些功能。

要安装所需的依赖项,从文本编辑器的终端打开项目,运行以下命令。

npm install

以下是已安装的依赖项。

  • [axios]:用于向合作银行的API发送请求。

  • [dotenv]:用于加载环境变量。

  • [express]:用于设置应用程序中的路由和控制器。

  • [ngrok]:用于暴露我们的localhost服务器。

  • [nodemon]:用来监听变化和重启服务器。

  • [unique-string]:用于生成随机字符串。

下一步是获得我们的CONSUMER KEYCONSUMER SECRET

要获得它们,请按照以下步骤进行。

  • 在上一步的合作银行的申请页面上,点击Sandbox Keys 标签。

  • 在该标签上,点击Generate keys 。这将产生Consumer KeyConsumer Secret

  • 复制它们并将其适当地粘贴到你的项目文件夹根部的.env 文件中。

  • 做完这些后,我们就可以开始执行操作了。我们将从src/controllers/Coop.js 文件中操作。

获得一个访问令牌

access token 是使用API时认证的基础。对于我们在API上进行的每个操作,我们必须发送一个访问令牌。

因此,我们将把它作为一个中间件来实现。这意味着我们不会返回任何东西,而是调用行中的下一个函数。Express.js支持这种功能。

getAccessToken 方法做如下修改。

async getAccessToken(req,res,next){

// compose a buffer based on consumer key and consumer secret
let buff = new Buffer.from(
  `${process.env.CONSUMER_KEY}:${process.env.CONSUMER_SECRET}`
);

// encode the buffer to a base64 string
let buff_data = buff.toString("base64");

// send the request to the api.
let response = await axios
  .default({

    //ignore ssl validation
    httpsAgent: new https.Agent({
      rejectUnauthorized: false,
    }),
    method: "POST", // request method.
    url:"https://developer.co-opbank.co.ke:8243/token", // request url
    headers: {
      "Content-Type": "application/x-www-form-urlencoded", // request content type
      Authorization: `Basic ${buff_data}`, // request auth string.
    },
    data: this.data, // request data
  })
  .catch(console.log);

// set the access token to the request object.
req.access_token = response.data.access_token;

//call the next function.
return next();

};

由于它将被视为一个中间件,因此不需要实现其各自的路由。

向Mpesa发送资金

从你的合作银行账户,你可以直接向Mpesa发送资金。

本教程将使用一个模拟,因为我们是在一个沙盒环境中。然而,这个概念在生产中也是一样的。

请按照以下步骤来实现该功能。

  • 在您的[仪表板页面],点击[sendToMpesa列表]。

  • 在新页面的右侧,在Applications ,选择你的应用程序,然后点击Subscribe

  • 修改sendToMpesa() 方法,如下所示。

async sendToMpesa(req,res,next){

// obtain our access token from the request object
let access_token = req.access_token;

// compose the authentication string
let auth = `Bearer ${access_token}`;

// ngrok url: TODO
let cbUrl = "";

// compose the reference no and message ref.
let refNo = uniqueString().slice(0,14);
let msgRef = uniqueString().slice(0,14);

// send the request to the api
let response = await axios.default({

    // ignore ssl validation
    httpsAgent:new https.Agent({
        rejectUnauthorized:false
    }),
    method:'POST', // request method.
    url:"https://developer.co-opbank.co.ke:8243/FundsTransfer/External/A2M/Mpesa/1.0.0/", // request URL
    data:{
        "CallBackUrl": `${cbUrl}/callback`, // callback url
        "Destinations": [
            {
            "MobileNumber": "254791569999", // any mpesa mobile no.
            "Narration": "Supplier Payment", // transaction narration
            "ReferenceNumber": refNo, // the generated refNo
            "Amount": "50" // amount to send.
            }
        ],
        "MessageReference": msgRef, // generated msgRef
        "Source": {
            "Narration": "Supplier Payment", // transaction narration
            "Amount": "50", // amount to send
            "TransactionCurrency": "KES", // currency
            "AccountNumber": "36001873000" // sandbox account no.
        }
    },
    headers:{
        'Authorization':auth // request auth string
    }
}).catch(console.log);


return res.send({
    message:response.data // response
});

};

为了使上述功能发挥作用,我们必须做以下工作。

  • 确保你使用的是沙盒账号。否则,会导致错误。
  • 从你的文本编辑器,打开你的终端,运行以下命令,启动开发服务器。
npm run dev
  • 如果你还没有ngrok,请在你的电脑上安装它。

  • 在成功安装ngrok ,在你的文本编辑器的终端上打开一个单独的标签,运行以下命令来启动它。

npm run ngrok
  • 复制记录的HTTPS URL并将其设置为cbUrl 变量的值。

  • callback 方法进行如下修改。

async callback(req,res,next){

console.log("...request...");

console.log(req.body);

};
  • 打开postman并发送一个POST 请求到:http://localhost:4000/send-to-mpesa.如果你遇到了错误,请重新审视上述步骤,否则你的响应应该类似于以下内容。

send-to-mpesa-postman-response

  • 下面应该类似于回调时在你的终端上记录的信息。

send-to-mpesa-console-response

访问账户迷你报表

帐户小报表是在检索你的银行帐户以前进行的至少五次交易时使用的。

合作银行的API支持这一功能。

要实现这一功能,请遵循以下步骤。

  • 在你的[仪表盘页面]上,点击[AccountMiniStatement列表]。

  • 在右边,在Applications ,选择你的应用程序,然后点击Subscribe

  • 修改accountMinistatement 方法,如下所示。

async accountMinistatement(req,res,next){

// url to send request to
let url = "https://developer.co-opbank.co.ke:8243/Enquiry/MiniStatement/Account/1.0.0/";

//get the access token from the request object and compose the auth string.
let access_token = req.access_token;
let auth = `Bearer ${access_token}`;

// compose the messageReference
let msgRef = uniqueString().slice(0,14);

//send a request to the server.
let response = await axios.default({

    //ignore ssl certificate
    httpsAgent:new https.Agent({
        rejectUnauthorized:false
    }),
    url, // url to send request to.
    method:'POST',// request method.
    data:{
        "MessageReference": `${msgRef}`, // randomly composed string
        "AccountNumber": "36001873000" // sandbox account no
    },
    headers:{
        'Authorization':auth // authentication string
    }
}).catch(console.log);

return res.send({
    message:response.data // response
});

};

为了测试这一点。

  • 确保开发服务器正在从你的终端运行。
  • 进入postman并发送一个POST 请求到。http://localhost:4000/account-mini-statement.

响应应该类似于以下内容。

account-mini-statement-postman-response

访问账户完整报表

一份完整的报表提供了在两个不同的指定日期之间进行的所有交易。

要实现它,请遵循以下步骤。

  • 从你的[仪表板页面],点击[AccountFullStatement列表]。

  • 在右边的Applications ,选择你的应用程序,并点击Subscribe

  • 修改accountFullstatement() 方法,如下所示。

async accountFullstatement(req,res,next){

//obtain  the url
let url = "https://developer.co-opbank.co.ke:8243/Enquiry/FullStatement/Account/1.0.0/";

// get the access token from the request object and compose the auth string.
let access_token = req.access_token;
let auth = `Bearer ${access_token}`;

// generate the message ref.
let msgRef = uniqueString().slice(0,14);

// specify the start and end date.
let startDate = "2020-11-01";
let endDate = "2021-03-01";

// send a request.
let response = await axios.default({

    // ignore the ssl certificate
    httpsAgent:new https.Agent({
        rejectUnauthorized:false
    }),
    url, // url to send request to.
    method:'POST', // request method
    data:{
        "MessageReference":`${msgRef}`, // randomly generated string
        "AccountNumber":"36001873000", // sandbox account no
        "StartDate": startDate, // from when
        "EndDate": endDate // to when
    },
    headers:{
        'Authorization':auth // authentication string
    }
}).catch(console.log);

return res.send({
    message:response.data // response
});

};

为了测试这一点。

  • 确保开发服务器正在运行。

  • 前往postman并发送一个POST 请求到:http://localhost:4000/account-full-statement.

响应应该类似于以下内容。

account-full-statement-postman-response

访问账户余额

通过API,我们可以从我们的账户中访问账户余额。

为了实现这个功能,我们遵循以下步骤。

  • 从你的[仪表板页面],点击[AccountBalance列表]。

  • 在右边的Applications ,选择你的应用程序,然后点击Subscribe

  • 修改accountBalance() 方法,如下所示。

async accountBalance(req,res,next){

// url to send request to.
let url = "https://developer.co-opbank.co.ke:8243/Enquiry/AccountBalance/1.0.0/";

// obtain the access token and compose the authentication string.
let access_token = req.access_token;
let auth = `Bearer ${access_token}`;

// compose the message reference
let msgRef = uniqueString().slice(0,14);

// send a request.
let response = await axios.default({

    //ignore ssl validation
    httpsAgent:new https.Agent({
        rejectUnauthorized:false
    }),
    method:'POST', // request method
    url, // url to send request to
    data:{
        "MessageReference":msgRef, // randomly generated string
        "AccountNumber":"36001873000" // sandbox account no
    },
    headers:{
        'Authorization':auth // authentication string
    }
}).catch(console.log);

return res.send({
    message:response.data // response
});

};

为了测试这一点。

  • 确保你使用的是sandbox account number 。否则会返回一个错误。

  • 确保开发服务器正在从你的终端运行。

  • 前往Postman并发送一个POST 请求到。http://localhost:4000/account-balance.

发送的响应应该类似于以下内容。

account-balance-postman-response

验证一个账户

通过API,我们可以识别一个有效的合作银行账户。由于我们是在沙盒环境中,我们被限制在默认的账户号码上进行测试。不同的将被称为无效的。

要实现这一点,请遵循以下步骤。

  • 从你的[仪表板页面]点击[账户验证列表]。

  • 在右边的Applications ,选择你的应用程序,然后点击Subscribe

  • 修改accountValidation() 方法,如下所示。

async accountValidation(req,res,next){

// url to send request to
let url = "https://developer.co-opbank.co.ke:8243/Enquiry/Validation/Account/1.0.0/";

// obtain the access token and compose the authentication string.
let access_token = req.access_token;
let auth = `Bearer ${access_token}`;

// compose the message reference.
let msgRef = uniqueString().slice(0,14);

// send a request to the API
let response = await axios.default({

    //ignore ssl certificate.
    httpsAgent:new https.Agent({
        rejectUnauthorized:false
    }),
    url, // url to send request to
    method:'POST', // request method
    data:{
        "MessageReference": msgRef, // randomly generated string
        "AccountNumber": "36001873000" // default sandbox account no
    },
    headers:{
        'Authorization':auth // authentication string
    }
}).catch(console.log);

return res.send({
    message:response.data // response
});

};

为了测试这一点。

  • 确保开发服务器在你的终端上运行。

  • 前往postman并发送一个POST 请求到。http://localhost:4000/account-validation.

发送的响应应该是这样的。

account-validation-postman-response

总结

在这篇文章中,我们使用Node.js实现了合作银行的API的以下功能。