wxpay.js 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. 'use strict';
  2. const assert = require('assert');
  3. const _ = require('lodash');
  4. const Controller = require('egg').Controller;
  5. /**
  6. * 微信支付
  7. */
  8. class WxPayController extends Controller {
  9. /**
  10. * 微信支付取得sign等参数
  11. */
  12. async wxpaysign() {
  13. const { orderno, money, content, openid } = this.ctx.request.body;
  14. assert(orderno, 'orderno不能为空');
  15. assert(openid, 'openid不能为空');
  16. assert(money, 'money不能为空');
  17. const { wxapi } = this.app.config;
  18. const mch_id = wxapi.mchid;
  19. const nonce_str = await this.service.wxpay.createNonceStr();
  20. const timestamp = await this.service.wxpay.createTimeStamp();
  21. const body = content;
  22. const out_trade_no = orderno;
  23. const total_fee = await this.service.wxpay.getmoney(money);
  24. const spbill_create_ip = this.ctx.ip;
  25. const notify_url = wxapi.wxurl;
  26. const trade_type = 'JSAPI';
  27. const sign = await this.service.wxpay.paysignjsapi(wxapi.appid, body, mch_id, nonce_str, notify_url, out_trade_no, spbill_create_ip, total_fee, trade_type, wxapi.mchkey, openid);
  28. console.log('sign==', sign);
  29. let formData = '<xml>';
  30. formData += '<appid>' + wxapi.appid + '</appid>'; // appid
  31. formData += '<body><![CDATA[' + body + ']]></body>';
  32. formData += '<mch_id>' + mch_id + '</mch_id>'; // 商户号
  33. formData += '<nonce_str>' + nonce_str + '</nonce_str>'; // 随机字符串,不长于32位。
  34. formData += '<notify_url>' + notify_url + '</notify_url>';
  35. formData += '<out_trade_no>' + out_trade_no + '</out_trade_no>';
  36. formData += '<spbill_create_ip>' + spbill_create_ip + '</spbill_create_ip>';
  37. formData += '<total_fee>' + total_fee + '</total_fee>';
  38. formData += '<trade_type>' + trade_type + '</trade_type>';
  39. formData += '<sign>' + sign + '</sign>';
  40. formData += '<openid>' + openid + '</openid>';
  41. formData += '</xml>';
  42. console.log('formData===', formData);
  43. const payurl = wxapi.payurl;
  44. const paydata = await this.ctx.curl(payurl, {
  45. method: 'post',
  46. data: formData,
  47. });
  48. const prepay_id = await this.service.wxpay.getXMLNodeValue(paydata.data.toString('UTF-8'));
  49. console.log('解析后的prepay_id==', prepay_id);
  50. // 将预支付订单和其他信息一起签名后返回给前端
  51. const finalsign = await this.service.wxpay.paysignjsapifinal(wxapi.appid, mch_id, prepay_id, nonce_str, timestamp, wxapi.mchkey);
  52. const res = { appId: wxapi.appid, partnerId: wxapi.mchid, prepayId: prepay_id, nonceStr: nonce_str, timeStamp: timestamp, package: 'prepay_id=' + prepay_id, sign: finalsign };
  53. this.ctx.ok({ data: res });
  54. }
  55. async wxpaysignback() {
  56. const { ctx } = this;
  57. console.log();
  58. ctx.body = 'hi, egg';
  59. }
  60. }
  61. module.exports = WxPayController;