Node.js NodeJS加入promise和request函数
我有下面的代码用于clover payment api,虽然代码工作得很好,但当我从postman调用api时,没有得到响应。我知道这是因为服务中存在多个请求,我试图找到一种更干净的方法来实现它,但始终无法让它正常工作。我正在尝试发回最终的响应,它是postPayment()函数中请求的响应。任何帮助都将不胜感激 我的服务代码是:Node.js NodeJS加入promise和request函数,node.js,promise,request,clover-payment,Node.js,Promise,Request,Clover Payment,我有下面的代码用于clover payment api,虽然代码工作得很好,但当我从postman调用api时,没有得到响应。我知道这是因为服务中存在多个请求,我试图找到一种更干净的方法来实现它,但始终无法让它正常工作。我正在尝试发回最终的响应,它是postPayment()函数中请求的响应。任何帮助都将不胜感激 我的服务代码是: const db = require('../_helpers/db'); const crypto = require('crypto'); const reque
const db = require('../_helpers/db');
const crypto = require('crypto');
const request = require("request-promise");
module.exports = {
getAll
};
var targetEnv = 'https://sandbox.dev.clover.com/v2/merchant/';
var cardNumber = '6011361000006668';
async function getAll(data) {
var url = targetEnv + data.merchant_id + '/pay/key';
var options = {
url: url,
method: 'GET',
headers: {
Authorization: 'Bearer ' + data.api_token
}
};
request(options, (error, response, body) => {
if (!error && response.statusCode === 200) {
console.log('getAll ' +data);
processEncryption(JSON.parse(body), JSON.stringify(data));
}
});
}
// Process the encryption information received by the pay endpoint.
function processEncryption(jsonResponse, data) {
console.log('processEncryption ' +data);
var prefix = jsonResponse['prefix'];
var pem = jsonResponse['pem'];
// create a cipher from the RSA key and use it to encrypt the card number, prepended with the prefix from GET /v2/merchant/{mId}/pay/key
var encrypted = crypto.publicEncrypt(pem, Buffer(prefix + cardNumber));
// Base64 encode the resulting encrypted data into a string to Clover as the 'cardEncrypted' property.
var cardEncrypted = new Buffer(encrypted).toString('base64');
return postPayment(cardEncrypted, data);
}
// Post the payment to the pay endpoint with the encrypted card information.
async function postPayment(cardEncrypted, body) {
// POST to /v2/merchant/{mId}/pay
console.log('mid ' +JSON.parse(body));
var posturl = targetEnv + '9ZQTAJSQKZ391/pay';
var postData = {
"orderId": "4N3RBF33EBEGT",
"currency": "usd",
"amount": 2,
"tipAmount": 0,
"taxAmount": 0,
"expMonth": 12,
"cvv": 123,
"expYear": 2018,
"cardEncrypted": cardEncrypted,
"last4": 6668,
"first6": 601136,
"streetAddress": "123 Fake street",
"zip": "94080",
"merchant_id": "9ZQTAJSQKZ391",
"order_id": "4N3RBF33EBEGT",
"api_token": "4792a281-38a9-868d-b33d-e36ecbad66f5"
}
var options = {
url: posturl,
method: 'POST',
headers: {
'Authorization': 'Bearer ' + "4792a281-38a9-868d-b33d-e36ecbad66f5",
},
json: postData
};
request(options, (error, response, body) => {
if (!error && response.statusCode === 200) {
//console.log(response);
return response; <---- this response is what i need to show in postman
}
});
console.log(response);
}
异步函数
getAll()
和postPayment()
未正确返回异步值(通过回调或承诺)
我建议将所有内容转换为承诺,并从getAll()
和postPayment()返回承诺。而且,由于转换为承诺,我将删除不推荐使用的request-promise
库,而使用get()
库。然后,您可以调用getAll()
,获得一个承诺,并使用解析值或拒绝从实际请求处理程序发送响应:
const db = require('../_helpers/db');
const crypto = require('crypto');
const got = require('got');
module.exports = {
getAll
};
var targetEnv = 'https://sandbox.dev.clover.com/v2/merchant/';
var cardNumber = '6011361000006668';
async function getAll(data) {
console.log('getAll ', data);
const url = targetEnv + data.merchant_id + '/pay/key';
const options = {
url: url,
method: 'GET',
headers: {
Authorization: 'Bearer ' + data.api_token
}
};
const response = await got(options);
return processEncryption(response, data);
}
// Process the encryption information received by the pay endpoint.
function processEncryption(jsonResponse, data) {
console.log('processEncryption ' + data);
const prefix = jsonResponse.prefix;
const pem = jsonResponse.pem;
// create a cipher from the RSA key and use it to encrypt the card number, prepended with the prefix from GET /v2/merchant/{mId}/pay/key
const encrypted = crypto.publicEncrypt(pem, Buffer(prefix + cardNumber));
// Base64 encode the resulting encrypted data into a string to Clover as the 'cardEncrypted' property.
const cardEncrypted = Buffer.from(encrypted).toString('base64');
return postPayment(cardEncrypted, data);
}
// Post the payment to the pay endpoint with the encrypted card information.
function postPayment(cardEncrypted, body) {
// POST to /v2/merchant/{mId}/pay
console.log('mid ', body);
const posturl = targetEnv + '9ZQTAJSQKZ391/pay';
const postData = {
"orderId": "4N3RBF33EBEGT",
"currency": "usd",
"amount": 2,
"tipAmount": 0,
"taxAmount": 0,
"expMonth": 12,
"cvv": 123,
"expYear": 2018,
"cardEncrypted": cardEncrypted,
"last4": 6668,
"first6": 601136,
"streetAddress": "123 Fake street",
"zip": "94080",
"merchant_id": "9ZQTAJSQKZ391",
"order_id": "4N3RBF33EBEGT",
"api_token": "4792a281-38a9-868d-b33d-e36ecbad66f5"
}
const options = {
url: posturl,
method: 'POST',
headers: {
'Authorization': 'Bearer ' + "4792a281-38a9-868d-b33d-e36ecbad66f5",
},
json: postData
};
return got(options);
}
然后,您的控制器:
const express = require('express');
const router = express.Router();
const tableOrderService = require('./cloverPayment.service');
// routes
router.post('/getAll', (req, res) => {
tableOrderService.getAll(req.body)
.then(users => res.json(users))
.catch(err => next(err));
});
module.exports = router;
您必须将res
作为参数传递到processEncryption()
和postPayment()
中,然后使用res.send(…)
从request()
回调中的postPayment()
发送您的最终响应。而且,在多个地方,您也需要通过发送错误响应来进行正确的错误处理。您不能直接返回值,因为它是异步的,您只是返回到回调中,因为函数早就返回了,甚至在值可用之前就已经返回了。@jfriend00谢谢您的回复,它不起作用了。当我尝试传递res时,它给出了一个错误。你能提供一个例子吗?非常感谢,你的例子真的澄清了很多东西,我终于成功了。
const express = require('express');
const router = express.Router();
const tableOrderService = require('./cloverPayment.service');
// routes
router.post('/getAll', (req, res) => {
tableOrderService.getAll(req.body)
.then(users => res.json(users))
.catch(err => next(err));
});
module.exports = router;