如何实现微信支付功能?

由于本人近期做过的一个微信小程序项目,里面涉及到了微信支付功能,故在此记录下来,以帮助更多需要的人!!

实例后端接口采用Java语言开发;前端自然是小程序了(H5也一样)

前期准备工作

1、获取商户号,必须是非个人小程序

功能--微信支付---关联商户号---注册商户号成功

2、必须开通微信支付商户号

开发---开发设置---AppID(小程序ID)

3、购买域名进行备案,设置SSL开启https访问。

开发思路与说明

无论前端是H5还是小程序后端或是其他语言,他们的开发步骤与思路都是一致的,下面通过前端以及后端思路来介绍,带大家动手开发微信支付功能。

  • 前端开发步骤:

1、首先需要获取openid

2、通过步骤1获得的openid获取prepay_id,用于微信签名使用

3、进行签名,需要参数prepay_id

4、申请支付,由前端API调起支付申请,打开支付界面

实例代码:

//小程序获取用户登录凭证code码;微信小程序由code获取openid和session_key
payoff: function(e){
    var that = this;
    wx.login({
      success: function(res) {
        that.getOpenId(res.code);
      }
    });
    
  },
//获取openid
  getOpenId: function(code){
    var that = this;
    wx.request({ 
        url: 'https://www.see-source.com/weixinpay/GetOpenId', 
        method: 'POST',
        header: {
           'content-type': 'application/x-www-form-urlencoded'
        },
        data: {'code':code},
        success: function(res) {
           var openId = res.data.openid;
           that.xiadan(openId);
        }
    })
  },
  //下单
  xiadan: function(openId){
    var that = this;
    wx.request({
        url: 'https://www.see-source.com/weixinpay/xiadan', 
        method: 'POST',
        header: {
           'content-type': 'application/x-www-form-urlencoded'
        },
        data: {'openid':openId},
        success: function(res) {
           var prepay_id = res.data.prepay_id;
           console.log("统一下单返回 prepay_id:"+prepay_id);
           that.sign(prepay_id);
        }
    })
  },
  //签名
  sign: function(prepay_id){
    var that = this;
    wx.request({
        url: 'https://www.see-source.com/weixinpay/sign', 
        method: 'POST',
        header: {
           'content-type': 'application/x-www-form-urlencoded'
        },
        data: {'repay_id':prepay_id},
        success: function(res) {
           that.requestPayment(res.data);

        }
    })
  },
  //申请支付
  requestPayment: function(obj){
    wx.requestPayment({
      'timeStamp': obj.timeStamp,
      'nonceStr': obj.nonceStr,
      'package': obj.package,
      'signType': obj.signType,
      'paySign': obj.paySign,
      'success':function(res){
      },
      'fail':function(res){
      }
    })
  }
  • 后端开发步骤:

1、开发接口,获取GetOpenId,为前端第一步调用做准备

参数说明:

  appID :你的小程序id; secret:你的小程序的secret; code:小程序获取用户登录凭证
GetOpenId.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String code = request.getParameter("code");
		HttpGet httpGet = new HttpGet("https://api.weixin.qq.com/sns/jscode2session?appid="+Configure.getAppID()+"&secret="+Configure.getSecret()+"&js_code="+code+"&grant_type=authorization_code");
                //设置请求器的配置
        HttpClient httpClient = HttpClients.createDefault();
        HttpResponse res = httpClient.execute(httpGet);
        HttpEntity entity = res.getEntity();
        String result = EntityUtils.toString(entity, "UTF-8");
        response.getWriter().append(result);
	}

2、编写统一下单接口

参数说明:

  appID :你的小程序id; Mch_id:你的商户号;Spbill_create_ip:服务端ip
Xiadan.java:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		try {
			String openid = request.getParameter("openid");
			OrderInfo order = new OrderInfo();
			order.setAppid(Configure.getAppID());
			order.setMch_id(Configure.getMch_id());
			order.setNonce_str(RandomStringGenerator.getRandomStringByLength(32));
			order.setBody("说明");
			order.setOut_trade_no(RandomStringGenerator.getRandomStringByLength(32));
			order.setTotal_fee(10);
			order.setSpbill_create_ip("123.57.218.54");
			order.setNotify_url("https://www.see-source.com/weixinpay/PayResult");
			order.setTrade_type("JSAPI");
			order.setOpenid(openid);
			order.setSign_type("MD5");
			//生成签名
			String sign = Signature.getSign(order);
			order.setSign(sign);
			
			String result = HttpRequest.sendPost("https://api.mch.weixin.qq.com/pay/unifiedorder", order);
			System.out.println(result);
			L.info("---------下单返回:"+result);
			XStream xStream = new XStream();
			xStream.alias("xml", OrderReturnInfo.class); 

			OrderReturnInfo returnInfo = (OrderReturnInfo)xStream.fromXML(result);
			JSONObject json = new JSONObject();
			json.put("prepay_id", returnInfo.getPrepay_id());
			response.getWriter().append(json.toJSONString());
		} catch (Exception e) {
			e.printStackTrace();
			L.error("-------", e);
		}
		
	}

3、编写签名/再签名接口

Sign.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	    try {
			String repay_id = request.getParameter("repay_id");
			SignInfo signInfo = new SignInfo();
			signInfo.setAppId(Configure.getAppID());
			long time = System.currentTimeMillis()/1000;
			signInfo.setTimeStamp(String.valueOf(time));
			signInfo.setNonceStr(RandomStringGenerator.getRandomStringByLength(32));
			signInfo.setRepay_id("prepay_id="+repay_id);
			signInfo.setSignType("MD5");
			//生成签名
			String sign = Signature.getSign(signInfo);
			
			JSONObject json = new JSONObject();
			json.put("timeStamp", signInfo.getTimeStamp());
			json.put("nonceStr", signInfo.getNonceStr());
			json.put("package", signInfo.getRepay_id());
			json.put("signType", signInfo.getSignType());
			json.put("paySign", sign);
			L.info("-------再签名:"+json.toJSONString());
			response.getWriter().append(json.toJSONString());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			L.error("-------", e);
		}
	}

4、最后,接收支付结果方法接口

PayResult.java:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//response.getWriter().append("Served at: ").append(request.getContextPath());
		
		String reqParams = StreamUtil.read(request.getInputStream());
		L.info("-------支付结果:"+reqParams);
		StringBuffer sb = new StringBuffer("<xml><return_code>SUCCESS</return_code><return_msg>OK</return_msg></xml>");
		response.getWriter().append(sb.toString());
	}

以上为整个小程序开发的完整微信支付的核心方法与思路,便于大家少走弯路。

 

1、所有文章未经授权禁止转载、摘编、复制或建立镜像,如有违反,追究法律责任。
2、本站文章部分来源注册用户发布或互联网收集而来,若有侵权,请邮件联系作者。
邮箱地址:wtao219@qq.com
THE END
分享
二维码
< <上一篇
下一篇>>