Nodejs-微信支付接入示例
代码示例
import request from 'request';
import xml2js from 'xml2js';
import qrcode from 'qrcode';
import fs from 'fs';
import { createHash } from 'crypto';
const appid = 'wxa4*********228';
const mch_id = '16*******67';
const key = 'd94***********d58a7';
function unifiedOrder(params, callback) {
params.appid = appid;
params.mch_id = mch_id;
params.nonce_str = generateNonceString();
params.trade_type = 'NATIVE';
params.sign = generateSign(params);
const builder = new xml2js.Builder();
const xml = builder.buildObject({ xml: params });
request.post(
{
url: 'https://api.mch.weixin.qq.com/pay/unifiedorder',
body: xml,
},
function (error, response, body) {
if (!error && response.statusCode === 200) {
parseXML(body, callback);
} else {
callback(error || '请求失败');
}
}
);
}
function generateNonceString(length = 32) {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let nonceStr = '';
for (let i = 0; i < length; i++) {
nonceStr += chars.charAt(Math.floor(Math.random() * chars.length));
}
return nonceStr;
}
function generateSign(params) {
const keys = Object.keys(params).sort();
const string = keys
.filter((key) => params[key] !== undefined && params[key] !== '')
.map((key) => key + '=' + params[key])
.join('&');
const stringSignTemp = string + '&key=' + key;
const sign = createHash('md5').update(stringSignTemp, 'utf8').digest('hex').toUpperCase();
return sign;
}
function parseXML(xml, callback) {
const parser = new xml2js.Parser({
explicitArray: false,
ignoreAttrs: true,
});
parser.parseString(xml, function (error, result) {
if (error) {
callback(error);
} else {
callback(null, result);
}
});
}
const params = {
body: '测试商品',
out_trade_no: '123456789',
total_fee: 1,
spbill_create_ip: '123.123.123.123',
notify_url: 'http://.com',
};
unifiedOrder(params, function (error, result) {
if (error) {
console.error(error);
} else {
qrcode.toFile(
'qrcode.png',
result.xml.code_url,
{
errorCorrectionLevel: 'H',
type: 'png',
scale: 10,
},
function (error) {
if (error) {
console.error('生成二维码失败:', error);
} else {
console.log('二维码已生成');
fs.readFile('qrcode.png', function (error, data) {
if (error) {
console.error('读取二维码文件失败:', error);
} else {
const base64Data = data.toString('base64');
console.log('Base64格式的二维码:', base64Data);
fs.unlink('qrcode.png', function (error) {
if (error) {
console.error('删除二维码文件失败:', error);
} else {
console.log('二维码文件已删除');
}
});
}
});
}
}
);
}
});
实现了微信统一下单功能,并生成一个二维码
request : 用于发送HTTP请求。
xml2js : 用于解析XML格式的响应数据。
qrcode : 用于生成二维码图片。
fs : 用于读取和删除文件。
crypto : 用于生成签名。
定义微信小程序的 appid 、商户号和密钥。