微信app支付java服务端

本文介绍如何在Java服务端实现微信APP支付功能,包括微信开放平台注册、获取必要参数及实现支付流程的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

微信app支付java服务端:

     1:前往微信开放平台,不是公众平台。注册并登陆。添加应用,按要求完成应用申请,提供公司应用图片信息,填写应用主要功能业务。需要支付300大洋。大约两三天审核就会通过,不教怎么申请各种破事,自行摸索,只贴出直接可用的代码。

     2:拿到APPId,AppSecret。进入微信支付接入商户。认真阅读页面信息。微信支付比支付宝支付恶心一点。得自己慢慢谷脑。之后申请开通支付功能。

    3:下面是代码。

       本文也是在查阅各种资料之后整理成自己可用的代码。方便自己日后工作需要。

@Controller
@RequestMapping("WXpay")
public class WxpayController {
    //声明logger
	private final static Logger logger =Logger.getLogger(WxpayController.class);
	// 微信支付商户号
	@Value("${USER_NUMBER}")
	private String mchId;
	// APIKey 交易过程中生成签名的密钥
	@Value("${APIKey}")
	private String WxApiKey;
	// APPID
	@Value("${APPID}")
	private String WxAppid;
	// SECRET 是appid对应的接口密码,用于获取接口调用凭证access_token使用。
	@Value("${SECRET}")
	private String WxSecret;
	 
	
	
	
	private String notifyUrl = " ...";
	/*
	 * 统一下单接口,我这里是传入订单id之后查询出具体订单信息。
	 */
	@RequestMapping(value = "params", method=RequestMethod.POST,produces = "application/json;charset=utf-8")
	@ResponseBody
	public Map<String, Object> params(Integer orderId,HttpServletRequest request) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		 
		try {
			 			 
			// 金额--->w微信支付金额参数以分为单位所以需要*100;
			 int acc = orderMoney.multiply(new BigDecimal(100)).intValue();
			// 金额不得小于0
			if (acc <= 0) {
				resultMap.put("msg", "付款金额错误");
				resultMap.put("code", "500");
				return resultMap;
			}
			SortedMap<Object, Object> map = new TreeMap<Object, Object>();
			map.put("appid", WxAppid);
			map.put("mch_id", mchId);
			map.put("nonce_str", WxApiKey);
			map.put("body", orderTitile);
			map.put("out_trade_no",orderNum); // 订单id
			map.put("fee_type", "CNY");     //货币类型 默认人民币:CNY
			map.put("total_fee", String.valueOf(acc));
			//获取用户ip
			map.put("spbill_create_ip", CommonUtil.getIpAddr(request));
			map.put("notify_url", notifyUrl);
			map.put("trade_type", "APP");
            //设置签名
			String sign = PayCommonUtil.createSign("UTF-8", map);
			map.put("sign", sign);
			//封装请求参数结束
	         String requestXML = PayCommonUtil.getRequestXml(map);
	       //调用统一下单接口
	         String result = PayCommonUtil.httpsRequest(ConfigUtil.UNIFIED_ORDER_URL, "POST", requestXML);
	         logger.info("Wx-下单信息:"+result);
	         /**统一下单接口返回正常的prepay_id,再按签名规范重新生成签名后,
	          * 将数据传输给APP。参与签名的字段名为
	          * appId,partnerId,prepayId,nonceStr,timeStamp,package。
	          * 注意:package的值格式为Sign=WXPay**/
	         Map map2 = XMLutil.doXMLParse(result);
	         SortedMap<Object,Object> map3 = new TreeMap<Object, Object>();
	         map3.put("appid", WxAppid);
	         map3.put("partnerid", mchId);
	         map3.put("prepayid", map2.get("prepay_id"));
	         map3.put("package", "Sign=WXPay");
	         map3.put("noncestr", PayCommonUtil.CreateNoncestr());
	         //生成时间戳 13位 ios默认规定10位
	         map3.put("timestamp", Long.parseLong(String.valueOf(System.currentTimeMillis()).toString().substring(0, 10)));
	         String sign2=PayCommonUtil.createSign("UTF-8", map3);
	         map3.put("sign", sign2);
	         resultMap.put("code", "200");
	         resultMap.put("msg", map3);
	         return resultMap;
	         
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return resultMap;

	}

