wxpay.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. 'use strict';
  2. const xmlreader = require('xmlreader');
  3. const fs = require('fs');
  4. const Service = require('egg').Service;
  5. class WxPayService extends Service {
  6. constructor(ctx) {
  7. super(ctx);
  8. this.abc = 'wxa9997e40dea04213';
  9. }
  10. // 把金额转为分
  11. async getmoney(money) {
  12. return parseFloat(money) * 100;
  13. }
  14. // 随机字符串产生函数
  15. async createNonceStr() {
  16. return Math.random().toString(36).substr(2, 15);
  17. }
  18. // 时间戳产生函数
  19. async createTimeStamp() {
  20. return parseInt(new Date().getTime() / 1000) + '';
  21. }
  22. // 签名加密算法
  23. async paysignjsapi(appid, body, mch_id, nonce_str, notify_url, out_trade_no, spbill_create_ip, total_fee, trade_type, mchkey, openid) {
  24. const ret = {
  25. appid,
  26. mch_id,
  27. nonce_str,
  28. body,
  29. notify_url,
  30. out_trade_no,
  31. spbill_create_ip,
  32. total_fee,
  33. trade_type,
  34. openid,
  35. };
  36. let string = await this.raw(ret);
  37. const key = mchkey;
  38. string = string + '&key=' + key;
  39. const crypto = require('crypto');
  40. return crypto.createHash('md5').update(string, 'utf8').digest('hex')
  41. .toUpperCase();
  42. }
  43. // 签名加密算法,第二次的签名
  44. async paysignjsapifinal(appid, mch_id, prepayid, noncestr, timestamp, mchkey) {
  45. const ret = {
  46. appId: appid,
  47. timeStamp: timestamp,
  48. nonceStr: noncestr,
  49. package: 'prepay_id=' + prepayid,
  50. signType: 'MD5',
  51. };
  52. let string = await this.raw(ret);
  53. const key = mchkey;
  54. string = string + '&key=' + key;
  55. const crypto = require('crypto');
  56. return crypto.createHash('md5').update(string, 'utf8').digest('hex')
  57. .toUpperCase();
  58. }
  59. async getXMLNodeValue(xml) {
  60. // var tmp = xml.split("<"+node_name+">");
  61. // console.log('tmp',tmp);
  62. // var _tmp = tmp[1].split("</"+node_name+">");
  63. // console.log('_tmp',_tmp);
  64. // return _tmp[0];
  65. const parseObj = await new Promise(function(resolve) {
  66. xmlreader.read(xml, function(errors, response) {
  67. if (errors !== null) {
  68. console.log(errors);
  69. return;
  70. }
  71. const prepay_id = response.xml.prepay_id.text();
  72. resolve(prepay_id);
  73. });
  74. });
  75. return parseObj;
  76. }
  77. async raw(args) {
  78. let keys = Object.keys(args);
  79. keys = keys.sort();
  80. const newArgs = {};
  81. keys.forEach(function(key) {
  82. newArgs[key] = args[key];
  83. });
  84. let string = '';
  85. for (const k in newArgs) {
  86. string += '&' + k + '=' + newArgs[k];
  87. }
  88. string = string.substr(1);
  89. return string;
  90. }
  91. }
  92. module.exports = WxPayService;