下面是使用 Node.js 和 Express 框架编写微信下单支付和微信退款的示例代码:
1. 安装依赖
```
npm install express wechat-pay
```
2. 配置微信支付参数
```javascript
const WechatPay = require('wechat-pay').WechatPay;
const wechatPay = new WechatPay({
appid: 'your_appid',
mchid: 'your_mchid',
partnerKey: 'your_partner_key',
pfx: fs.readFileSync('path/to/your/pkcs12.p12'),
});
```
3. 处理微信支付回调
```javascript
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/wechat/pay/notify', (req, res) => {
const xml = req.body.xml;
wechatPay.verifySign(xml, (err, result) => {
if (err) {
console.error(err);
return res.send('');
}
// 处理业务逻辑,例如更新订单状态等
res.send('');
});
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
```
4. 发起微信支付
```javascript
app.get('/wechat/pay', (req, res) => {
const params = {
body: '商品描述',
out_trade_no: '商户订单号',
total_fee: 1, // 单位为分
spbill_create_ip: req.ip,
notify_url: 'http://yourdomain.com/wechat/pay/notify',
trade_type: 'JSAPI',
openid: '用户的openid',
};
wechatPay.createUnifiedOrder(params, (err, result) => {
if (err) {
console.error(err);
return res.send('发起支付失败');
}
const prepay_id = result.prepay_id;
const params = {
appId: wechat