	// 微信回调
	@ResponseBody
	@RequestMapping(value = "WxNotify.html", produces = "application/json;charset=utf-8", method = {
			RequestMethod.POST })
	public String returnmsg(HttpServletRequest request) throws Exception {
		// 定义map,解析结果存储
		HashMap<String, String> map = new HashMap<String, String>();

		InputStream inputStream = request.getInputStream();
		// 读取输入流
		SAXReader reader = new SAXReader();
		Document document = reader.read(inputStream);
		// 获得xml根元素
		Element root = document.getRootElement();
		// 得到根元素的所有子节点
		List<Element> elementList = root.elements();
		for (Element e : elementList) {
			map.put(e.getName(), e.getText());
		}
		JSONObject json = JSONObject.fromObject(map);
		System.out.println("消息通知结果:" + json.toString());
		   logger.info("Wx-消息通知结果:" + json.toString());
		// 验证签名的过程

		// 判断是否支付成功
		if (map.get("return_code").equals("SUCCESS")) {
                
			/**
			 * 支付成功之后的业务处理
			 */
            //商户订单号
			String out_trade_no = map.get("out_trade_no");
			//商户号
			String mch_id = map.get("mch_id");
			//用户标识
			String openid=map.get("openid");
			//总金额
			 String total_fee =map.get("total_fee");
			 //微信支付订单号
			 String transaction_id = map.get("transaction_id");
			 //支付时间
			 String time_end = map.get("time_end");

		        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		        Date date =null;
		        try {
		        	
		        	date =  format.parse(time_end);
				} catch (Exception e) {
					// TODO: handle exception
				}  
			 
			// 释放资源
			inputStream.close();
			inputStream = null;

			// bis.close();
			return "SUCCESS";
		}

		if (map.get("return_code").equals("FAIL")) {

			/**
			 * 支付失败后的业务处理
			 */
               
			// 释放资源
			inputStream.close();

			inputStream = null;

			return "SUCCESS";
		}

		// 释放资源
		inputStream.close();
		inputStream = null;

		return "SUCCESS";

	}
	
	  

注:上面是主要加签和回调的代码。缺少 传入订单id之后,调用dao层进行数据库查询。可自己测试写成假数据。这里会用到一个准确获取用户的ip地址,也贴出来吧。

     

 public static String getIpAddr(HttpServletRequest request){  
	        String ipAddress = request.getHeader("x-forwarded-for");  
	            if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {  
	                ipAddress = request.getHeader("Proxy-Client-IP");  
	            }  
	            if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {  
	                ipAddress = request.getHeader("WL-Proxy-Client-IP");  
	            }  
	            if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {  
	                ipAddress = request.getRemoteAddr();  
	                if(ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")){  
	                    //根据网卡取本机配置的IP  
	                    InetAddress inet=null;  
	                    try {  
	                        inet = InetAddress.getLocalHost();  
	                    } catch (UnknownHostException e) {  
	                        e.printStackTrace();  
	                    }  
	                    ipAddress= inet.getHostAddress();  
	                }  
	            }  
	            //对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割  
	            if(ipAddress!=null && ipAddress.length()>15){ //"***.***.***.***".length() = 15  
	                if(ipAddress.indexOf(",")>0){  
	                    ipAddress = ipAddress.substring(0,ipAddress.indexOf(","));  
	                }  
	            }  
	            return ipAddress;   
	    }

下面是各工具类。做出详细介绍;

1:服务号相关信息;

public class ConfigUtil {
	 /**
     * 服务号相关信息
     */
     public final static String APPID = "**";//服务号的应用号
     public final static String MCH_ID = "***2";//商户号
     public final static String API_KEY = "*-***";//API密钥
     public final static String SIGN_TYPE = "MD5";//签名加密方式
     public final static String SECRET="*******";

    public final static String UNIFIED_ORDER_URL = "https://api.mch.weixin.qq.com/pay/unifiedorder";
}

2:MD5加密

public class MD5Util {
	 private static String byteArrayToHexString(byte b[]) {
	        StringBuffer resultSb = new StringBuffer();
	        for (int i = 0; i < b.length; i++)
	            resultSb.append(byteToHexString(b[i]));

	        return resultSb.toString();
	    }

	    private static String byteToHexString(byte b) {
	        int n = b;
	        if (n < 0)
	            n += 256;
	        int d1 = n / 16;
	        int d2 = n % 16;
	        return hexDigits[d1] + hexDigits[d2];
	    }

	    public static String MD5Encode(String origin, String charsetname) {
	        String resultString = null;
	        try {
	            resultString = new String(origin);
	            MessageDigest md = MessageDigest.getInstance("MD5");
	            if (charsetname == null || "".equals(charsetname))
	                resultString = byteArrayToHexString(md.digest(resultString
	                        .getBytes()));
	            else
	                resultString = byteArrayToHexString(md.digest(resultString
	                        .getBytes(charsetname)));
	        } catch (Exception exception) {
	        }
	        return resultString;
	    }

	    private static final String hexDigits[] = { "0", "1", "2", "3", "4", "5",
	            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
}

3:信息管理器:

public class My509TrustManager implements X509TrustManager {
	   // 检查客户端证书
    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    }

    // 检查服务器端证书
    public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    }

