欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

微信支付java后台,安卓前端

程序员文章站 2024-01-22 21:32:40
...

1,查询流程图:

https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=8_3
微信支付java后台,安卓前端

2,后台对应的api

https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=9_1

3,先去管理中心,应用详情里面查看 AppId,在微信支付里面找到商户号MCH_ID,

登录微信pay.weixin.qq.com,中在账户中心--->api安全里面配置api**(API_KEY):

微信支付java后台,安卓前端

 

4,根据api知道数据是要xml格式

<xml>
  <appid><![CDATA[wx2421b1c4370ec43b]]></appid>
  <attach><![CDATA[支付测试]]></attach>
  <bank_type><![CDATA[CFT]]></bank_type>
  <fee_type><![CDATA[CNY]]></fee_type>
  <is_subscribe><![CDATA[Y]]></is_subscribe>
  <mch_id><![CDATA[10000100]]></mch_id>
  <nonce_str><![CDATA[5d2b6c2a8db53831f7eda20af46e531c]]></nonce_str>
  <openid><![CDATA[oUpF8uMEb4qRXf22hE3X68TekukE]]></openid>
  <out_trade_no><![CDATA[1409811653]]></out_trade_no>
  <result_code><![CDATA[SUCCESS]]></result_code>
  <return_code><![CDATA[SUCCESS]]></return_code>
  <sign><![CDATA[B552ED6B279343CB493C5DD0D78AB241]]></sign>
  <sub_mch_id><![CDATA[10000100]]></sub_mch_id>
  <time_end><![CDATA[20140903131540]]></time_end>
  <total_fee>1</total_fee><coupon_fee><![CDATA[10]]></coupon_fee>
<coupon_count><![CDATA[1]]></coupon_count>
<coupon_type><![CDATA[CASH]]></coupon_type>
<coupon_id><![CDATA[10000]]></coupon_id>
<coupon_fee_0><![CDATA[100]]></coupon_fee_0>
  <trade_type><![CDATA[JSAPI]]></trade_type>
  <transaction_id><![CDATA[1004400740201409030005092168]]></transaction_id>
</xml>

4,准备工具类WeChatUntils;https://download.csdn.net/download/Oujenny/12026538

maven导入一个包:

  <!-- https://mvnrepository.com/artifact/org.jdom/jdom -->
        <dependency>
            <groupId>org.jdom</groupId>
            <artifactId>jdom</artifactId>
            <version>2.0.2</version>
        </dependency>
package com.xxx.util;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.Set;
import java.util.SortedMap;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;

import com.xxxx.controller.MyX509TrustManager;

public class WechatUtil {
	
	
	  //签名类  utf-8
	  public static String createSign(String characterEncoding, SortedMap<String, 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;
	    }
	  
	  
	 // SSL协议发起http请求
	  public static String getRequestXml(SortedMap<String, 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();
	    } 
/*	  public static String getRequestXml(SortedMap<String, Object> parameters) {
	        StringBuffer sb = new StringBuffer();
	        sb.append("<xml>");
	        Iterator<Entry<String, Object>> iterator = parameters.entrySet().iterator();
	        while (iterator.hasNext()) {
	            Entry<String,Object> entry = (Entry<String,Object>) iterator.next();
	            String key = (String) entry.getKey();
	            String value = (String) entry.getValue();
	            sb.append("<" + key + ">" + value + "</" + key + ">");
	        }
	        sb.append("</xml>");
	        return sb.toString();
	    }*/
	  

	  /**
	     * 发送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 MyX509TrustManager()};
	            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;
	    }	  
	  
	  //随机数
	    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;
	    }
	    
	    

	    /**
	     * 解析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();
	    }
	    
	    
	    

	    /**
	     * 是否签名正确,规则是:按参数名称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);
	    }


}

5,必要参数:

package com.xxx.util;

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


    public final static String UNIFIED_ORDER_URL = "https://api.mch.weixin.qq.com/pay/unifiedorder";//请求下单的http

}

6,信任管理器:

package com.xxxx.controller;

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.X509TrustManager;

public class MyX509TrustManager  implements X509TrustManager {

	@Override
	public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public X509Certificate[] getAcceptedIssuers() {
		// TODO Auto-generated method stub
		return  new X509Certificate[0];
	}

}

7,XMLUtil 

package com.xxxx.util;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;

public class XMLUtil {
    /**
     * 解析xml,返回第一级元素键值对。如果第一级元素有子节点,则此节点的值是子节点的xml数据。
     */
    public static Map doXMLParse(String strxml) throws Exception {
        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
     */
    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();
    }
    
}

