您的位置:首页 > 移动开发 > 微信开发

(Java)jfinal 实现微信现金红包发送,欢迎各种软件业务订制开发合作

2017-10-13 13:57 711 查看
/**

 * 

 */

package com.laoyao.SendRedPack;

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

import java.io.InputStream;

import java.security.KeyManagementException;

import java.security.KeyStore;

import java.security.KeyStoreException;

import java.security.NoSuchAlgorithmException;

import java.security.UnrecoverableKeyException;

import java.security.cert.CertificateException;

import java.text.SimpleDateFormat;

import java.util.ArrayList;

import java.util.Collections;

import java.util.Date;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

import java.util.UUID;

import javax.net.ssl.SSLContext;

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.entity.StringEntity;

import org.apache.http.impl.client.CloseableHttpClient;

import org.apache.http.impl.client.HttpClients;

import org.apache.http.ssl.SSLContexts;

import org.apache.http.util.EntityUtils;

import org.dom4j.Document;

import org.dom4j.DocumentException;

import org.dom4j.Element;

import org.dom4j.io.SAXReader;

import com.jfinal.kit.PropKit;

import com.laoyao.util.MessageUtil;

import com.laoyao.util.abc;

/**

 *类描述:

 * 

 * @author: laoyao

 *@date: 日期:2016-12-22 时间:下午05:03:55

 *@version 1.0

 */

