• java服务端微信小程序支付


    发布时间:2018-10-05
     
    技术:springboot+maven
     

    概述

    java微信小程序demo支付只需配置支付一下参数即可运行

    详细

    一、前言

    (1)适合人群

    1,java服务端开发人员

    2,初级人员开发人员

    3,了解spring springboot+maven

    3,了解小程序开发跟前端人员接口对接

    (2) 你需要准备什么?

    1,积极主动学习

    2,微信开发基本流程

    3,java后端几大框架掌握如(spring springboot maven mybatis)

    二、前期准备工作

    软件环境:eclipse

    官方下载:https://www.eclipse.org/downloads/

    1丶基本需求

    1,实现商品支付功能

    2,项目目录结构

    image.png

    三、实现步骤

    1.在小程序中获取用户的登录信息,成功后可以获取到用户的code值

    2.在用户自己的服务端请求微信获取用户openid接口,成功后可以获取用户的openid值

    微信官方api地址:点击打开链接

    3.在用户自己的服务器上面请求微信的统一下单接口,下单成功后可以获取prepay_id值

    微信官方api地址:点击打开链接

    4.在微信小程序中支付订单,最终实现微信的支付功能

    微信官方api地址:点击打开链接

    29b4a001f01d8aa8b896ef1eb58696fe_SouthEast.png

    1,下面我们就开始详细的介绍一下微信支付的整个流程:

    首先是获取用户的信息,也就是小程序中的登录接口:

    //app.js
    App({
      onLaunch: function() {
        wx.login({
          success: function(res) {
            if (res.code) {
              //发起网络请求
              wx.request({
                url: 'https://test.com/onLogin',
                data: {
                  code: res.code
                }
              })
            } else {
              console.log('获取用户登录态失败!' + res.errMsg)
            }
          }
        });
      }
    })

    2,contrller层实现登陆方法方法

    /**
     * @Description: 本示例仅供参考,请根据自己的使用情景进行修改
     * @Date: 2018/7/17
     * @Author: wcf
     */
    @RequestMapping("/weixin")
    @RestController
    public class WeixinController extends WeixinSupport{
    
        private Logger logger = LoggerFactory.getLogger(getClass());
    
        private static final String appid = "";	    //微信小程序appid
        private static final String secret = "";	//微信小程序密钥
        private static final String grant_type = "";
    
        /**
         * 小程序后台登录,向微信平台发送获取access_token请求,并返回openId
         *
         * @param code
         * @return openid
         * @throws WeixinException
         * @throws IOException
         * @since Weixin4J 1.0.0
         */
        @RequestMapping("login")
        public Map<String, Object> login(String code, HttpServletRequest request) throws WeixinException, IOException {
            if (code == null || code.equals("")) {
                throw new WeixinException("invalid null, code is null.");
            }
    
            Map<String, Object> ret = new HashMap<String, Object>();
            //拼接参数
            String param = "?grant_type=" + grant_type + "&appid=" + appid + "&secret=" + secret + "&js_code=" + code;
    
            //创建请求对象
            HttpsClient http = new HttpsClient();
            //调用获取access_token接口
            Response res = http.get("https://api.weixin.qq.com/sns/jscode2session" + param);
            //根据请求结果判定,是否验证成功
            JSONObject jsonObj = res.asJSONObject();
            if (jsonObj != null) {
                Object errcode = jsonObj.get("errcode");
                if (errcode != null) {
                    //返回异常信息
                    throw new WeixinException(getCause(Integer.parseInt(errcode.toString())));
                }
    
                ObjectMapper mapper = new ObjectMapper();
                OAuthJsToken oauthJsToken = mapper.readValue(jsonObj.toJSONString(),OAuthJsToken.class);
    
                logger.info("openid=" + oauthJsToken.getOpenid());
                ret.put("openid", oauthJsToken.getOpenid());
            }
            return ret;
        }

    3、发起微信支付请求

       /**
         * @Description: 发起微信支付
         * @param openid
         * @param request
         * @author: wcf
         * @date: 2018年7月17日
         */
        @RequestMapping("wxPay")
        public Json wxPay(String openid, HttpServletRequest request){
            Json json = new Json();
            try{
                //生成的随机字符串
                String nonce_str = StringUtils.getRandomStringByLength(32);
                //商品名称
                String body = "测试商品名称";
                //获取本机的ip地址
                String spbill_create_ip = IpUtils.getIpAddr(request);
    
                String orderNo = "123456788";
                String money = "1";//支付金额,单位:分,这边需要转成字符串类型,否则后面的签名会失败
    
                Map<String, String> packageParams = new HashMap<String, String>();
                packageParams.put("appid", WxPayConfig.appid);
                packageParams.put("mch_id", WxPayConfig.mch_id);
                packageParams.put("nonce_str", nonce_str);
                packageParams.put("body", body);
                packageParams.put("out_trade_no", orderNo);//商户订单号
                packageParams.put("total_fee", money);//支付金额,这边需要转成字符串类型,否则后面的签名会失败
                packageParams.put("spbill_create_ip", spbill_create_ip);
                packageParams.put("notify_url", WxPayConfig.notify_url);
                packageParams.put("trade_type", WxPayConfig.TRADETYPE);
                packageParams.put("openid", openid);
    
                // 除去数组中的空值和签名参数
                packageParams = PayUtil.paraFilter(packageParams);
                String prestr = PayUtil.createLinkString(packageParams); // 把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串
    
                //MD5运算生成签名,这里是第一次签名,用于调用统一下单接口
                String mysign = PayUtil.sign(prestr, WxPayConfig.key, "utf-8").toUpperCase();
                logger.info("=======================第一次签名:" + mysign + "=====================");
                
                //拼接统一下单接口使用的xml数据,要将上一步生成的签名一起拼接进去
                String xml = "<xml>" + "<appid>" + WxPayConfig.appid + "</appid>"
                        + "<body><![CDATA[" + body + "]]></body>"
                        + "<mch_id>" + WxPayConfig.mch_id + "</mch_id>"
                        + "<nonce_str>" + nonce_str + "</nonce_str>"
                        + "<notify_url>" + WxPayConfig.notify_url + "</notify_url>"
                        + "<openid>" + openid + "</openid>"
                        + "<out_trade_no>" + orderNo + "</out_trade_no>"
                        + "<spbill_create_ip>" + spbill_create_ip + "</spbill_create_ip>"
                        + "<total_fee>" + money + "</total_fee>"
                        + "<trade_type>" + WxPayConfig.TRADETYPE + "</trade_type>"
                        + "<sign>" + mysign + "</sign>"
                        + "</xml>";
    
                System.out.println("调试模式_统一下单接口 请求XML数据:" + xml);
    
                //调用统一下单接口,并接受返回的结果
                String result = PayUtil.httpRequest(WxPayConfig.pay_url, "POST", xml);
    
                System.out.println("调试模式_统一下单接口 返回XML数据:" + result);
    
                // 将解析结果存储在HashMap中
                Map map = PayUtil.doXMLParse(result);
    
                String return_code = (String) map.get("return_code");//返回状态码
    
                //返回给移动端需要的参数
                Map<String, Object> response = new HashMap<String, Object>();
                if(return_code == "SUCCESS" || return_code.equals(return_code)){
                    // 业务结果
                    String prepay_id = (String) map.get("prepay_id");//返回的预付单信息
                    response.put("nonceStr", nonce_str);
                    response.put("package", "prepay_id=" + prepay_id);
                    Long timeStamp = System.currentTimeMillis() / 1000;
                    response.put("timeStamp", timeStamp + "");//这边要将返回的时间戳转化成字符串,不然小程序端调用wx.requestPayment方法会报签名错误
    
                    String stringSignTemp = "appId=" + WxPayConfig.appid + "&nonceStr=" + nonce_str + "&package=prepay_id=" + prepay_id+ "&signType=" + WxPayConfig.SIGNTYPE + "&timeStamp=" + timeStamp;
                    //再次签名,这个签名用于小程序端调用wx.requesetPayment方法
                    String paySign = PayUtil.sign(stringSignTemp, WxPayConfig.key, "utf-8").toUpperCase();
                    logger.info("=======================第二次签名:" + paySign + "=====================");
    
                    response.put("paySign", paySign);
                    //更新订单信息
                    //业务逻辑代码
                }
                response.put("appid", WxPayConfig.appid);
    
                json.setSuccess(true);
                json.setData(response);
            }catch(Exception e){
                e.printStackTrace();
                json.setSuccess(false);
                json.setMsg("发起失败");
            }
            return json;
        }

    4、微信WxPayConfig配置

    /**
     * @Description:
     * @Date: 2018/7/17
     * @Author: wcf
     */
    public class WxPayConfig {
        //小程序appid
        public static final String appid = "";
        //微信支付的商户id
        public static final String mch_id = "";
        //微信支付的商户密钥
        public static final String key = "";
        //支付成功后的服务器回调url
        public static final String notify_url = "";
        //签名方式
        public static final String SIGNTYPE = "MD5";
        //交易类型
        public static final String TRADETYPE = "JSAPI";
        //微信统一下单接口地址
        public static final String pay_url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
    }

    5、下面是IpUtils工具类

    /**
     * @Description:
     * @Date: 2018/7/17
     * @Author: wcf
     */
    public class IpUtils {
        /**
         * IpUtils工具类方法
         * 获取真实的ip地址
         * @param request
         * @return
         */
        public static String getIpAddr(HttpServletRequest request) {
            String ip = request.getHeader("X-Forwarded-For");
            if(StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)){
                //多次反向代理后会有多个ip值,第一个ip才是真实ip
                int index = ip.indexOf(",");
                if(index != -1){
                    return ip.substring(0,index);
                }else{
                    return ip;
                }
            }
            ip = request.getHeader("X-Real-IP");
            if(StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)){
                return ip;
            }
            return request.getRemoteAddr();
        }
    }

    6、StringUtils工具类等

    /**
     * @Description:
     * @Date: 2018/7/17
     * @Author: wcf
     */
    public class StringUtils extends org.apache.commons.lang3.StringUtils{
        /**
         * StringUtils工具类方法
         * 获取一定长度的随机字符串,范围0-9,a-z
         * @param length:指定字符串长度
         * @return 一定长度的随机字符串
         */
        public static String getRandomStringByLength(int length) {
            String base = "abcdefghijklmnopqrstuvwxyz0123456789";
            Random random = new Random();
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < length; i++) {
                int number = random.nextInt(base.length());
                sb.append(base.charAt(number));
            }
            return sb.toString();
        }
    }

    7、微信请求回调contrller

        /**
         * @Description:微信支付
         * @return
         * @author dzg
         * @throws Exception
         * @throws WeixinException
         * @date 2018年7月17日
         */
        @RequestMapping(value="/wxNotify")
        public void wxNotify(HttpServletRequest request,HttpServletResponse response) throws Exception{
            BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream)request.getInputStream()));
            String line = null;
            StringBuilder sb = new StringBuilder();
            while((line = br.readLine())!=null){
                sb.append(line);
            }
            br.close();
            //sb为微信返回的xml
            String notityXml = sb.toString();
            String resXml = "";
            System.out.println("接收到的报文:" + notityXml);
    
            Map map = PayUtil.doXMLParse(notityXml);
    
            String returnCode = (String) map.get("return_code");
            if("SUCCESS".equals(returnCode)){
                //验证签名是否正确
                if(PayUtil.verify(PayUtil.createLinkString(map), (String)map.get("sign"), WxPayConfig.key, "utf-8")){
                    /**此处添加自己的业务逻辑代码start**/
    
    
                    /**此处添加自己的业务逻辑代码end**/
    
                    //通知微信服务器已经支付成功
                    resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
                            + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
                }
            }else{
                resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
                        + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
            }
            System.out.println(resXml);
            System.out.println("微信支付回调数据结束");
    
            BufferedOutputStream out = new BufferedOutputStream(
                    response.getOutputStream());
            out.write(resXml.getBytes());
            out.flush();
            out.close();
        }
    7,请求的接口是 注意code是从微信小程序传的code这code是我随意的code必须从小程序那边获取才能调起微信支付
    http://localhost:8080/weixin/wxPay?code=code

    8,成功后显示如图

    Q(~E(BX3)Y6D8%WEPX5(2`W.png

    注:本文著作权归作者,由demo大师发表,拒绝转载,转载需要作者授权

  • 相关阅读:
    ASP.NET服务器控件开发(3)事件和回传数据的处理
    ASP.NET服务器控件开发(1)封装html
    .Net Remoting(基本操作) Part.2
    javascript方法和技巧大全_javascript教程
    .Net Remoting(分离服务程序实现) Part.3
    [转]我在面试.NET/C#程序员时会提出的问题
    ASP.NET服务器控件开发(2)继承WebControl类
    一点点对WebResource.axd的配置及使用[原创]
    .Net Remoting(远程方法回调) Part.4
    ASP.NET自定义控件复杂属性声明持久性浅析
  • 原文地址:https://www.cnblogs.com/demodashi/p/10486875.html
Copyright © 2020-2023  润新知