8,UUIDUtil 

package com.xxx.util;

import java.util.UUID;

/**
 * 唯一标识uuid
 * @author Administrator
 *
 */
public class UUIDUtil {
	
	//生成指定个数的uuid
	public static String[] getUUID(int num) {
		
		if(num<=0) {
			return null;
		}
		String[] uuidAri=new String[num];
		
		for(int i=0;i<uuidAri.length;i++) {
			uuidAri[i]=getUUID32();
		}
		
		return uuidAri;
	}

	
	//32位的uuid
	public static String getUUID32() {
		
		String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();

		
		return uuid;
	}
	
	public static void main(String[] args) {
		 getUUID32();
		 
		 getUUID(5);
		 
	}
}

 

9,微信下单:
 

//测试环境
		//微信默认从单位为分,所以用此方法将单位调整成元
		 // int price100 = new BigDecimal(price).multiply(new BigDecimal(100)).intValue();
		            SortedMap<String, Object> parameters = new TreeMap<String, Object>();
		            parameters.put("appid", ConfigUtil.APPID);//appid
		            parameters.put("attach", "xxxxx");//附加数据
		            parameters.put("body", "会员充值中心");//商品描述
		            parameters.put("mch_id", ConfigUtil.MCH_ID);//商户号
		            parameters.put("nonce_str", WechatUtil.CreateNoncestr());//随机字符串
		            parameters.put("notify_url", "http://www.weixin.qq.com/wxpay/pay.php");//回调地址
		            
		            parameters.put("out_trade_no", UUIDUtil.getUUID32()); //商户订单号
		            //parameters.put("spbill_create_ip", "123.12.12.123");//终端ip
		            
		            parameters.put("total_fee", "1");//金额
		            parameters.put("trade_type", "APP");//交易类型
		            parameters.put("fee_type", "CNY");//金额类型
		           /* parameters.put("total_fee", String.valueOf(price100));*/
		           
		            //parameters.put("spbill_create_ip", "127.0.0.1");//终端IP	
		           
		            
		            //设置签名
		            String sign =WechatUtil.createSign("UTF-8", parameters);
		            System.out.println(sign);
		            parameters.put("sign", sign);
		            //封装请求参数结束
		            String requestXML = PayCommonUtil.getRequestXml(parameters);
		            System.out.println(requestXML);
		            //调用统一下单接口
		            String result = PayCommonUtil.httpsRequest(ConfigUtil.UNIFIED_ORDER_URL, "POST", requestXML);//地址
		            System.out.println("\n" + result);
		            try {
		                /**统一下单接口返回正常的prepay_id,再按签名规范重新生成签名后,将数据传输给APP。参与签名的字段名为appId,partnerId,prepayId,nonceStr,timeStamp,package。注意:package的值格式为Sign=WXPay**/
		                Map<String, String> map = XMLUtil.doXMLParse(result);
		                SortedMap<String, Object> parameterMap2 = new TreeMap<String, Object>();
		                parameterMap2.put("appid", ConfigUtil.APPID);
		                parameterMap2.put("partnerid", ConfigUtil.MCH_ID);
		                parameterMap2.put("prepayid", map.get("prepay_id"));
		                parameterMap2.put("package", "Sign=WXPay");
		                parameterMap2.put("noncestr", WechatUtil.CreateNoncestr());
		                //本来生成的时间戳是13位,但是ios必须是10位,所以截取了一下
		                parameterMap2.put("timestamp", Long.parseLong(String.valueOf(System.currentTimeMillis()).toString().substring(0, 10)));
		                String sign2 = WechatUtil.createSign("UTF-8", parameterMap2);
		                parameterMap2.put("sign", sign2);//此 parameterMap2内容送到ios调用就可以了
		               /* landlordNew.setWxSign(sign2);
		                this.landlordNewService.update(landlordNew);*/
		                HashMap<Object, Object> resultMap = new HashMap<>();
		                resultMap.put("code", "200");
		                resultMap.put("msg", parameterMap2);
		                System.out.println(resultMap);
		            } catch (JDOMException e) {
		                e.printStackTrace();
		            } catch (IOException e) {
		                e.printStackTrace();
		            }

