微信支付 H5端 和小程序端 统一下单接口 4个JAVA源码文件代码

首先来看看官方支付文档的一些相关信息 

1、用户在商户侧完成下单,使用微信支付进行支付

2、由商户后台向微信支付发起下单请求(调用统一下单接口)注:交易类型trade_type=MWEB

3、统一下单接口返回支付相关参数给商户后台,如支付跳转url(参数名“mweb_url”),商户通过mweb_url调起微信支付中间页

4、中间页进行H5权限的校验,安全性检查(此处常见错误请见下文)

5、如支付成功,商户后台会接收到微信侧的异步通知

6、用户在微信支付收银台完成支付或取消支付,返回商户页面(默认为返回支付发起页面)

7、商户在展示页面,引导用户主动发起支付结果的查询

8,9、商户后台判断是否接到收微信侧的支付结果通知,如没有,后台调用我们的订单查询接口确认订单状态

10、展示最终的订单支付结果给用户

常见问题

一、回调页面

正常流程用户支付完成后会返回至发起支付的页面,如需返回至指定页面,则可以在MWEB_URL后拼接上redirect_url参数,来指定回调页面。

如,您希望用户支付完成后跳转至https://www.wechatpay.com.cn,则可以做如下处理:

假设您通过统一下单接口获到的MWEB_URL= https://wx.tenpay.com/cgi-bin/mmpayweb-bin/checkmweb?prepay_id=wx20161110163838f231619da20804912345&package=1037687096

 

则拼接后的地址为MWEB_URL= https://wx.tenpay.com/cgi-bin/mmpayweb-bin/checkmweb?prepay_id=wx20161110163838f231619da20804912345&package=1037687096&redirect_url=https%3A%2F%2Fwww.wechatpay.com.cn

注意:

  1.需对redirect_url进行urlencode处理

  2.由于设置redirect_url后,回跳指定页面的操作可能发生在:1,微信支付中间页调起微信收银台后超过5秒 2,用户点击“取消支付“或支付完成后点“完成”按钮。因此无法保证页面回跳时,支付流程已结束,所以商户设置的redirect_url地址不能自动执行查单操作,应让用户去点击按钮触发查单操作。回跳页面展示效果可参考下图

 

 

 

二、其它常见错误

 

序号 问题 错误描述 解决方法
1 网络环境未能通过安全验证,请稍后再试 1. 商户侧统一下单传的终端IP(spbill_create_ip)与用户实际调起支付时微信侧检测到的终端IP不一致导致的,这个问题一般是商户在统一下单时没有传递正确的终端IP到spbill_create_ip导致,详细可参见客户端ip获取指引
 

2. 统一下单与调起支付时的网络有变动,如统一下单时是WIFI网络,下单成功后切换成4G网络再调起支付,这样可能会引发我们的正常拦截,请保持网络环境一致的情况下重新发起支付流程

2 商家参数格式有误,请联系商家解决

1. 当前调起H5支付的referer为空导致,一般是因为直接访问页面调起H5支付,请按正常流程进行页面跳转后发起支付,或自行抓包确认referer值是否为空

 

