wxpay.js 2.5 KB

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