博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java服务端微信小程序支付
阅读量:7104 次
发布时间:2019-06-28

本文共 11055 字,大约阅读时间需要 36 分钟。

概述

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.jsApp({  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")@RestControllerpublic 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
login(String code, HttpServletRequest request) throws WeixinException, IOException { if (code == null || code.equals("")) { throw new WeixinException("invalid null, code is null."); } Map
ret = new HashMap
(); //拼接参数 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
packageParams = new HashMap
(); 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 = "
" + "
" + WxPayConfig.appid + "
" + "" + "
" + WxPayConfig.mch_id + "
" + "
" + nonce_str + "
" + "
" + WxPayConfig.notify_url + "
" + "
" + openid + "
" + "
" + orderNo + "
" + "
" + spbill_create_ip + "
" + "
" + money + "
" + "
" + WxPayConfig.TRADETYPE + "
" + "
" + mysign + "
" + "
"; 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
response = new HashMap
(); 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 = "
" + "
" + "
" + "
"; } }else{ resXml = "
" + "
" + "
" + "
"; } 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大师发表,拒绝转载,转载需要作者授权

 

你可能感兴趣的文章
HTTP 请求返回代码含义
查看>>
python+soket实现UDP协议的客户/服务端中文聊天程序
查看>>
android:使用BaseExpandableListAdapter实现可折叠的列表
查看>>
什么时候用存储过程
查看>>
【MongoDB for Java】Java操作MongoDB
查看>>
0c-42-ARC模式下如何兼容非ARC的类
查看>>
程序员进阶之路—如何独当一面
查看>>
闲话WPF之十一(Dependency属性 [3] )
查看>>
JS组件系列——基于Bootstrap Ace模板的菜单Tab页效果优化
查看>>
eclipse中tomcat快速启动关闭参数设置
查看>>
C++ extern "c "的作用
查看>>
实践:几十亿条数据分布在几十个节点上的毫秒级实时排序方法
查看>>
PMWiki安装教程
查看>>
JAVA多线程之volatile 与 synchronized 的比较
查看>>
一个经典编程面试题的“隐退”
查看>>
POJ2109
查看>>
显示创建一个表的SQL语句
查看>>
光流和KLT
查看>>
Linux c括号作用域【原创笔记】
查看>>
分分钟带你玩转 Web Services【2】CXF
查看>>