2. 如果是APP里调起H5支付,需要在webview中手动设置referer,如(
Map extraHeaders = new HashMap();
extraHeaders.put("Referer", "商户申请H5时提交的授权域名");//例如 http://www.baidu.com ))

3 商家存在未配置的参数,请联系商家解决 1,当前调起H5支付的域名(微信侧从referer中获取)与申请H5支付时提交的授权域名不一致,如需添加或修改授权域名,请登陆商户号对应的商户平台--"产品中心"--"开发配置"自行配置

2,如果设置了回跳地址redirect_url,请确认设置的回跳地址的域名与申请H5支付时提交的授权域名是否一致
4 支付请求已失效,请重新发起支付 统一下单返回的MWEB_URL生成后,有效期为5分钟,如超时请重新生成MWEB_URL后再发起支付
6 请在微信外打开订单,进行支付 H5支付不能直接在微信客户端内调起,请在外部浏览器调起
7 IOS:签名验证失败

下面的我实际开发的代码  

1:WxPayController  控制器前端请求传递相应的参数 调用微信统一下单接口 生成订单消息和调用微信支付 

package com.xinjue.web.smallprogram; 

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import javax.annotation.Resource;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xinjue.common.Globals;
import com.xinjue.common.JsonData;
import com.xinjue.meta.Tb_OrderReport;
import com.xinjue.meta.Tb_OrderReport_log;
import com.xinjue.meta.Tb_purchase;
import com.xinjue.meta.Users;
import com.xinjue.service.Tb_OrderReportService;
import com.xinjue.util.DateUtils;
import com.xinjue.util.IpUtils;
import com.xinjue.util.PayUtils;
import com.xinjue.util.StringUtils;
import com.xinjue.util.WxPayConfig;
import com.xinjue.web.BaseController;

/** 
 * @author tqf
 * @version 创建时间:2019-4-10 上午10:54:46 
 * 类说明   微信小程序支付 H5支付
 */
@Controller
public class WxPayController extends BaseController{
	
		@Resource Tb_OrderReportService orderReportService;
		/**
		 * @Description: 发起微信支付 统一下单 返回调起支付需要的参数值
		 * @param request
		 */
		@RequestMapping(value="/wxPay",method = RequestMethod.POST)
		public void  wxPay(HttpServletRequest request,HttpServletResponse response)throws IOException{
			response.setCharacterEncoding("UTF-8");
			response.setContentType("text/html");
			Users users = (Users) request.getSession().getAttribute(Globals.SSESION_USER);
			JsonData jsonData = new JsonData();
			PrintWriter out = null;
			if(users == null){
				response.getWriter().write("{\"return_msg\":\"请先登录\"}");
				return;
			}
			try{
				out = response.getWriter();
				
				String openid = request.getParameter("openid");  //"oirgo491UCy5mBcyv7ldQe2RyDtE"
				String total_fee = request.getParameter("total_fee"); //支付金额
				String new_total_fee = "1";//String.valueOf((Integer.parseInt(total_fee)*100)); //金额是以分为单位的  乘以100换算成元  正式区放开
				String from = request.getParameter("from");// 来源  0--H5	1--小程序
				String paytype = request.getParameter("paytype");  //支付类型  0--微信  1--支付宝
				String title = request.getParameter("title");// 购买标题
				String type = request.getParameter("type"); //购买类型   0--精简版   1--专业版
				//商品名称  微信支付订单展示使用
				String body_name = "0".equals(type)?"精简版":"专业版";
				String body = "购买报告-"+body_name;//request.getParameter("body");//"购买报告-"+body_name;//"测试支付商品名称";
				
				//生成的随机字符串
				String nonce_str = StringUtils.getRandomStringByLength(32);
				//获取客户端的ip地址
				String spbill_create_ip = IpUtils.getIpAddr(request); //request.getRemoteHost();
				
				//商户订单号
				String out_trade_no = "";
				String random = String.valueOf(Math.random()).substring(2,8);
				out_trade_no =DateUtils.dateToString(new Date(), "yyyyMMddhhmmssSSS")+random;
				out_trade_no = out_trade_no.substring(out_trade_no.length()-16, out_trade_no.length());
				
				//组装参数,用户生成统一下单接口的签名
				Map<String, String> packageParams = new HashMap<String, String>();
				
				packageParams.put("mch_id", WxPayConfig.mch_id);
				packageParams.put("nonce_str", nonce_str);
				packageParams.put("body", body);
				packageParams.put("out_trade_no", out_trade_no);//商户订单号
				packageParams.put("total_fee", new_total_fee);//支付金额,这边需要转成字符串类型,否则后面的签名会失败
				packageParams.put("spbill_create_ip", spbill_create_ip);
				packageParams.put("notify_url", WxPayConfig.notify_url);//支付成功后的回调地址
				if("0".equals(from)){ //H5参数
					packageParams.put("appid", WxPayConfig.GZH_appid);
					packageParams.put("trade_type", WxPayConfig.GZH_TRADETYPE);
					packageParams.put("scene_info", WxPayConfig.scene_info);
				}else{ //小程序
					packageParams.put("openid", openid);
					packageParams.put("appid", WxPayConfig.appid);
					packageParams.put("trade_type", WxPayConfig.TRADETYPE);//支付方式  trade_type=JSAPI,openid此参数必传,用户在商户appid下的唯一标识
				}
				
				packageParams = PayUtils.paraFilter(packageParams);
	        	String prestr = PayUtils.createLinkString(packageParams); // 把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串 
	        
	        	//MD5运算生成签名,这里是第一次签名,用于调用统一下单接口
	        	String mysign = PayUtils.sign(prestr, WxPayConfig.key, "utf-8").toUpperCase();
	        	
	        	
	        	String xmlString ="";
	        	if("0".equals(from)){ //H5请求参数
	        		 xmlString += "<scene_info>"+WxPayConfig.scene_info+"</scene_info>"
                 	           + "<trade_type>" + WxPayConfig.GZH_TRADETYPE + "</trade_type>"
                 	           + "<appid>" + WxPayConfig.GZH_appid + "</appid>";
                }else{//小程序
                	 xmlString+= "<trade_type>" + WxPayConfig.TRADETYPE + "</trade_type>"
                			  + "<openid>" + openid + "</openid>" 
                	 		  + "<appid>" + WxPayConfig.appid + "</appid>";
                }
		        //拼接统一下单接口使用的xml数据,要将上一步生成的签名一起拼接进去
		        String xml =  
		        		"<xml>" + "<body><![CDATA[" + body + "]]></body>" 
			                    + "<mch_id>" + WxPayConfig.mch_id + "</mch_id>" 
			                    + "<nonce_str>" + nonce_str + "</nonce_str>" 
			                    + "<notify_url>" + WxPayConfig.notify_url + "</notify_url>"  
			                    + "<out_trade_no>" + out_trade_no + "</out_trade_no>" 
			                    + "<spbill_create_ip>" + spbill_create_ip + "</spbill_create_ip>" 
			                    + "<total_fee>"+new_total_fee+"</total_fee>"
			                    + xmlString
			                    + "<sign>" + mysign + "</sign>"
			                    + "</xml>";
        		/*packageParams.put("sign", mysign);
        		genXml(packageParams);*//**/
		        
		        System.out.println("调试模式_统一下单接口 请求XML数据:" + xml);
		        
		       
		        
		        //调用统一下单接口,并接受返回的结果
		        String result = PayUtils.httpRequest(WxPayConfig.pay_url, "POST", xml);
		        
		        System.out.println("调试模式_统一下单接口 返回XML数据:" + result);
		        
		        // 将解析结果存储在HashMap中   
		        Map map = PayUtils.doXMLParse(result);
		        
		        String return_code = (String) map.get("return_code");//返回状态码
		        String return_msg = (String) map.get("return_msg");
		        
			    Map<String, Object> mapParams = new HashMap<String, Object>();//返回给小程序端需要的参数
			    mapParams.put("return_code", return_code);
			    mapParams.put("return_msg", return_msg);
		        if(return_code.equals("SUCCESS")){     //生成自己的订单信息
		        	 //生成订单记录
			        Tb_OrderReport orderReport = new Tb_OrderReport();
			        orderReport.setAddTime(new Date());
			        orderReport.setFrom(Integer.parseInt(from));
			        orderReport.setOut_trade_no(out_trade_no);
			        orderReport.setPaytype(Integer.parseInt(paytype));
			        orderReport.setStatus(0);
			        orderReport.setTitle(title);
			        orderReport.setTotal_fee(new Double(total_fee));
			        orderReport.setType(Integer.parseInt(type));
			        orderReport.setUserId(users.getUserId());
			        orderReportService.insert(orderReport);
			        
		        	//小程序端使用     H5下单和小程序下单 都会返回这些参数
		        	String prepay_id = (String) map.get("prepay_id");//返回的预付单信息   小程序端使用
		            mapParams.put("nonceStr", nonce_str);
		            mapParams.put("package", "prepay_id=" + prepay_id);
		            Long timeStamp = new Date().getTime();//System.currentTimeMillis() / 1000;   
		            mapParams.put("timeStamp", timeStamp + "");//这边要将返回的时间戳转化成字符串,不然小程序端调用wx.requestPayment方法会报签名错误
		            //拼接签名需要的参数
		            String stringSignTemp = "appId=" + WxPayConfig.appid + "&nonceStr=" + nonce_str + "&package=prepay_id=" + prepay_id+ "&signType=MD5&timeStamp=" + timeStamp;   
		            //再次签名,这个签名用于小程序端调用wx.requesetPayment方法
		            String paySign = PayUtils.sign(stringSignTemp, WxPayConfig.key, "utf-8").toUpperCase();
		            mapParams.put("paySign", paySign);
		            mapParams.put("appid", WxPayConfig.appid);
		            
		            //H5端支付 特有参数  支付跳转地址
		            if("0".equals(from)){
		            	String mweb_url = (String) map.get("mweb_url"); //支付跳转链接  H5端使用
			            String redirect_url  = "http://m.xinjuenet.cn/presentation"; //支付完成回调跳转地址  自定义
			            mweb_url = mweb_url+"&redirect_url="+URLEncoder.encode(redirect_url,"UTF-8");
			            mapParams.put("mweb_url", mweb_url);
		            }
		            jsonData = new JsonData(Globals.SUCCESS, "", mapParams);
		        }else{
		        	jsonData = new JsonData(Globals.SYSTEM_BUSY,"",mapParams);
		        }
			}catch(Exception e){
				e.printStackTrace();
			}
			out.write(jsonData.toJsonString());
		}	


	/**
     * @Description:微信小程序支付回调通知地址
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/wxNotify",method = RequestMethod.GET)
    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 = PayUtils.doXMLParse(notityXml);
 
        String returnCode = (String) map.get("return_code");
        String total_fee  = (String) map.get("total_fee"); //支付金额
        String trade_state = (String) map.get("trade_state"); //支付状态
        if("SUCCESS".equals(returnCode)){
            //验证签名是否正确
            Map<String, String> validParams = PayUtils.paraFilter(map);  //回调验签时需要去除sign和空值参数
            String validStr = PayUtils.createLinkString(validParams);//把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串
            String sign = PayUtils.sign(validStr, WxPayConfig.key, "utf-8").toUpperCase();//拼装生成服务器端验证的签名
            //根据微信官网的介绍,此处不仅对回调的参数进行验签,还需要对返回的金额与系统订单的金额进行比对等
            //商户系统对于支付结果通知的内容一定要做签名验证,并校验返回的订单金额是否与商户侧的订单金额一致,防止数据泄漏导致出现“假通知”,造成资金损失
            if(sign.equals(map.get("sign"))){
                /**此处添加自己的业务逻辑代码start**/
            	if(trade_state != null && "SUCCESS".equals(trade_state)){
            	String out_trade_no = (String) map.get("out_trade_no"); //返回的商户订单号  根据这个改变订单支付状态
            	String time_end = (String) map.get("time_end"); //支付完成时间
            	String result = map.toString(); //返回的所有字段保存支付日志文件
            	
            	//时间格式化
            	SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
            	Date date = (Date) sdf.parse(time_end);
            	SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            	String time =sdf2.format(date);
            	
            
            	//1:更新订单状态和支付时间
            	Tb_OrderReport orderReport = new Tb_OrderReport();
            	orderReport.setOut_trade_no(out_trade_no);
            	orderReport.setTime_end(DateUtils.stringToDate(time, "yyyy-MM-dd HH:mm:ss"));
            	orderReport.setStatus(1);
            	orderReportService.updateStatus(orderReport);
            	
            	//2:添加支付回调记录
            	Tb_OrderReport_log orderReport_log = new Tb_OrderReport_log();
            	orderReport_log.setAddTime(new Date());
            	orderReport_log.setType(0);
            	orderReport_log.setMessage(result);
            	orderReport_log.setOut_trade_no(out_trade_no);
            	orderReportService.insertOrderReportlog(orderReport_log);
            	
            	//3生成唯一购买记录地址 用户通过地址访问购买之后的完整版本报告
            	String key = StringUtils.getRandomStringByLength(32);
            	Tb_OrderReport orderReport2 = new Tb_OrderReport();
            	//orderReport2.setUserId(users.getUserId());
            	orderReport2.setOut_trade_no(out_trade_no);
            	orderReport2 = orderReportService.selectByOut_trade_no(orderReport2);
            	
            	String linkUrl = "";
            	if(orderReport2.getType() == 0){
            		linkUrl = "presentationStreamlining";//精简版
            	}else{
            		linkUrl = "presentationmajor"; //专业版
            	}
            	
            	Tb_purchase purchase = new Tb_purchase();
            	purchase.setUserId(orderReport2.getUserId());
            	purchase.setKey(key);
            	purchase.setAddTime(new Date());
            	purchase.setType(orderReport2.getType());
            	purchase.setLinkUrl(linkUrl);
            	purchase.setOut_trade_no(out_trade_no);
            	orderReportService.insert_purchase(purchase);
            	
                /**此处添加自己的业务逻辑代码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();
    }

	/**
	 * 生成xml
	 * @return
	 */
	public static String genXml(Map<String,String> map)throws Exception{
		StringBuffer sb=new StringBuffer();
		sb.append("<xml>");
		for(String k:map.keySet()){
			Object value=map.get(k);
			sb.append("<"+k+">"+value+"</"+k+">");
		}
		sb.append("</xml>");
		return sb.toString();//new String(sb.toString().getBytes("ISO8859-1"),"UTF-8");
	}
	
	/**
	 * 跳转到支付页面
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value="/wxpaypage",method = RequestMethod.GET)
	public String  wxpaypage(HttpServletRequest request,HttpServletResponse response)throws IOException{
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html");
		Users users = (Users) request.getSession().getAttribute(Globals.SSESION_USER);
		if(users == null){
			try {
				response.sendRedirect("login");
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}
		String title = request.getParameter("title");
		String money = request.getParameter("money");
		String type = request.getParameter("type");
		String type_name = type.equals("0")?"精简版":"专业版";
		request.setAttribute("title", title);
		request.setAttribute("money", money);
		request.setAttribute("type", type);
		request.setAttribute("type_name", type_name);
		return "wxpaypage";
	}

}
 

2:IpUtils  获取实际的IP地址工具类 

package com.xinjue.util; 

import java.net.InetAddress;
import java.net.UnknownHostException;

import javax.servlet.http.HttpServletRequest;

/** 
 * @author tqf
 * @version 创建时间:2019-4-10 上午11:32:52 
 * 类说明 
 */
public class IpUtils {
		
	/**
	 * IpUtils工具类方法
	 * 获取真实的ip地址
	 * @param request
	 * @return
	 */
	public static String getIpAddr(HttpServletRequest request) { 
		InetAddress addr = null;
		try { 
			 addr = InetAddress.getLocalHost(); 
		} catch (UnknownHostException e) { 
			 return request.getRemoteAddr(); 
		}
		System.out.println(addr.getHostAddress());
		return addr.getHostAddress();
	}
}
 

3:PayUtils  有请求接口方法  签名 xml解析等..方法 

package com.xinjue.util;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.commons.codec.digest.DigestUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class PayUtils
{
  public static String sign(String text, String key, String input_charset)
  {
    text = text + "&key=" + key;
    return DigestUtils.md5Hex(getContentBytes(text, input_charset));
  }
  
  public static boolean verify(String text, String sign, String key, String input_charset)
  {
    text = text + key;
    String mysign = DigestUtils.md5Hex(getContentBytes(text, input_charset));
    if (mysign.equals(sign)) {
      return true;
    }
    return false;
  }
  
  public static byte[] getContentBytes(String content, String charset)
  {
    if ((charset == null) || ("".equals(charset))) {
      return content.getBytes();
    }
    try {
      return content.getBytes(charset);
    } catch (UnsupportedEncodingException e) {
      throw new RuntimeException("MD5签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + charset);
    }
  }
  
  private static boolean isValidChar(char ch) {
    if (((ch >= '0') && (ch <= '9')) || ((ch >= 'A') && (ch <= 'Z')) || ((ch >= 'a') && (ch <= 'z')))
      return true;
    if (((ch >= '一') && (ch <= '翿')) || ((ch >= 32768) && (ch <= 38191)))
      return true;
    return false;
  }
  
  public static Map<String, String> paraFilter(Map<String, String> sArray)
  {
    Map<String, String> result = new HashMap();
    if ((sArray == null) || (sArray.size() <= 0)) {
      return result;
    }
    for (String key : sArray.keySet()) {
      String value = (String)sArray.get(key);
      if ((value != null) && (!value.equals("")) && (!key.equalsIgnoreCase("sign")) && 
        (!key.equalsIgnoreCase("sign_type")))
      {
        result.put(key, value); }
    }
    return result;
  }
  
  public static String createLinkString(Map<String, String> params)
  {
    List<String> keys = new ArrayList(params.keySet());
    Collections.sort(keys);
    String prestr = "";
    for (int i = 0; i < keys.size(); i++) {
      String key = (String)keys.get(i);
      String value = (String)params.get(key);
      if (i == keys.size() - 1) {
        prestr = prestr + key + "=" + value;
      } else {
        prestr = prestr + key + "=" + value + "&";
      }
    }
    return prestr;
  }
  
  public static String httpRequest(String requestUrl, String requestMethod, String outputStr)
  {
    StringBuffer buffer = null;
    try {
      URL url = new URL(requestUrl);
      HttpURLConnection conn = (HttpURLConnection)url.openConnection();
      conn.setRequestMethod(requestMethod);
      conn.setDoOutput(true);
      conn.setDoInput(true);
      conn.connect();
      
      if (outputStr != null) {
        OutputStream os = conn.getOutputStream();
        os.write(outputStr.getBytes("utf-8"));
        os.close();
      }
      
      InputStream is = conn.getInputStream();
      InputStreamReader isr = new InputStreamReader(is, "utf-8");
      BufferedReader br = new BufferedReader(isr);
      buffer = new StringBuffer();
      String line = null;
      while ((line = br.readLine()) != null) {
        buffer.append(line);
      }
      br.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
    return buffer.toString();
  }
  
  public static String urlEncodeUTF8(String source) { String result = source;
    try {
      result = URLEncoder.encode(source, "UTF-8");
    }
    catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }
    return result;
  }
  
  public static Map doXMLParse(String strxml)
    throws Exception
  {
    if ((strxml == null) || ("".equals(strxml))) {
      return null;
    }
    try
    {
      Map<String, String> data = new HashMap();
      
      DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
      documentBuilderFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
      documentBuilderFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
      documentBuilderFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
      documentBuilderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
      documentBuilderFactory.setFeature("http://javax.xml.XMLConstants/feature/secure-processing", true);
      documentBuilderFactory.setXIncludeAware(false);
      documentBuilderFactory.setExpandEntityReferences(false);
      
      InputStream stream = new ByteArrayInputStream(strxml.getBytes("UTF-8"));
      Document doc = documentBuilderFactory.newDocumentBuilder().parse(stream);
      doc.getDocumentElement().normalize();
      NodeList nodeList = doc.getDocumentElement().getChildNodes();
      for (int idx = 0; idx < nodeList.getLength(); idx++) {
        Node node = nodeList.item(idx);
        if (node.getNodeType() == 1) {
          org.w3c.dom.Element element = (org.w3c.dom.Element)node;
          data.put(element.getNodeName(), element.getTextContent());
        }
      }
      try {
        stream.close();
      }
      catch (Exception localException1) {}
      
      return data;
    } catch (Exception ex) {
      throw ex;
    }
  }
  
  public static String getChildrenText(List children)
  {
    StringBuffer sb = new StringBuffer();
    if (!children.isEmpty()) {
      Iterator it = children.iterator();
      while (it.hasNext()) {
        org.jdom.Element e = (org.jdom.Element)it.next();
        String name = e.getName();
        String value = e.getTextNormalize();
        List list = e.getChildren();
        sb.append("<" + name + ">");
        if (!list.isEmpty()) {
          sb.append(getChildrenText(list));
        }
        sb.append(value);
        sb.append("</" + name + ">");
      }
    }
    
    return sb.toString();
  }
  
  public static InputStream String2Inputstream(String str) { return new ByteArrayInputStream(str.getBytes()); }
}

4:WxPayConfig  微信支付请求的一些基本参数 静态的 实体类 

package com.xinjue.util; 
/** 
 * @author tqf
 * @version 创建时间:2019-4-10 上午11:13:33 
 * 类说明    小程序微信支付的配置文件
 */
public class WxPayConfig {
	
		//小程序appid
		public static final String appid = "";
		// 公众号ID
		public static final String GZH_appid = "";
		//微信支付的商户id
		public static final String mch_id = "";
		//微信支付的商户密钥
		public static final String key = "";
		//支付成功后的服务器回调url
		//public static final String notify_url = ""; //正式区
		public static final String notify_url = ""; //测试区
		//签名方式,固定值
		public static final String SIGNTYPE = "MD5";
		//交易类型,小程序支付的固定值为JSAPI
		public static final String TRADETYPE = "JSAPI";
		//交易类型 wap H5端
		public static final String GZH_TRADETYPE = "MWEB";
		//微信统一下单接口地址
		public static final String pay_url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
		
		// H5端 场景信息   scene_info
		public static final String scene_info = "{\"h5_info\": {\"type\":\"WAP\",\"wap_url\": \"\",\"wap_name\": \"心觉咨询\"}}";
}
 

测试的话 需要在商户的H5支付设置

发布了72 篇原创文章 · 获赞 3 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/tanqingfu1/article/details/103860898