微信公众号发送红包

不敢标原创,感谢 柳峰老师和另一位dalao(http://my.csdn.net/wgyscsf)
        /**
	 * 
	 * 微信发红包
	 * @param openid 用户openid
	 * @param wishing  红包祝福语
	 * @param totalAmount  红包金额
	 * @param actName  活动名称
	 * @param remark  备注信息
	 * @return true/false
	 */
	public boolean sendredPack(String openid,String wishing,String totalAmount,String actName,String remark) {
		boolean reCode = false;

		Packets packets = new Packets();
		String nostr = CreateNonceStr.getRandomString(32);
		packets.setNonce_str(nostr);// 随机数

		packets.setClient_ip(LOCALIP);// 本机IP

		packets.setMch_id(MCID);// 商户号

		packets.setWxappid(APPID);// appid

		packets.setSend_name("有你");

		packets.setRe_openid(openid);// openID

		packets.setAct_name(actName);

		Date d = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		// System.out.println("当前时间:" + sdf.format(d));
		String numb = sdf.format(d);
		packets.setMch_billno(MCID+numb);

		packets.setTotal_num("1");// 红包发放总人数

		packets.setWishing(wishing);// 红包祝福语

		packets.setTotal_amount(totalAmount);// 金额

		packets.setRemark(remark);//备注

		// packets.setScene_id("场景ID");

		// packets.setRisk_info("活动信息");

		// packets.setConsume_mch_id("资金授权商户号");

		Map<String, Object> params = new TreeMap<String, Object>(new Comparator<String>() {
			public int compare(String obj1, String obj2) {
				// 升序排序
				return obj1.compareTo(obj2);
			}
		});
		params.put("nonce_str", nostr);
		params.put("mch_billno", packets.getMch_billno());
		params.put("mch_id", MCID);
		params.put("wxappid", APPID);
		params.put("send_name", packets.getSend_name());
		params.put("re_openid", packets.getRe_openid());
		params.put("total_amount", packets.getTotal_amount());
		params.put("total_num", packets.getTotal_num());
		params.put("wishing", packets.getWishing());
		params.put("client_ip", LOCALIP);
		params.put("act_name", packets.getAct_name());
		params.put("remark", packets.getRemark());

		packets.setSign(MD5.createSign(params));// 签名

		XMLUtil xmlUtil = new XMLUtil();
		xmlUtil.xstream().alias("xml", Packets.class);
		String sendPacketsXml = xmlUtil.xstream().toXML(packets);
		System.out.println(sendPacketsXml);
		try {
			String returnCode = ClientCustomSSL.ssl("https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack",sendPacketsXml, MCID);
			                                         //https://api.mch.weixin.qq.com/mmpaymkttransfers/sendgroupredpack
			//System.out.println("返回的:" + returnCode);
			Map<String, String> re = XMLUtil.parseXml(returnCode);
			for (Map.Entry<String, String> entry : re.entrySet()) {
				if (entry.getKey().equals("return_msg")) {
					System.out.println( entry.getKey()+":"+entry.getValue());
					if (entry.getValue().equals("发放成功.")) {
						reCode = true;
					}
				}
			}
		} catch (Exception e) {
			System.out.println("发红包出错了");
		}
		return reCode;
	}
public class ClientCustomSSL {

    /**
     * 发送请求
     * */
    public static String ssl(String url,String data,String mchId){
        StringBuffer message = new StringBuffer();
        try {
            //String mchId = Global.getConfig("MCHId");
            KeyStore keyStore  = KeyStore.getInstance("PKCS12");
            String certFilePath = "D:"+File.separator+"cert"+File.separator+"apiclient_cert.p12";
            // linux下
           /* if ("/".equals(File.separator)) {
                certFilePath = "//usr//local//certs//apiclient_cert.p12";
            }*/
            FileInputStream instream = new FileInputStream(new File(certFilePath));
            keyStore.load(instream, mchId.toCharArray());
            SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, mchId.toCharArray()).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
            CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
            HttpPost httpost = new HttpPost(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"));
           // System.out.println("executing request" + httpost.getRequestLine());
            CloseableHttpResponse response = httpclient.execute(httpost);
            try {
                HttpEntity entity = response.getEntity();
                //System.out.println("----------------------------------------");
               // System.out.println(response.getStatusLine());
                if (entity != null) {
                    //System.out.println("Response content length: " + entity.getContentLength());
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent(),"UTF-8"));
                    String text;
                    while ((text = bufferedReader.readLine()) != null) {
                        message.append(text);
                    }
                }
                EntityUtils.consume(entity);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                response.close();
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        } 
        return message.toString();
    }

}

猜你喜欢

转载自blog.csdn.net/weixin_35790330/article/details/66972400