    // 返回受信任的X509证书数组
    public X509Certificate[] getAcceptedIssuers() {
        return null;
    }
}

4:支付工具类

/**
 * 微信支付工具
 * @author huangjiangmin
 * @date
 */
public class PayCommonUtil {
	// 微信支付商户号
		@Value("${USER_NUMBER}")
		private String mchId;
		// APIKey 交易过程中生成签名的密钥
		@Value("${APIKey}")
		private String WxApiKey;
		// APPID
		@Value("${APPID}")
		private String WxAppid;
		// SECRET 是appid对应的接口密码,用于获取接口调用凭证access_token使用。
		@Value("${SECRET}")
		private String WxSecret;
	
	
	public static String CreateNoncestr(int length) {
        String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        String res = "";
        for (int i = 0; i < length; i++) {
            Random rd = new Random();
            res += chars.indexOf(rd.nextInt(chars.length() - 1));
        }
        return res;
    }

    public static String CreateNoncestr() {
        String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        String res = "";
        for (int i = 0; i < 16; i++) {
            Random rd = new Random();
            res += chars.charAt(rd.nextInt(chars.length() - 1));
        }
        return res;
    }


    /** 
     * 是否签名正确,规则是:按参数名称a-z排序,遇到空值的参数不参加签名。 
     * @return boolean 
     */  
    public static boolean isTenpaySign(String characterEncoding, SortedMap<Object, Object> packageParams) {  
        StringBuffer sb = new StringBuffer();  
        Set es = packageParams.entrySet();  
        Iterator it = es.iterator();  
        while(it.hasNext()) {  
            Map.Entry entry = (Map.Entry)it.next();  
            String k = (String)entry.getKey();  
            String v = (String)entry.getValue();  
            if(!"sign".equals(k) && null != v && !"".equals(v)) {  
                sb.append(k + "=" + v + "&");  
            }  
        }  

        sb.append("key=" + ConfigUtil.API_KEY);  

        //算出摘要  
        String mysign = MD5Util.MD5Encode(sb.toString(), characterEncoding).toLowerCase();  
        String tenpaySign = ((String)packageParams.get("sign")).toLowerCase();  

        //System.out.println(tenpaySign + "    " + mysign);  
        return tenpaySign.equals(mysign);  
    }  


    /**
     * @Description:sign签名
     * @param characterEncoding 编码格式
     * @param parameters 请求参数
     * @return
     */
    public static String createSign(String characterEncoding,SortedMap<Object,Object> parameters){
        StringBuffer sb = new StringBuffer();
        Set es = parameters.entrySet();
        Iterator it = es.iterator();
        while(it.hasNext()) {
            Map.Entry entry = (Map.Entry)it.next();
            String k = (String)entry.getKey();
            Object v = entry.getValue();
            if(null != v && !"".equals(v) 
                    && !"sign".equals(k) && !"key".equals(k)) {
                sb.append(k + "=" + v + "&");
            }
        }
        sb.append("key="+ConfigUtil.API_KEY);
        String sign = MD5Util.MD5Encode(sb.toString(), characterEncoding).toUpperCase();
        return sign;
    }
    /**
     * @Description:将请求参数转换为xml格式的string
     * @param parameters  请求参数
     * @return
     */
    public static String getRequestXml(SortedMap<Object,Object> parameters){
        StringBuffer sb = new StringBuffer();
        sb.append("<xml>");
        Set es = parameters.entrySet();
        Iterator it = es.iterator();
        while(it.hasNext()) {
            Map.Entry entry = (Map.Entry)it.next();
            String k = (String)entry.getKey();
            String v = (String)entry.getValue();
            if ("attach".equalsIgnoreCase(k)||"body".equalsIgnoreCase(k)) {
                sb.append("<"+k+">"+"<![CDATA["+v+"]]></"+k+">");
            }else {
                sb.append("<"+k+">"+v+"</"+k+">");
            }
        }
        sb.append("</xml>");
        return sb.toString();
    }
    /**
     * @Description:返回给微信的参数
     * @param return_code 返回编码
     * @param return_msg  返回信息
     * @return
     */
    public static String setXML(String return_code, String return_msg) {
        return "<xml><return_code><![CDATA[" + return_code
                + "]]></return_code><return_msg><![CDATA[" + return_msg
                + "]]></return_msg></xml>";
    }


