个人微信支付总结---不喜勿喷

微信支付开发总结

作者:bruce.bei 日期:2018.2.2

QQ同微信:215748382

 

做微信开发以来到微信支付也有2,3年时间了,做过微信公众号支付、微信H5支付以及在公众号内用h5支付,下面要总结下这有点麻烦的微信支付,以便于以后再次开发。

第一、需要查看微信官网的开发文档,因为微信他本身在更新,一两年后可能接口会有所变化。用到的网站可以通过百度搜索查阅,关键字如:微信公众平台,微信商家平台,微信开发平台。

第二、根据文档做相关配置。先要从微信公众平台通过认证,300一年,申请微信支付功能,具体开放权限还要看微信公众平台如何处理(下同,要参照官方文档)。公众号平台---公众号设置---功能设置,JS接口安全域名和网页授权域名。

个人微信支付总结---不喜勿喷

 个人微信支付总结---不喜勿喷

 

注:配置这个的方法有两种,一种是直接用80端口,域名解析到这个ip,程序上直接放文件;第二种是用nginx进行反向映射,反向映射的ip和域名可能需要同一个运营商,腾讯域名映射到阿里云服务器会有问题。

 

第三、编码。借用别人的微信开源框架。

<properties>

<weixin-java-mp.version>2.6.2.BETA</weixin-java-mp.version>

</properties>

<dependency>

<groupId>com.github.binarywang</groupId>

<artifactId>weixin-java-mp</artifactId>

<version>${weixin-java-mp.version}</version>

</dependency>

 个人微信支付总结---不喜勿喷

 

注:公司项目的微信支付,用的是公众号支付,而且微信公众平台接入了服务器。

第四、支付开发。微信支付的开发有多种,微信公众号支付、扫码支付、H5支付、公众号内H5支付、APP内支付等。具体看官网后续推出。配置如下:

 个人微信支付总结---不喜勿喷

该页面每次操作的时候,都需要安装安全控件:

 

 个人微信支付总结---不喜勿喷

个人微信支付总结---不喜勿喷

 

添加授权目录时,需要定位到支付调用的路径。比如,H5支付的路径为

http://web.wx.nbmlnx.cn/jiashu/data/xxxx

那么填写的路径为:

http://web.wx.nbmlnx.cn/jiashu/

直接解析到地址的情况是这样的,没有进行更多尝试,希望朋友们有经验的分享

公众号的支付路径:

http://wx.nbmlnx.cn/

 个人微信支付总结---不喜勿喷

该域名用的是反向代理

 个人微信支付总结---不喜勿喷

 

如果配置都顺利,那么ok,代码实现了。

 

下面贴代码:

控制层

支付接口:

@RequestMapping("/wx/getWxPayConfig")

public Map<String, Object> getWxPayConfig(HttpSessionsession,

HttpServletRequest request, IntegerorderId, StringtotalPrice,

String orderType) {

String openId = (String)session.getAttribute("openid");

if(openId ==null){

openId ="oA3ydjrJesa3kaoIDoGu5sYk_6l4";

}

Map<String, Object> resultMap =new HashMap<>();

Map<String, String> payMap =new HashMap<>();

try {

SimpleDateFormat sdf =new SimpleDateFormat("yyyyMMddHHmmssSSS");// 20150320010101002

String tradeNo =sdf.format(new Date());

// 生成订单对象

Map<String, String> orderMap =new TreeMap<>();

orderMap.put("appid", WXPayConstants.APPID);// APPID

orderMap.put("mch_id", WXPayConstants.MCH_ID);// 商户号

orderMap.put("nonce_str", WXPayUtil.generateNonceStr());// 随机字符串

// <span

// style="color:#ff0000;"><strong>说明2(见文末)</strong></span>

orderMap.put("body","美灵思服务");// 商品描述

orderMap.put("out_trade_no",tradeNo +orderId);// 商户订单号

BigDecimal bigDecimal =new BigDecimal(

Double.valueOf(totalPrice) * 100);

orderMap.put("total_fee",

bigDecimal.setScale(0, BigDecimal.ROUND_HALF_UP).toString());// 金额需要扩大100倍:1代表支付时是0.01

orderMap.put("spbill_create_ip","115.215.40.166");// 终端IP

System.out.println(request.getRemoteAddr());

if (orderType.equals("online_booking")) {

orderMap.put("notify_url",

"http://wx.nbmlnx.cn/data/online_booking/notify");// 通知地址

} else if (orderType.equals("private_service")) {

orderMap.put("notify_url",

"http://wx.nbmlnx.cn/data/private_service/notify");// 通知地址

} else if (orderType.equals("team_service")) {

orderMap.put("notify_url",

"http://wx.nbmlnx.cn/data/team_service/notify");// 通知地址

}

orderMap.put("trade_type","JSAPI");// JSAPI--公众号支付、NATIVE--原生扫码支付、APP--app支付,MWEB--H5支付

orderMap.put("openid",openId);// warning

// TODO

// trade_type=JSAPI时(即公众号支付),此参数必传

orderMap.put("sign",

WXPayUtil.generateSignature(orderMap, WXPayConstants.KEY));// 签名<span

// style="color:#ff0000;"><strong>说明5(见文末,签名方法一并给出)</strong></span>

 

URL httpUrl =new URL(WXPayConstants.PAY_URL);

HttpURLConnection httpURLConnection = (HttpURLConnection)httpUrl

.openConnection();

httpURLConnection.setDoOutput(true);

httpURLConnection.setRequestMethod("POST");

httpURLConnection.connect();

OutputStream outputStream =httpURLConnection.getOutputStream();

outputStream.write(WXPayUtil.mapToXml(orderMap).getBytes("UTF-8"));

outputStream.flush();

outputStream.close();

 

// 获取输入流

BufferedReader reader =new BufferedReader(new InputStreamReader(

httpURLConnection.getInputStream()));

 

String line =null;

StringBuffer sb =new StringBuffer();

while ((line =reader.readLine()) !=null) {

sb.append(line);

}

System.out.println(sb.toString());

Map<String, String> map = WXPayUtil.xmlToMap(sb.toString());

if ((null !=map) &&"SUCCESS".equals(map.get("return_code"))

&& "SUCCESS".equals(map.get("result_code"))) {

payMap.put("appId", WXPayConstants.APPID);

payMap.put("nonceStr", WXPayUtil.generateNonceStr());

payMap.put("package","prepay_id=" +map.get("prepay_id"));

payMap.put("signType", WXPayConstants.SignType.MD5.toString());

payMap.put("timeStamp",

Long.toString(WXPayUtil.getCurrentTimestamp()));

payMap.put("paySign", WXPayUtil.generateSignature(payMap,

WXPayConstants.KEY, WXPayConstants.SignType.MD5));

payMap.put("mweb_url",map.get("mweb_url"));

resultMap.putAll(R.ok());

resultMap.putAll(payMap);

} else {

payMap.put("return_msg",map.get("return_msg"));

resultMap.putAll(payMap);

}

} catch (Exceptione) {

e.printStackTrace();

resultMap.putAll(R.error(e.toString()));

}

return resultMap;

}

