接口发放微信企业号红包

来源:互联网 发布:mac如何免费翻墙 编辑:程序博客网 时间:2024/05/16 11:45
微信接口红包这块就一个坑,我们在实际的开发中找了很多种办法 也看了N次 文档,最后我们通过以下步骤成功发送红包

1.保存用户在客户端授权信息。

2.后端通过企业号拿到用户所有的信息 保存到数据库中,注意一定要和每个用户的userid相同

3.用户申请提现时,查找数据库里面的userid获取到它本身的openid。

以下是关键代码:

发送红包代码

 1 public class AwardABonus { 2     public static String fun(String opid, int totalamount) { 3         String httpurl = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack"; 4         String noncestr = 随机字符串; 5         String mchid = 商户号; 6  7         SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS"); 8         String times = (df.format(new Date()) + (int) (Math.random() * 10.0D)) 9                 .toString();10         String mchbillno = mchid + times;11         String wxappid = "公众账号appid";12         String nickname = "";13         String key = "公众号key";14         String reopenid = opid;15         String sendname = "商户名称";16         int minvalue = 100;17         int maxvalue = 10000;18         int totalnum = 1;//付款金额 分为单位19         String wishing = "xxoo"; //红包名称20         String clientip = "";//IP地址21         String actname = "xxoo";//活动名称22         String remark = "xxoo";//备注23         String stringSignTemp = "act_name=" + actname + "&client_ip="24                 + clientip + "&max_value=" + maxvalue + "&mch_billno="25                 + mchbillno + "&mch_id=" + mchid + "&min_value=" + minvalue26                 + "&nick_name=" + nickname + "&nonce_str=" + noncestr27                 + "&re_openid=" + reopenid + "&remark=" + remark28                 + "&send_name=" + sendname + "&total_amount=" + totalamount29                 + "&total_num=" + totalnum + "&wishing=" + wishing30                 + "&wxappid=" + wxappid + "&key=" + key;31         String sign = MD5Tool.md5(stringSignTemp).toUpperCase();32 33         String pr1 = "<xml><act_name>" + actname + "</act_name>"34                 + "<nick_name>" + nickname + "</nick_name>" + "<client_ip>"35                 + clientip + "</client_ip>" + "<total_amount>" + totalamount36                 + "</total_amount>" + "<min_value>" + minvalue + "</min_value>"37                 + "<max_value>" + maxvalue + "</max_value>" + "<total_num>"38                 + totalnum + "</total_num>" + "<mch_billno>" + mchbillno39                 + "</mch_billno>" + "<mch_id>" + mchid + "</mch_id>"40                 + "<nonce_str>" + noncestr + "</nonce_str>" + "<re_openid>"41                 + reopenid + "</re_openid>" + "<remark>" + remark + "</remark>"42                 + "<send_name>" + sendname + "</send_name>" + "<wishing>"43                 + wishing + "</wishing>" + "<wxappid>" + wxappid + "</wxappid>"44                 + "<sign>" + sign + "</sign>" + "</xml>";45         InputStream in = null;46         StringBuilder sb = new StringBuilder();47         HttpEntity entity = null;48         try {49             File file = new File(PathKit.getWebRootPath()50                     + "\\cert\\apiclient_cert.p12");51             FileInputStream fileInputStream = new FileInputStream(file);52             KeyStore clientTrustKeyStore = KeyStore.getInstance("PKCS12");53             clientTrustKeyStore.load(fileInputStream, mchid.toCharArray());54             KeyManagerFactory kmf = KeyManagerFactory55                     .getInstance(KeyManagerFactory.getDefaultAlgorithm());56             kmf.init(clientTrustKeyStore, mchid.toCharArray());57             TrustManager[] tm = { new MyX509TrustManager() };58             SSLContext sslContext = SSLContext.getInstance("TLSv1");59             sslContext.init(kmf.getKeyManagers(), tm, new SecureRandom());60             SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(61                     sslContext);62             CloseableHttpClient httpclient = HttpClients.custom()63                     .setSSLSocketFactory(sslsf).build();64             HttpPost httppost = new HttpPost(httpurl);65             httppost.setEntity(new StringEntity(pr1, "utf-8"));66             System.out.println(EntityUtils.toString(httppost.getEntity()));67             CloseableHttpResponse response = httpclient.execute(httppost);68             entity = response.getEntity();69             in = entity.getContent();70             byte[] bytes = new byte[1024];71             int len = 0;72             while ((len = in.read(bytes)) != -1)73                 sb.append(new String(bytes, 0, len));74         } catch (Exception e) {75             e.printStackTrace();76 77             if (in != null)78                 try {79                     in.close();80                     EntityUtils.toString(entity);81                 } catch (IOException localIOException) {82                 } finally {83                 }84         } finally {85             if (in != null)86                 try {87                     in.close();88                     EntityUtils.toString(entity);89                 } catch (IOException localIOException1) {90                 } finally {91                 }92         }93         System.out.println(sb.toString());94         return sb.toString();95     }

通过企业号授权拿到AccessToken

//appID 企业号  public static String getAccessToken(String appID, String appScret) {    String setAccess_token = null;    String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" +       appID + "&secret=" + appScret;    try {      URL getUrl = new URL(url);      HttpURLConnection http = (HttpURLConnection)getUrl        .openConnection();      http.setRequestMethod("GET");      http.setRequestProperty("Content-Type",         "application/x-www-form-urlencoded");      http.setDoOutput(true);      http.setDoInput(true);      http.connect();      InputStream is = http.getInputStream();      int size = is.available();      byte[] b = new byte[size];      is.read(b);      String message = new String(b, "UTF-8");      JSONObject json = JSONObject.parseObject(message);      System.out.println(json);      setAccess_token = json.getString("access_token");      Integer setExpires_in = new Integer(json.getString("expires_in"));      System.out.println(setAccess_token);    } catch (MalformedURLException e) {      e.printStackTrace();    } catch (IOException e) {      e.printStackTrace();    }    return setAccess_token;  }}

获取公众号用户列表

    public static List<String> getAllWeiXinUser(String accessToken) {        List openIds = new ArrayList();        String action = "https://api.weixin.qq.com/cgi-bin/user/get?access_token="                + accessToken;        try {            URL urlGet = new URL(action);            HttpURLConnection http = (HttpURLConnection) urlGet                    .openConnection();            http.setRequestMethod("GET");            http.setRequestProperty("Content-Type",                    "application/x-www-form-urlencoded");            http.setDoOutput(true);            http.setDoInput(true);            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");            System.setProperty("sun.net.client.defaultReadTimeout", "30000");            http.connect();            InputStream is = http.getInputStream();            int size = is.available();            byte[] jsonBytes = new byte[size];            is.read(jsonBytes);            String result = new String(jsonBytes, "UTF-8");            JSONObject jsonObj = new JSONObject(result);            System.out.println("users" + jsonObj.get("data"));            JSONObject json1 = new JSONObject(jsonObj.get("data").toString());            System.out.println(json1.toString());            JSONArray json2 = new JSONArray(json1.get("openid").toString());            for (int i = 0; i < json2.length(); i++) {                openIds.add(i, json2.getString(i));            }        } catch (Exception e) {            e.printStackTrace();        }        return openIds;    }
原创粉丝点击