    /**
     * 发送https请求
     * @param requestUrl 请求地址
     * @param requestMethod 请求方式(GET、POST)
     * @param outputStr 提交的数据
     * @return 返回微信服务器响应的信息
     */
    public static String httpsRequest(String requestUrl, String requestMethod, String outputStr) {
        try {
            // 创建SSLContext对象,并使用我们指定的信任管理器初始化
            TrustManager[] tm = { new My509TrustManager() };
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();
            URL url = new URL(requestUrl);
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            //conn.setSSLSocketFactory(ssf);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            // 设置请求方式(GET/POST)
            conn.setRequestMethod(requestMethod);
            conn.setRequestProperty("content-type", "application/x-www-form-urlencoded"); 
            // 当outputStr不为null时向输出流写数据
            if (null != outputStr) {
                OutputStream outputStream = conn.getOutputStream();
                // 注意编码格式
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }
            // 从输入流读取返回内容
            InputStream inputStream = conn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            StringBuffer buffer = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            // 释放资源
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            inputStream = null;
            conn.disconnect();
            return buffer.toString();
        } catch (ConnectException ce) {
//          log.error("连接超时:{}", ce);
        } catch (Exception e) {
//          log.error("https请求异常:{}", e);
        }
        return null;
    }

    /**
     * 发送https请求
     * 
     * @param requestUrl 请求地址
     * @param requestMethod 请求方式(GET、POST)
     * @param outputStr 提交的数据
     * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
     */
     public static JSONObject httpsRequest(String requestUrl, String requestMethod) {
            JSONObject jsonObject = null;
            try {
                    // 创建SSLContext对象,并使用我们指定的信任管理器初始化
                    TrustManager[] tm = { new My509TrustManager() };
                    SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
                    sslContext.init(null, tm, new java.security.SecureRandom());
                    // 从上述SSLContext对象中得到SSLSocketFactory对象
                    SSLSocketFactory ssf = sslContext.getSocketFactory();
                    URL url = new URL(requestUrl);
                    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
                    //conn.setSSLSocketFactory(ssf);
                    conn.setDoOutput(true);
                    conn.setDoInput(true);
                    conn.setUseCaches(false);
                    conn.setConnectTimeout(3000);
                    // 设置请求方式(GET/POST)
                    conn.setRequestMethod(requestMethod);
                    //conn.setRequestProperty("content-type", "application/x-www-form-urlencoded"); 
                    // 当outputStr不为null时向输出流写数据
                    // 从输入流读取返回内容
                    InputStream inputStream = conn.getInputStream();
                    InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
                    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                    String str = null;
                    StringBuffer buffer = new StringBuffer();
                    while ((str = bufferedReader.readLine()) != null) {
                            buffer.append(str);
                    }
                    // 释放资源
                    bufferedReader.close();
                    inputStreamReader.close();
                    inputStream.close();
                    inputStream = null;
                    conn.disconnect();
                    jsonObject = JSONObject.parseObject(buffer.toString());
            } catch (ConnectException ce) {
//                    log.error("连接超时:{}", ce);
            } catch (Exception e) {
                    System.out.println(e);
//                    log.error("https请求异常:{}", e);
            }
            return jsonObject;
}

    public static String urlEncodeUTF8(String source){
        String result = source;
        try {
            result = java.net.URLEncoder.encode(source,"utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }
}

5:用于微信的Xml解析封装:

/**
 * xml封装用于微信支付
 * @author huangjiangmin
 * @date 2018年3月27日上午10:17:37
 */
public class XMLutil {
	 /**
     * 解析xml,返回第一级元素键值对。如果第一级元素有子节点,则此节点的值是子节点的xml数据。
     * @param strxml
     * @return
     * @throws JDOMException
     * @throws IOException
     */
    public static Map doXMLParse(String strxml) throws JDOMException, IOException {
        strxml = strxml.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\"");

        if(null == strxml || "".equals(strxml)) {
            return null;
        }

        Map m = new HashMap();

        InputStream in = new ByteArrayInputStream(strxml.getBytes("UTF-8"));
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(in);
        Element root = doc.getRootElement();
        List list = root.getChildren();
        Iterator it = list.iterator();
        while(it.hasNext()) {
            Element e = (Element) it.next();
            String k = e.getName();
            String v = "";
            List children = e.getChildren();
            if(children.isEmpty()) {
                v = e.getTextNormalize();
            } else {
                v = XMLutil.getChildrenText(children);
            }

            m.put(k, v);
        }

        //关闭流
        in.close();

        return m;
    }

    /**
     * 获取子结点的xml
     * @param children
     * @return String
     */
    public static String getChildrenText(List children) {
        StringBuffer sb = new StringBuffer();
        if(!children.isEmpty()) {
            Iterator it = children.iterator();
            while(it.hasNext()) {
                Element e = (Element) it.next();
                String name = e.getName();
                String value = e.getTextNormalize();
                List list = e.getChildren();
                sb.append("<" + name + ">");
                if(!list.isEmpty()) {
                    sb.append(XMLutil.getChildrenText(list));
                }
                sb.append(value);
                sb.append("</" + name + ">");
            }
        }

        return sb.toString();
    }

}
一步一步下来。微信支付就完成了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值