回调接口:

 /**

     * 微信支付回调

     * @param request

     * @param response

     * @return

     * @throws TransactionalException

     */

    @RequestMapping("/online_booking/notify")

    public String wxBookPaySuccess(HttpServletRequestrequest,HttpServletResponseresponse)throws Exception {

        String result =null;//返回给微信的处理结果

        String inputLine;

        String notityXml ="";

        request.setCharacterEncoding("UTF-8");

        response.setCharacterEncoding("UTF-8");

        response.setContentType("text/html;charset=UTF-8");

        response.setHeader("Access-Control-Allow-Origin","*");

        //微信给返回的东西

        try {

            while ((inputLine =request.getReader().readLine()) !=null) {

                notityXml +=inputLine;

            }

            request.getReader().close();

        } catch (Exceptione) {

            e.printStackTrace();

            result = WXPayUtil.setXml("fail","xml获取失败");

        }

        if (notityXml==null||notityXml=="") {

            result = WXPayUtil.setXml("fail","xml为空");

        }

        Map map = WXPayUtil.xmlToMap(notityXml);

        // 解析各种数据

        String appid = (String)map.get("appid");//应用ID

        String attach = (String)map.get("attach");//商家数据包

        String bank_type = (String)map.get("bank_type");//付款银行

        String cash_fee = (String)map.get("cash_fee");//现金支付金额

        String fee_type = (String)map.get("fee_type");//货币种类

        String is_subscribe = (String)map.get("is_subscribe");//是否关注公众账号

        String mch_id = (String)map.get("mch_id");//商户号

        String nonce_str = (String)map.get("nonce_str");//随机字符串

        String openid = (String)map.get("openid");//用户标识

        String out_trade_no = (String)map.get("out_trade_no");// 获取商户订单号

        String result_code = (String)map.get("result_code");// 业务结果

        String return_code = (String)map.get("return_code");// SUCCESS/FAIL

        String sign = (String)map.get("sign");// 获取签名

        String time_end = (String)map.get("time_end");//支付完成时间

        String total_fee = (String)map.get("total_fee");// 获取订单金额

        String trade_type = (String)map.get("trade_type");//交易类型

        String transaction_id = (String)map.get("transaction_id");//微信支付订单号

 

        SortedMap<String, String> parameters =new TreeMap<>();

        // 数据加密

        parameters.put("appid",appid);//应用ID

        parameters.put("attach",attach);//商家数据包

        parameters.put("bank_type",bank_type);//付款银行

        parameters.put("cash_fee",cash_fee);//现金支付金额

        parameters.put("fee_type",fee_type);//货币种类

        parameters.put("is_subscribe",is_subscribe);//是否关注公众账号

        parameters.put("mch_id",mch_id);//商户号

        parameters.put("nonce_str",nonce_str);//随机字符串

        parameters.put("openid",openid);//用户标识

        parameters.put("out_trade_no",out_trade_no);// 商户订单号

        parameters.put("result_code",result_code);// 业务结果

        parameters.put("return_code",return_code);// SUCCESS/FAIL

        parameters.put("time_end",time_end);// 支付完成时间

        parameters.put("total_fee",total_fee);// 获取订单金额

        parameters.put("trade_type",trade_type);//交易类型

        parameters.put("transaction_id",transaction_id);//微信支付订单号

 

        //MD5加密

        String endsign = WXPayUtil.generateSignature(parameters, WXPayConstants.KEY);

 

        if(sign.equals(endsign)){

            result = WXPayUtil.setXml("SUCCESS","OK");

        }

        String orderId =out_trade_no.substring(17);

        onlineBookService.paySuccess(Integer.valueOf(orderId));

        return result;

}

 

 有需要和见解欢迎交流:215748382。专注提升自己,你我都行。