wxpay.js 3.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. 'use strict';
  2. const { CrudService } = require('naf-framework-mongoose/lib/service');
  3. const { BusinessError, ErrorCode } = require('naf-core').Error;
  4. const _ = require('lodash');
  5. const assert = require('assert');
  6. const random = require('string-random');
  7. const moment = require('moment');
  8. const crypto = require('crypto');
  9. const xml2js = require('xml2js');
  10. const fs = require('fs');
  11. // wxpay
  12. class WxpayService extends CrudService {
  13. constructor(ctx) {
  14. super(ctx, 'wxpay');
  15. // this.model = this.ctx.model.Wxpay;
  16. this.appInfo = this.app.config.appInfo;
  17. this.redis = this.app.redis;
  18. }
  19. async toAuth({ code, id }) {
  20. const token = await this.redis.get(id);
  21. console.log(`token=>${token}`);
  22. if (token) return;
  23. const url = ({ id, secret }) => `https://api.weixin.qq.com/sns/jscode2session?appid=${id}&secret=${secret}&js_code=${code}&grant_type=authorization_code`;
  24. console.log(`url=>${url(this.appInfo)}`);
  25. const res = await this.ctx.curl(url(this.appInfo), {
  26. method: 'get',
  27. dataType: 'json',
  28. });
  29. console.log(`res=>${res}`);
  30. const info = JSON.stringify(res.data);
  31. await this.redis.set(id, info, 'EX', 3600);
  32. }
  33. async cash({ id, name, money }) {
  34. const token = await this.redis.get(id);
  35. if (!token) throw new BusinessError(ErrorCode.SERVICE_FAULT, '未找到用户的openid,请重新登陆小程序!');
  36. const { openid } = JSON.parse(token);
  37. if (!this.appInfo) throw new BusinessError(ErrorCode.FILE_FAULT, '未设置小程序相关设置');
  38. // check_name:校验真名,暂不校验
  39. const object = { amount: money, check_name: 'NO_CHECK', desc: '提现', mch_appid: this.appInfo.id, mchid: this.appInfo.store, nonce_str: random(16), openid, partner_trade_no: `cash${moment().format('YYYYMMDDHHmmss')}${random(12)}`, re_user_name: name };
  40. const clientIp = _.get(this.ctx.request, 'header.x-real-ip');
  41. if (clientIp) object.spbill_create_ip = clientIp;
  42. const sign = this.turnToSign(object);
  43. const xml = ` <xml>
  44. <mch_appid>${this.appInfo.id}</mch_appid>
  45. <mchid>${this.appInfo.store}</mchid>
  46. <nonce_str>${object.nonce_str}</nonce_str>
  47. <partner_trade_no>${object.partner_trade_no}</partner_trade_no>
  48. <openid>${openid}</openid>
  49. <check_name>NO_CHECK</check_name>
  50. <re_user_name>${name}</re_user_name>
  51. <amount>${money}</amount>
  52. <desc>提现</desc>
  53. ${clientIp ? '<spbill_create_ip></spbill_create_ip>' : ''}
  54. <sign>${sign}</sign>
  55. </xml>`;
  56. const url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers';
  57. const res = await this.ctx.curl(url, {
  58. method: 'post',
  59. data: xml,
  60. dataType: 'xml',
  61. key: fs.readFileSync('cert/apiclient_key.pem'),
  62. cert: fs.readFileSync('cert/apiclient_cert.pem'),
  63. });
  64. const data = res.data;
  65. const parse = new xml2js.Parser({ trim: true, explicitArray: false, explicitRoot: false });
  66. const result = await parse.parseStringPromise(data);
  67. // TODO 添加错误记录
  68. const { return_code, return_msg, result_code, err_code, err_code_des } = result;
  69. // 请求是否成功
  70. if (return_code !== 'SUCCESS') throw new BusinessError(ErrorCode.SERVICE_FAULT, `${return_code}:${return_msg}`);
  71. // 请求失败具体问题
  72. if (result_code === 'FAIL') throw new BusinessError(ErrorCode.SERVICE_FAULT, `${err_code}:${err_code_des}`);
  73. }
  74. turnToSign(object) {
  75. const _arr = [];
  76. for (const key in object) {
  77. _arr.push(key + '=' + object[key]);
  78. }
  79. const str = `${_arr.join('&')}&key=${this.appInfo.storeKey}`;
  80. return crypto.createHash('md5').update(str, 'utf8').digest('hex')
  81. .toUpperCase();
  82. }
  83. NoticeCode(code) {
  84. const arr = [ 'NOTENOUGH', 'SYSTEMERROR', 'NAME_MISMATCH', 'SIGN_ERROR', 'FREQ_LIMIT', 'MONEY_LIMIT', 'CA_ERROR', 'V2_ACCOUNT_SIMPLE_BAN', 'PARAM_IS_NOT_UTF8', 'SENDNUM_LIMIT' ];
  85. return arr;
  86. }
  87. }
  88. module.exports = WxpayService;