NodeJS 保存MPesa回调数据

dvtswwa3  于 2023-08-04  发布在  Node.js
关注(0)|答案(2)|浏览(107)

我试图保存MPesa回调数据,当用户支付了利帕Na Mpesa,need保存CheckoutRequestID,从令牌解码的用户名,然后如果支付成功的cllback URL需要更新相关的CheckoutRequestID从mysql的金额,从那里它需要更新用户的钱包与新的值.目前代码运行良好,但我不能保存,当我试图访问用户名或任何值的回调不返回任何数据。下面是LipaNaMpesa代码和STK回调代码。

LipaNaMpesa代码

router.get('/stk', middleware.access, middleware.checkToken, (req, res) => {
    let endpoint = "https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest"
    let auth = "Bearer " + req.access_token

    let datenow = new Date()
    //console.log(datenow.getUTCDate())
    const timestamp = datenow.getFullYear() +"" + addZero((datenow.getMonth()+1))+"" +addZero(datenow.getUTCDate())+ ""+ addZero(datenow.getHours())+"" +  addZero(datenow.getMinutes())+"" +  addZero(datenow.getSeconds())
   // console.log(timestamp)
    const password = (new Buffer.from('174379' + 'bfb279f9aa9bdbcf158e97dd71a467cd2e0c893059b10f78e6b72ada1ed2c919' + timestamp).toString('base64'))

    request(
        {
            url: endpoint,
            method: "POST",
            headers: {
                "Authorization": auth
            },
            json: {

                "BusinessShortCode": 174379,
                "Password": password,
                //"MTc0Mzc5YmZiMjc5ZjlhYTliZGJjZjE1OGU5N2RkNzFhNDY3Y2QyZTBjODkzMDU5YjEwZjc4ZTZiNzJhZGExZWQyYzkxOTIwMjExMjExMDcyODAw"
                "Timestamp": timestamp,
                "TransactionType": "CustomerPayBillOnline",
                "Amount": 1,
                "PartyA": 254792482180,//254792482180,
                "PartyB": 174379,
                "PhoneNumber": 254792482180,//254704148972,
                "CallBackURL": "https://9b68-41-80-113-243.ngrok.io/mrequests/stk_confirm",
                "AccountReference": "GoChama",
                "TransactionDesc": "Wallet Deposit"
            }
        },
        function (error, response, body) {
            if (error) {
                console.log(error)
            }
            else {
             // console.log(body.CheckoutRequestID)
               //console.log(req.decoded.username) 
              res.status(200).json(body)
            }
        }
    )
})

字符串

STK CallBAck代码

router.post('/stk_confirm', (req, res) => {
    console.log('....................... stk_confirm .............')
    console.log("Payload Received", req.body.Body.stkCallback)
   /* const callbackData = req.body.Body.stkCallback
    console.log("Payload Received", callbackData)
    var resultCode = callbackData.ResultCode;
    var checkoutId = callbackData.CheckoutRequestID
    var username = req.decoded.username
    if(resultCode === 0){
        const details = callbackData.CallbackMetadata.Item

        var mReceipt;
        var mPhoneNumber;
        var mAmount;

        await details.forEach(entry =>{
            switch (entry.Name){
                case "MpesaReceiptNumber":
                mReceipt = entry.Value
                break;

                case "PhoneNumber":
                mPhoneNumber = entry.Value
                break;

                case "Amount":
                mAmount = entry.Value
                break;

                default:
                    break;
            }
        })
        

    }*/
    res.status(200).json(req.body)
    
})


代码的注解部分在添加时不返回任何值。我做错了什么吗?

hmmo2u0o

hmmo2u0o1#

这就是Daraja API在解决您的问题时的工作方式。当您调用LipaNaMpesa代码并执行时,将返回以下响应。

{
 "MerchantRequestID": "7758-32589747-1",
 "CheckoutRequestID": "ws_CO_21072022121325565708374149",
 "ResponseCode": "0",
 "ResponseDescription": "Success. Request accepted for processing",
 "CustomerMessage": "Success. Request accepted for processing"
}

字符串
此时,您将把CheckoutRequestID与令牌中解码的用户名以及您希望保存的任何其他内容一起保存到数据库中。LipaNaMpesa代码向客户的电话发送提示并返回上述响应。
如果客户未输入PIN或余额不足,或由于其他原因,交易无法通过,则回调URL不会返回任何内容。
如果客户输入PIN并付款,回调URL返回如下响应

{
"Body": 
{
    "stkCallback": 
    {
        "MerchantRequestID": "21605-295434-4",
        "CheckoutRequestID": "ws_CO_04112017184930742",
        "ResultCode": 0,
        "ResultDesc": "The service request is processed successfully.",
        "CallbackMetadata": 
        {
            "Item": 
            [
                {
                    "Name": "Amount",
                    "Value": 1
                },
                {
                    "Name": "MpesaReceiptNumber",
                    "Value": "LK451H35OP"
                },
                {
                    "Name": "Balance"
                },
                {
                    "Name": "TransactionDate",
                    "Value": 20171104184944
                },
                {
                    "Name": "PhoneNumber",
                    "Value": 254706506361
                }
            ]
        }
    }
}
}


现在,您可以更新从LipaNaMpesa代码响应中插入CheckoutRequestID的DB行。两个响应的CheckoutRequestID相同。

mec1mxoz

mec1mxoz2#

你没有得到回调数据,因为你还没有解析json对象。在处理来自daraja的callBackPost请求之前,需要使用bodyParser.json()解析它,如下所示……

//remember to import the module
//const bodyParser = require("body-parser")
router.use(bodyParser.json())
router.post("/stk_confirm", (req, res) => { 
    const callbackData = req.body.Body.stkCallback;/*Everything Should now work as anticipated*/
})

字符串
如果你可能还没有安装body-parser模块,你可以按如下方式安装它:在Windows中使用'cd'命令在命令行中导航到项目文件夹(包含服务器脚本的文件夹),运行.

npm install body-parser


在Linux中,运行...

sudo npm install body-parser


感谢您的阅读,如有任何查询,请WhatsApp我:+254743437015。编码愉快。

相关问题