wxpay.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. let formData = '<xml>';
  29. formData += '<appid>' + wxapi.appid + '</appid>'; // appid
  30. formData += '<body><![CDATA[' + body + ']]></body>';
  31. formData += '<mch_id>' + mch_id + '</mch_id>'; // 商户号
  32. formData += '<nonce_str>' + nonce_str + '</nonce_str>'; // 随机字符串,不长于32位。
  33. formData += '<notify_url>' + notify_url + '</notify_url>';
  34. formData += '<out_trade_no>' + out_trade_no + '</out_trade_no>';
  35. formData += '<spbill_create_ip>' + spbill_create_ip + '</spbill_create_ip>';
  36. formData += '<total_fee>' + total_fee + '</total_fee>';
  37. formData += '<trade_type>' + trade_type + '</trade_type>';
  38. formData += '<sign>' + sign + '</sign>';
  39. formData += '<openid>' + openid + '</openid>';
  40. formData += '</xml>';
  41. const payurl = wxapi.payurl;
  42. const paydata = await this.ctx.curl(payurl, {
  43. method: 'post',
  44. data: formData,
  45. });
  46. const prepay_id = await this.service.wxpay.getXMLNodeValue(paydata.data.toString('UTF-8'));
  47. // 将预支付订单和其他信息一起签名后返回给前端
  48. const finalsign = await this.service.wxpay.paysignjsapifinal(wxapi.appid, mch_id, prepay_id, nonce_str, timestamp, wxapi.mchkey);
  49. const res = { appId: wxapi.appid, partnerId: wxapi.mchid, prepayId: prepay_id, nonceStr: nonce_str, timeStamp: timestamp, package: 'prepay_id=' + prepay_id, sign: finalsign };
  50. this.ctx.ok({ data: res });
  51. }
  52. async wxpaysignback() {
  53. const { ctx } = this;
  54. ctx.body = 'hi, egg';
  55. }
  56. }
  57. module.exports = WxPayController;