微信 Java调用微信自动发红包

作者:じ☆ve宝贝

发布时间:2015-09-15T14:19:40

java调用微信发送红包

配置信息Const.java

public class Const {

	public static final String WXAPPID = "appid" ; //商户appid
	public static final String MCH_ID = "商户号" ; //商户号
	public static final String KEY = "API初始密钥" ; //API初始密钥
	public static final String URL = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";//微信api接口
	public static final String KEYSTORE_FILE = "D:/zhengshu/apiclient_cert.p12";//证书存放地址
	public static final String KEYSTORE_PASSWORD = "商户密码";
	
}

Md5.java

package cn.studyjava.weixin.util;

import java.security.MessageDigest;

public class Md5 {
	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" };
}

RedPaperUtil.java

package cn.studyjava.weixin.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.security.KeyStore;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.net.ssl.SSLContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;



public class RedPaperUtil {

	/**
	 * 
	 * @param nonce_str
	 *            随机字符串
	 * @param mch_billno
	 *            商户订单
	 * @param mch_id
	 *            商户号
	 * @param wxappid
	 *            商户appid
	 * @param nick_name
	 *            提供方名称
	 * @param send_name
	 *            用户名
	 * @param re_openid
	 *            用户openid
	 * @param total_amount
	 *            付款金额 单位 分
	 * @param min_value
	 *            最小红包 单位 分
	 * @param max_value
	 *            最大红包 单位 分 (最小金额等于最大金额:min_value=max_value=total_amount)
	 * @param total_num
	 *            红包发送总人数
	 * @param wishing
	 *            红包祝福语
	 * @param client_ip
	 *            ip地址
	 * @param act_name
	 *            活动名称
	 * @param remark
	 *            备注
	 */
	public static Map<String, Object> redPaper(String nonce_str, String mch_billno, String nick_name,
			String send_name, String re_openid, String total_amount,
			String min_value, String max_value, String total_num,
			String wishing, String client_ip, String act_name, String remark) {

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("nonce_str", nonce_str);// 随机字符串
		map.put("mch_billno", mch_billno);// 商户订单
		map.put("mch_id", Const.MCH_ID);// 商户号
		map.put("wxappid", Const.WXAPPID);// 商户appid
		map.put("nick_name", nick_name);// 提供方名称
		map.put("send_name", send_name);// 用户名
		map.put("re_openid", re_openid);// 用户openid
		map.put("total_amount", total_amount);// 付款金额
		map.put("min_value", min_value);// 最小红包
		map.put("max_value", max_value);// 最大红包
		map.put("total_num", total_num);// 红包发送总人数
		map.put("wishing", wishing);// 红包祝福语
		map.put("client_ip", client_ip);// ip地址
		map.put("act_name", act_name);// 活动名称
		map.put("remark", remark);// 备注
		map.put("sign", createSign(map));// 签名
		return map;
	}

	/**
	 * 微信支付签名算法sign
	 * 
	 * @param map
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static String createSign(Map<String , Object> map) {
		SortedMap<Object,Object> parameters = new TreeMap<Object,Object>();  
		for (Map.Entry<String, Object> m : map.entrySet()) {
			parameters.put(m.getKey(), m.getValue().toString());
		}
		StringBuffer sb = new StringBuffer();
		Set es = parameters.entrySet();// 所有参与传参的参数按照accsii排序(升序)
		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=" + Const.KEY);
		String sign = Md5.MD5Encode(sb.toString(), "UTF-8")
				.toUpperCase();
		return sign;
	}
	
	/**
	 * 创建xml
	 * @param map
	 * @return
	 */
	public static String createXML(Map<String, Object> map){
		String xml = "<xml>";
		Set<String> set = map.keySet();
		Iterator<String> i = set.iterator();
		while(i.hasNext()){
			String str = i.next();
			xml+="<"+str+">"+"<![CDATA["+map.get(str)+"]]>"+"</"+str+">";
		}
		xml+="</xml>";
		return xml;
	}
	