public class RedPackUtil {
/**
* 生成6位或10位随机数 param codeLength(多少位)

* @return
*/
private static String createCode(int codeLength) {
String code = "";
for (int i = 0; i < codeLength; i++) {
code += (int) (Math.random() * 9);
}
return code;
}

private static boolean isValidChar(char ch) {
if ((ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z')
|| (ch >= 'a' && ch <= 'z'))
return true;
if ((ch >= 0x4e00 && ch <= 0x7fff) || (ch >= 0x8000 && ch <= 0x952f))
return true;// 简体中文汉字编码
return false;
}

/**
* 除去数组中的空值和签名参数

* @param sArray
*            签名参数组
* @return 去掉空值与签名参数后的新签名参数组
*/
public static Map<String, String> paraFilter(Map<String, String> sArray) {

Map<String, String> result = new HashMap<String, String>();

if (sArray == null || sArray.size() <= 0) {
return result;
}

for (String key : sArray.keySet()) {
String value = sArray.get(key);
if (value == null || value.equals("")
|| key.equalsIgnoreCase("sign")
|| key.equalsIgnoreCase("sign_type")) {
continue;
}
result.put(key, value);
}

return result;
}

/**
* 把数组所有元素排序,并按照“参数=参数值”的模式用“&”字符拼接成字符串

* @param params
*            需要排序并参与字符拼接的参数组
* @return 拼接后字符串
*/
public static String createLinkString(Map<String, String> params) {

List<String> keys = new ArrayList<String>(params.keySet());
Collections.sort(keys);
String prestr = "";

for (int i = 0; i < keys.size(); i++) {
String key = keys.get(i);
String value = params.get(key);

if (i == keys.size() - 1) {// 拼接时,不包括最后一个&字符
prestr = prestr + key + "=" + value;
} else {
prestr = prestr + key + "=" + value + "&";
}
}

return prestr;
}

/**
* 发送现金红包

* @throws KeyStoreException
* @throws IOException
* @throws CertificateException
* @throws NoSuchAlgorithmException
* @throws UnrecoverableKeyException
* @throws KeyManagementException
* @throws DocumentException
*/
public static String sendRedPack(String openid,String totalAmount) throws KeyStoreException,
NoSuchAlgorithmException, CertificateException, IOException,
KeyManagementException, UnrecoverableKeyException,
DocumentException {
// 获取uuid作为随机字符串
String nonceStr = UUID.randomUUID().toString().trim().replaceAll("-","");
String today = new SimpleDateFormat("yyyyMMdd").format(new Date());
String code = createCode(10);
String mch_id =PropKit.get("mch_id").toString().trim();//商户号
String appid =PropKit.get("appid").toString().trim();
openid = "o2lQKwb3QGVLS1OLJzlXdvYkTbvg"; // 发送给指定微信用户的openid
SendRedPackBean sendRedPackPo = new SendRedPackBean();
totalAmount = "100";
sendRedPackPo.setNonce_str(nonceStr);
sendRedPackPo.setMch_billno(mch_id + today + code);
sendRedPackPo.setMch_id(mch_id);
sendRedPackPo.setWxappid(appid);
sendRedPackPo.setNick_name("aaa");
sendRedPackPo.setSend_name(PropKit.get("pay_name").toString().trim());
sendRedPackPo.setRe_openid(openid);
sendRedPackPo.setTotal_amount(totalAmount);
sendRedPackPo.setMin_value(totalAmount);
sendRedPackPo.setMax_value(totalAmount);
sendRedPackPo.setTotal_num("1");
sendRedPackPo.setWishing("老妖分享微信红包推送!欢迎各种软件开发业务合作:237405542");
sendRedPackPo.setClient_ip("192.255.1.123"); // IP
sendRedPackPo.setAct_name("欢迎各种软件开发业务合作:237405542");
sendRedPackPo.setRemark("快来推广抢红包!");

// 把请求参数打包成数组
Map<String, String> sParaTemp = new HashMap<String, String>();
sParaTemp.put("nonce_str", sendRedPackPo.getNonce_str());
sParaTemp.put("mch_billno", sendRedPackPo.getMch_billno());
sParaTemp.put("mch_id", sendRedPackPo.getMch_id());
sParaTemp.put("wxappid", sendRedPackPo.getWxappid());
sParaTemp.put("nick_name", sendRedPackPo.getNick_name());
sParaTemp.put("send_name", sendRedPackPo.getSend_name());
sParaTemp.put("re_openid", sendRedPackPo.getRe_openid());
sParaTemp.put("total_amount", sendRedPackPo.getTotal_amount());
sParaTemp.put("min_value", sendRedPackPo.getMin_value());
sParaTemp.put("max_value", sendRedPackPo.getMax_value());
sParaTemp.put("total_num", sendRedPackPo.getTotal_num());
sParaTemp.put("wishing", sendRedPackPo.getWishing());
sParaTemp.put("client_ip", sendRedPackPo.getClient_ip());
sParaTemp.put("act_name", sendRedPackPo.getAct_name());
sParaTemp.put("remark", sendRedPackPo.getRemark());

// 除去数组中的空值和签名参数
Map<String, String> sPara = paraFilter(sParaTemp);
String prestr = createLinkString(sPara); // 把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串
String key = "&key="+PropKit.get("apiKey").toString().trim(); // 商户支付密钥
String mysign = MD5.sign(prestr, key, "utf-8").toUpperCase();
sendRedPackPo.setSign(mysign);
String respXml = MessageUtil.messageToXml(sendRedPackPo);
// 打印respXml发现,得到的xml中有“__”不对,应该替换成“_”
respXml = respXml.replace("__", "_");
// 将解析结果存储在HashMap中
Map<String, String> map = new HashMap<String, String>();
KeyStore keyStore = KeyStore.getInstance("PKCS12");
FileInputStream instream = new FileInputStream(new File(
"C:/cert/apiclient_cert.p12")); // 此处为证书所放的绝对路径
try {
keyStore.load(instream, mch_id.toCharArray());
} finally {
instream.close();
}
// Trust own CA and all self-signed certs
SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore,
mch_id.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 httpPost = new HttpPost(
"https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack");
StringEntity reqEntity = new StringEntity(respXml, "utf-8");
// 设置类型
reqEntity.setContentType("application/x-www-form-urlencoded");
httpPost.setEntity(reqEntity);
System.out.println("executing request" + httpPost.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httpPost);
try {
HttpEntity entity = response.getEntity();
System.out.println(response.getStatusLine());
if (entity != null) {
// 从request中取得输入流
InputStream inputStream = entity.getContent();
// 读取输入流
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());
// 释放资源
inputStream.close();
inputStream = null;
}
EntityUtils.consume(entity);
} finally {
response.close();
}
} finally {
httpclient.close();
}
// 返回状态码
String return_code = map.get("return_code");

abc.log.info(return_code);
// 返回信息
String return_msg = map.get("return_msg");
abc.log.info(return_msg);
// 业务结果
String result_code = map.get("result_code");
// 错误代码
String err_code = map.get("err_code");
// 错误代码描述
String err_code_des = map.get("err_code_des");
//System.out.println(err_code+err_code_des );
return return_code;
}