10,微信的异步回调

/**
	     * 微信异步通知 (签约支付)
	     */
	   @RequestMapping(value="/wechatandalipay/Wechatpaycallback",method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	    @ResponseBody
	    public String Wechatpaycallback(HttpServletRequest request, HttpServletResponse response) {

	        try {
	            //读取参数
	            InputStream inputStream;
	            StringBuffer sb = new StringBuffer();
	            inputStream = request.getInputStream();
	            String s;
	            BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
	            while ((s = in.readLine()) != null) {
	                sb.append(s);
	            }
	            in.close();
	            inputStream.close();
	            //解析xml成map
	            Map<String, String> m = new HashMap<String, String>();
	            m = XMLUtil.doXMLParse(sb.toString());
	            for (Object keyValue : m.keySet()) {
	                System.out.println(keyValue + "=" + m.get(keyValue));
	            }
	            //过滤空 设置 TreeMap
	            SortedMap<Object, Object> packageParams = new TreeMap<Object, Object>();
	            Iterator it = m.keySet().iterator();
	            while (it.hasNext()) {
	                String parameter = (String) it.next();
	                String parameterValue = m.get(parameter);

	                String v = "";
	                if (null != parameterValue) {
	                    v = parameterValue.trim();
	                }
	                packageParams.put(parameter, v);
	            }

	            //判断签名是否正确
	            String resXml = "";
	            if (PayCommonUtil.isTenpaySign("UTF-8", packageParams)) {
	                if ("SUCCESS".equals((String) packageParams.get("result_code"))) {
	                    // 这里是支付成功
	                    //////////执行自己的业务逻辑////////////////
	                    String appid = (String) packageParams.get("appid");//appid
	                    String sign = (String) packageParams.get("sign");//签名
	                    String total_fee = (String) packageParams.get("total_fee");//总金额
	                    String mch_id = (String) packageParams.get("mch_id"); //商户号
	                    String openid = (String) packageParams.get("openid");  //用户标识

	                //微信回调 商户号回调的商户订单号是out_trade_no
	               //(需要唯一,同一个订单号执行下单接口会报错),这里笔者使用
	              //nonce_str作为订单号,后续还需要改动。这个字段官方文档解释为随机字
	              //符串,但后来发现回调的时候返回的nonce_str跟下单填进去的nonce_str
	             //一致,所以暂时用来当订单号了。)
	                    String out_trade_no = (String) packageParams.get("nonce_str"); //商户订单号
	                    String transaction_id = (String) packageParams.get("transaction_id"); //微信支付订单号
	                   写逻辑代码
	                    
						}
	                    //this.contractpayReturn(appid, sign, total_fee, mch_id, openid, out_trade_no, transaction_id);
	                    resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
	                            + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
	                    
	                    return resXml;
	                   
	                } else {
	                   // logger.info("支付失败,错误信息:" + packageParams.get("err_code"));
	                    resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
	                            + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
	                    
	                    return resXml;
	                }
	            } else {
	                resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
	                        + "<return_msg><![CDATA[通知签名验证失败]]></return_msg>" + "</xml> ";
	                
	               
	                  
	            }
	            BufferedOutputStream out = new BufferedOutputStream(
	                    response.getOutputStream());
	            out.write(resXml.getBytes());
	            out.flush();
	            out.close();
	            return resXml;
	        } catch (Exception ex) {
	      
	        }
	        
	        
	        return "";
	   }

注意:

如果是签名错误  就去api那里的签名校正,如果校正是对的  那么就是api**错误。

相关标签: 支付 微信支付