3,143
社区成员
发帖
与我相关
我的任务
分享
public String sendRedPack(String fromUserName, int amount) {
SortedMap<String, Object> map = new TreeMap<String, Object>();
map.put("nonce_str", WeixinUtil.createNoncestr(32)); // 随机字符串,不长于32位
// 商户订单号(每个订单号必须唯一)。组成:mch_id+yyyymmdd+10位一天内不能重复的数字。接口根据商户订单号支持重入,如出现超时可再调用。
map.put("mch_billno", WeixinUtil.getMchBillNo());
map.put("mch_id", Constants.MCH_ID); // 微信支付分配的商户号
map.put("wxappid", Constants.getAppId()); // 微信分配的公众账号ID(企业号corpid即为此appId)
map.put("send_name", "CanguangMedia"); // 商户名称, 红包发送者名称
map.put("re_openid", fromUserName); // "oy-yfuAMQ4tynMP98bOdMmuS4Bk4"; // 接受红包的用户.用户在wxappid下的openid
map.put("total_amount", amount + ""); // 付款金额,单位分
map.put("total_num", "1"); // 红包发放总人数
map.put("wishing", "ThankYou"); // 红包祝福语
map.put("client_ip", "xxx.xx.xx.xxx"); // 调用接口的机器Ip地址
map.put("act_name", "TestRedPackage"); // 活动名称
map.put("remark", "ThankYou2"); // 备注信息
String sign = WxPayHelper.createSign("UTF-8", map); // 签名
map.put("sign", sign);
String xmlParam = WeixinUtil.mapToXml(map);
log.info("sendRedPack, 入参xmlParam=" + xmlParam);
String result = "";
try {
result = MoneyUtils.doSendMoney(Constants.SEND_REDPACK_URL, fromUserName, xmlParam);
Map resultMap = XmlUtil.xml2map(result);
if("FAIL".equals(resultMap.get("result_code"))) {
result = (String) resultMap.get("error_code_des");
}
else {
result = "感谢您的支持,红包已发放到您的微信上,请查收!";
}
log.info("sendRedPack获取结果:" + result);
} catch (Exception e) {
log.error("sendRedPack发生异常:" + e.getMessage(), e);
System.out.println("sendRedPack发生异常:" + e.getMessage());
}
return result;
}
/**
* 生成随机数
* @param length 要生成的长度
* @return
*/
public static String createNoncestr(int length) {
String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
String res = "";
for (int i = 0; i < length; i++) {
res += chars.charAt(rd.nextInt(chars.length() - 1));
}
return res;
}
/**
* 创建商户订单号
* @return
*/
public static String getMchBillNo() {
String mchBillNo = "";
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
SimpleDateFormat sdf2 = new SimpleDateFormat("HHmmssSSS");
Date now = new Date();
mchBillNo = Constants.MCH_ID + sdf.format(now) + sdf2.format(now) + rd.nextInt(9);
return mchBillNo;
}
/**
* map转换成微信标准的xml格式
* @param map 微信入参map
* @return
*/
public static String mapToXml(SortedMap<String, Object> map) {
String xml = "<xml>";
Iterator<Entry<String, Object>> iter = map.entrySet().iterator();
while (iter.hasNext()) {
Entry<String, Object> entry = iter.next();
String key = entry.getKey();
Object val = entry.getValue();
xml += "<" + key + "><![CDATA[" + val + "]]></" + key + ">";
}
xml += "</xml>";
return xml;
}
/**
* 微信支付签名算法sign
* @param characterEncoding
* @param parameters
* @return
*/
public static String createSign(String characterEncoding, SortedMap<String, Object> parameters) {
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=" + Constants.API_KEY);
String sign = MD5Util.MD5(sb.toString()).toUpperCase();
log.info("signStr=" + sb.toString() + ", sign=" + sign);
// String sign = MD5Util.MD5Encode(sb.toString(), characterEncoding).toUpperCase();
return sign;
}
public static String doSendMoney(String url, String fromName, String data) throws Exception {
log.info("doSendMoney入参:url=" + url + ", fromName=" + fromName + ", data=" + data);
KeyStore keyStore = KeyStore.getInstance("PKCS12");
// FileInputStream instream = new FileInputStream(new File(Constants.KEYSTORE_FILE));//P12文件目录
InputStream instream = null;
try {
instream = MoneyUtils.class.getResourceAsStream("apiclient_cert.p12");
// instream = new FileInputStream(new File("apiclient_cert.p12"));//P12文件目录
} catch(Exception e) {
log.error("doSendMoney 00发生异常:" + e.getMessage(), e);
e.printStackTrace();
}
log.info("doSendMoney instream====>" + instream.toString());
try {
keyStore.load(instream, Constants.KEYSTORE_PASSWORD.toCharArray());//这里写密码..默认是你的MCHID
} catch (Exception e) {
e.printStackTrace();
log.error("doSendMoney 1发生异常:" + e.getMessage(), e);
}
finally {
instream.close();
}
// Trust own CA and all self-signed certs
SSLContext sslcontext = SSLContexts.custom()
.loadKeyMaterial(keyStore, Constants.KEYSTORE_PASSWORD.toCharArray())//这里也是写密码的
.build();
// Allow TLSv1 protocol only
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(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();
String jsonStr = toStringInfo(response.getEntity(),"UTF-8");
log.info("doSendMoney返回:jsonStr=" + jsonStr);
//微信返回的报文时GBK,直接使用httpcore解析乱码
// String jsonStr = EntityUtils.toString(response.getEntity(),"UTF-8");
EntityUtils.consume(entity);
return jsonStr;
} catch(Exception e) {
log.error("doSendMoney 发生异常:" + e.getMessage(), e);
return null;
} finally {
response.close();
}
} finally {
httpclient.close();
}
}