接口发放微信企业号红包

微信接口红包这块就一个坑,我们在实际的开发中找了很多种办法 也看了N次 文档,最后我们通过以下步骤成功发送红包

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

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

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

以下是关键代码:

发送红包代码

public class AwardABonus {
    public static String fun(String opid, int totalamount) {
        String httpurl = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";
        String noncestr = 随机字符串;
        String mchid = 商户号;

        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String times = (df.format(new Date()) + (int) (Math.random() * 10.0D))
                .toString();
        String mchbillno = mchid + times;
        String wxappid = "公众账号appid";
        String nickname = "";
        String key = "公众号key";
        String reopenid = opid;
        String sendname = "商户名称";
        int minvalue = 100;
        int maxvalue = 10000;
        int totalnum = 1;//付款金额 分为单位
        String wishing = "xxoo"; //红包名称
        String clientip = "";//IP地址
        String actname = "xxoo";//活动名称
        String remark = "xxoo";//备注
        String stringSignTemp = "act_name=" + actname + "&client_ip="
                + clientip + "&max_value=" + maxvalue + "&mch_billno="
                + mchbillno + "&mch_id=" + mchid + "&min_value=" + minvalue
                + "&nick_name=" + nickname + "&nonce_str=" + noncestr
                + "&re_openid=" + reopenid + "&remark=" + remark
                + "&send_name=" + sendname + "&total_amount=" + totalamount
                + "&total_num=" + totalnum + "&wishing=" + wishing
                + "&wxappid=" + wxappid + "&key=" + key;
        String sign = MD5Tool.md5(stringSignTemp).toUpperCase();

        String pr1 = "<xml><act_name>" + actname + "</act_name>"
                + "<nick_name>" + nickname + "</nick_name>" + "<client_ip>"
                + clientip + "</client_ip>" + "<total_amount>" + totalamount
                + "</total_amount>" + "<min_value>" + minvalue + "</min_value>"
                + "<max_value>" + maxvalue + "</max_value>" + "<total_num>"
                + totalnum + "</total_num>" + "<mch_billno>" + mchbillno
                + "</mch_billno>" + "<mch_id>" + mchid + "</mch_id>"
                + "<nonce_str>" + noncestr + "</nonce_str>" + "<re_openid>"
                + reopenid + "</re_openid>" + "<remark>" + remark + "</remark>"
                + "<send_name>" + sendname + "</send_name>" + "<wishing>"
                + wishing + "</wishing>" + "<wxappid>" + wxappid + "</wxappid>"
                + "<sign>" + sign + "</sign>" + "</xml>";
        InputStream in = null;
        StringBuilder sb = new StringBuilder();
        HttpEntity entity = null;
        try {
            File file = new File(PathKit.getWebRootPath()
                    + "\\cert\\apiclient_cert.p12");
            FileInputStream fileInputStream = new FileInputStream(file);
            KeyStore clientTrustKeyStore = KeyStore.getInstance("PKCS12");
            clientTrustKeyStore.load(fileInputStream, mchid.toCharArray());
            KeyManagerFactory kmf = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmf.init(clientTrustKeyStore, mchid.toCharArray());
            TrustManager[] tm = { new MyX509TrustManager() };
            SSLContext sslContext = SSLContext.getInstance("TLSv1");
            sslContext.init(kmf.getKeyManagers(), tm, new SecureRandom());
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                    sslContext);
            CloseableHttpClient httpclient = HttpClients.custom()
                    .setSSLSocketFactory(sslsf).build();
            HttpPost httppost = new HttpPost(httpurl);
            httppost.setEntity(new StringEntity(pr1, "utf-8"));
            System.out.println(EntityUtils.toString(httppost.getEntity()));
            CloseableHttpResponse response = httpclient.execute(httppost);
            entity = response.getEntity();
            in = entity.getContent();
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = in.read(bytes)) != -1)
                sb.append(new String(bytes, 0, len));
        } catch (Exception e) {
            e.printStackTrace();

            if (in != null)
                try {
                    in.close();
                    EntityUtils.toString(entity);
                } catch (IOException localIOException) {
                } finally {
                }
        } finally {
            if (in != null)
                try {
                    in.close();
                    EntityUtils.toString(entity);
                } catch (IOException localIOException1) {
                } finally {
                }
        }
        System.out.println(sb.toString());
        return sb.toString();
    }


通过企业号授权拿到AccessToken//appID 企业号  

//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;
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值