	/**
	 * 随机数值
	 * 
	 * @return
	 */
	public static String buildRandom() {
		String currTime = getCurrTime();
		String strTime = currTime.substring(8, currTime.length());
		int num = 1;
		double random = Math.random();
		if (random < 0.1) {
			random = random + 0.1;
		}
		for (int i = 0; i < 1; i++) {
			num = num * 10;
		}
		return (int) ((random * num)) + strTime;
	}

	/**
	 * 获取当前时间 yyyyMMddHHmmssSSS
	 * @return String
	 */ 
	public static String getCurrTime() {
		Date now = new Date();
		SimpleDateFormat outFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		String s = outFormat.format(now);
		System.out.println(s);
		return s;
	}
	/**
	 * 订单号生成 商户号+当前时间+1位随机数
	 * 
	 * @param map
	 * @return
	 */
	public static String getOrderNo() {
		String order = Const.MCH_ID
				+getCurrTime();
		Random r = new Random();
		for (int i = 0; i < 1; i++) {
			order += r.nextInt(9);
		}
		System.out.println(order.length()-10-8);
		return order;
	}
	
	/**
	 * 获取ip
	 * 
	 * @param request
	 * @return
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("PRoxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		if (null == ip) {
			ip = "";
		}
		if (!"".equals(ip)) {
			String[] ipArr = ip.split(",");
			if (ipArr.length > 1) {
				ip = ipArr[0];
			}
		}
		return ip;
	}
	
	/**
	 * 发送红包
	 * @param data xml格式数据
	 *
	 */
	
	@SuppressWarnings("unchecked")
	public static Map<String, String> doSendMoney(String data) throws Exception {
		KeyStore keyStore  = KeyStore.getInstance("PKCS12");
		FileInputStream instream = new FileInputStream(new File(Const.KEYSTORE_FILE));//P12文件目录
        try {
            keyStore.load(instream, Const.KEYSTORE_PASSWORD.toCharArray());//这里写密码..默认是你的MCHID
        } finally {
            instream.close();
        }
        SSLContext sslcontext = SSLContexts.custom()
                .loadKeyMaterial(keyStore, Const.KEYSTORE_PASSWORD.toCharArray())//这里也是写密码的
                .build();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null,
        		SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
        try {
        	HttpPost httpost = new HttpPost(Const.URL); // 设置响应头信息
        	httpost.addHeader("Connection", "keep-alive");
        	httpost.addHeader("Accept", "*/*");
        	httpost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        	httpost.addHeader("Host", "api.mch.weixin.qq.com");
        	httpost.addHeader("X-Requested-With", "XMLHttpRequest");
        	httpost.addHeader("Cache-Control", "max-age=0");
        	httpost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
    		httpost.setEntity(new StringEntity(data, "UTF-8"));
            CloseableHttpResponse response = httpclient.execute(httpost);
            try {
                HttpEntity entity = response.getEntity();
                BufferedReader responseBuffer = new BufferedReader(
        				new InputStreamReader((entity.getContent())));
                
                SAXReader reader = new SAXReader();
				Document document = reader.read(responseBuffer);
				Element root = document.getRootElement();
				List<Element> elementList = root.elements();
				Map<String, String> remap = new HashMap<String, String>();
				for (Element e : elementList)
					remap.put(e.getName(), e.getText());

				return remap;
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
	}
	
}

测试类

public static void main(String[] args) {
		Map<String, Object> map = RedPaperUtil.redPaper(RedPaperUtil.buildRandom(), RedPaperUtil.getOrderNo(), "Java学习论坛", "Java学习论坛", fromUserName, money+"", money+"", money+"", "1", "工作顺利", RedPaperUtil.getIpAddr(request), "你收到一个红包", "感谢关注Java学习论坛");
}
	System.out.println(RedPaperUtil.createXML(map));
	Map<String, String> remap = RedPaperUtil.doSendMoney(RedPaperUtil.createXML(map));
	if("FAIL".equals(remap.get("return_code"))){
		ciaActivity.setCheckStatus(Const.RED_BAG_SUC_STATUS);
		ciaActivityService.updateCiaActivityByExample(ciaActivity, ciaActivityExample);
		respContent=remap.get("return_msg");
	}else if("SUCCESS".equals(remap.get("return_code"))){
		return ;
	else{
		return ;
	}
}