public static void main(String[] args) throws KeyManagementException, UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, DocumentException {
PropKit.use("a_little_config.txt");
sendRedPack("o2lQKwb3QGVLS1OLJzlXdvYkTbvg","100");
}
}

/**

 * 

 */package com.laoyao.SendRedPack;

import java.io.UnsupportedEncodingException;

import org.apache.commons.codec.digest.DigestUtils;

/**

 *类描述:

 *@author: laoyao

 *@date: 日期:2016-12-22 时间:下午05:19:13

 *@version 1.0

 */

public class MD5 {

    /**

     * 签名字符串

     * @param text 需要签名的字符串

     * @param key 密钥

     * @param input_charset 编码格式

     * @return 签名结果

     */

    public static String sign(String text, String key, String input_charset) {

    text = text + key;

        return DigestUtils.md5Hex(getContentBytes(text, input_charset));

    }

    

    /**

     * 签名字符串

     * @param text 需要签名的字符串

     * @param sign 签名结果

     * @param key 密钥

     * @param input_charset 编码格式

     * @return 签名结果

     */

    public static boolean verify(String text, String sign, String key, String input_charset) {

    text = text + key;

    String mysign = DigestUtils.md5Hex(getContentBytes(text, input_charset));

    if(mysign.equals(sign)) {

    return true;

    }

    else {

    return false;

    }

    }

    /**

     * @param content

     * @param charset

     * @return

     * @throws SignatureException

     * @throws UnsupportedEncodingException 

     */

