wechat_pay.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /* eslint-disable camelcase */
  2. const { appid, mchid, serial_no, key, plat_serial, refund_url, notify_url } =
  3. require('../config').wechatPay;
  4. const { host } = require('../config');
  5. const WxPay = require('wechatpay-node-v3');
  6. const fs = require('fs');
  7. const pay = new WxPay({
  8. appid,
  9. mchid,
  10. serial_no,
  11. key,
  12. publicKey: fs.readFileSync(`${__dirname}/apiclient_cert.pem`), // 公钥
  13. privateKey: fs.readFileSync(`${__dirname}/apiclient_key.pem`), // 秘钥
  14. });
  15. const model = {
  16. // 下单
  17. async placeOrder(obj) {
  18. const { description, out_trade_no, openid, total, url = '/external/pay/notice' } = obj;
  19. try {
  20. const res = await pay.transactions_native({
  21. appid, // 应用id
  22. mchid, // 直连商户号
  23. description, // 商品描述
  24. out_trade_no, // 商户订单号
  25. notify_url: `${host}${url}`, // 通知回调地址
  26. amount: {
  27. // 订单金额详情
  28. total, // 总金额
  29. currency: 'CNY', // 货币类型
  30. },
  31. });
  32. console.log(res);
  33. return res;
  34. } catch (error) {
  35. console.log('下单错误', error);
  36. console.log(error.response.data);
  37. return error.response.data;
  38. }
  39. },
  40. // 退款
  41. async refund(obj) {
  42. const { out_trade_no, total, reason, refund, out_refund_no, url } = obj;
  43. try {
  44. const res = await pay.refunds({
  45. out_refund_no, // 商户退款号
  46. reason, // 描述
  47. out_trade_no, // 商户订单号
  48. notify_url: `${host}/external/refund/notice`, // 通知回调地址
  49. amount: {
  50. // 订单金额详情
  51. total, // 总金额
  52. refund, // 金额
  53. currency: 'CNY', // 退款币种,
  54. },
  55. });
  56. console.log(res);
  57. return res;
  58. } catch (error) {
  59. console.log('下单错误', error);
  60. console.log(error.response.data);
  61. return false;
  62. }
  63. },
  64. decodeNotify(obj) {
  65. const { original_type, algorithm, ciphertext, associated_data, nonce } = obj;
  66. const res = pay.decipher_gcm(ciphertext, associated_data, nonce);
  67. },
  68. };
  69. module.exports = pay;