    private static byte[] getContentBytes(String content, String charset) {

        if (charset == null || "".equals(charset)) {

            return content.getBytes();

        }

        try {

            return content.getBytes(charset);

        } catch (UnsupportedEncodingException e) {

            throw new RuntimeException("MD5签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + charset);

        }

    }

}

/**

 * 

 */

package com.laoyao.SendRedPack;

/**

 *类描述:

 * 

 * @author: laoyao

 *@date: 日期:2016-12-22 时间:下午04:47:51

 *@version 1.0

 */

public class SendRedPackBean {
private String nonce_str;
private String sign;
private String mch_billno;
private String mch_id;
private String sub_mch_id;
private String wxappid;
private String nick_name;
private String send_name;
private String re_openid;
private String total_amount;
private String min_value;
private String max_value;
private String total_num;
private String wishing;
private String client_ip;
private String act_name;
private String remark;
private String logo_imgurl;
private String share_content;
private String share_url;
private String share_imgurl;

public String getNonce_str() {
return nonce_str;
}
public void setNonce_str(String nonceStr) {
nonce_str = nonceStr;
}
public String getSign() {
return sign;
}
public void setSign(String sign) {
this.sign = sign;
}
public String getMch_billno() {
return mch_billno;
}
public void setMch_billno(String mchBillno) {
mch_billno = mchBillno;
}
public String getMch_id() {
return mch_id;
}
public void setMch_id(String mchId) {
mch_id = mchId;
}
public String getSub_mch_id() {
return sub_mch_id;
}
public void setSub_mch_id(String subMchId) {
sub_mch_id = subMchId;
}
public String getWxappid() {
return wxappid;
}
public void setWxappid(String wxappid) {
this.wxappid = wxappid;
}
public String getNick_name() {
return nick_name;
}
public void setNick_name(String nickName) {
nick_name = nickName;
}
public String getSend_name() {
return send_name;
}
public void setSend_name(String sendName) {
send_name = sendName;
}
public String getRe_openid() {
return re_openid;
}
public void setRe_openid(String reOpenid) {
re_openid = reOpenid;
}
public String getTotal_amount() {
return total_amount;
}
public void setTotal_amount(String totalAmount) {
total_amount = totalAmount;
}
public String getMin_value() {
return min_value;
}
public void setMin_value(String minValue) {
min_value = minValue;
}
public String getMax_value() {
return max_value;
}
public void setMax_value(String maxValue) {
max_value = maxValue;
}
public String getTotal_num() {
return total_num;
}
public void setTotal_num(String totalNum) {
total_num = totalNum;
}
public String getWishing() {
return wishing;
}
public void setWishing(String wishing) {
this.wishing = wishing;
}
public String getClient_ip() {
return client_ip;
}
public void setClient_ip(String clientIp) {
client_ip = clientIp;
}
public String getAct_name() {
return act_name;
}
public void setAct_name(String actName) {
act_name = actName;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getLogo_imgurl() {
return logo_imgurl;
}
public void setLogo_imgurl(String logoImgurl) {
logo_imgurl = logoImgurl;
}
public String getShare_content() {
return share_content;
}
public void setShare_content(String shareContent) {
share_content = shareContent;
}
public String getShare_url() {
return share_url;
}
public void setShare_url(String shareUrl) {
share_url = shareUrl;
}
public String getShare_imgurl() {
return share_imgurl;
}
public void setShare_imgurl(String shareImgurl) {
share_imgurl = shareImgurl;
}

}

/**

 * 

 */package com.laoyao.SendRedPack;

import java.io.UnsupportedEncodingException;

import java.net.InetAddress;

import org.apache.commons.codec.digest.DigestUtils;

/**

 *类描述:

 *@author: laoyao

 *@date: 日期:2016-12-22 时间:下午05:16:41

 *@version 1.0

 */

public class UUIDHexGenerator {

private String sep = "";

private static final int IP;

private static short counter = (short) 0;

private static final int JVM = (int) (System.currentTimeMillis() >>> 8);

private static UUIDHexGenerator uuidgen = new UUIDHexGenerator();

static {
int ipadd;
try {
ipadd = toInt(InetAddress.getLocalHost().getAddress());
} catch (Exception e) {
ipadd = 0;
}
IP = ipadd;
}

public static UUIDHexGenerator getInstance() {
return uuidgen;
}

public static int toInt(byte[] bytes) {
int result = 0;
for (int i = 0; i < 4; i++) {
result = (result << 8) - Byte.MIN_VALUE + (int) bytes[i];
}
return result;
}

protected String format(int intval) {
String formatted = Integer.toHexString(intval);
StringBuffer buf = new StringBuffer("00000000");
buf.replace(8 - formatted.length(), 8, formatted);
return buf.toString();
}

protected String format(short shortval) {
String formatted = Integer.toHexString(shortval);
StringBuffer buf = new StringBuffer("0000");
buf.replace(4 - formatted.length(), 4, formatted);
return buf.toString();
}

protected int getJVM() {
return JVM;
}

protected synchronized short getCount() {
if (counter < 0) {
counter = 0;
}
return counter++;
}

protected int getIP() {
return IP;
}

protected short getHiTime() {
return (short) (System.currentTimeMillis() >>> 32);
}

protected int getLoTime() {
return (int) System.currentTimeMillis();
}

public String generate() {
return new StringBuffer(36)
.append(format(getIP()))
.append(sep)
.append(format(getJVM()))
.append(sep)
.append(format(getHiTime()))
.append(sep)
.append(format(getLoTime()))
.append(sep)
.append(format(getCount()))
.toString();
}

/**
* @param args
*/
public static void main(String[] args) {
String id;
UUIDHexGenerator uuid = UUIDHexGenerator.getInstance();
 
for(int i = 0;i<100;i++)
{
id = uuid.generate();
 
}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息