企业微信获取JS-SDK并下载临时素材

前言

注意:
1.corpid是企业微信的ID, corpsecret是应用程序的;需要应用配置网页授权可信任域名,下载完文件后,把已下载的文件放置到域名根目录下(需要管理员权限,查看文档具体说明。)
2.小程序获取方法其实是一样的,只是地址不一样,可以看一下微信文档说明。

在这里插入图片描述
在这里插入图片描述

1.企业微信获取access_token
https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=corpid&corpsecret=corpsecret

/**
     * 企业微信access_token
     * @return
     */
    public static String getQyAccess_token() throws Exception {
        String nowtime = DateHelper.getNow();
        //小于半个小时直接返回之前的 qywx_accesstoken
        if(StringHelper.isNotEmpty(qywx_accesstoken) && DateHelper.getDateSecond(qywx_accesstokentime,nowtime)<1800){
            return qywx_accesstoken;
        }
        qywx_accesstokentime = nowtime;
        HttpURLConnection conn = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader bufferedReader = null;
        JSONObject jsonObject = null;
        try {
            String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid="+CORPID+"&corpsecret="+CORPSECRET;
            URL u = new URL(url);
            conn = (HttpURLConnection) u.openConnection();
            conn.setRequestMethod("GET");
            conn.connect();
            inputStreamReader = new InputStreamReader(conn.getInputStream(), "utf-8");
            bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            StringBuffer buffer = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            jsonObject = JSONObject.fromObject(buffer.toString());
            String access_token = jsonObject.getString("access_token");
            //System.out.println("----------------------Access_token---------------------------" + access_token);
            return access_token;
        } catch (Exception e) {
            System.out.println("----------------------Access_tokenError---------------------------" + jsonObject);
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
                if (inputStreamReader != null) {
                    inputStreamReader.close();
                }
                if (conn != null) {
                    conn.disconnect();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

2.获取jsticket
https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=access_token

/**
     * 获取jsticket的执行体
     *
     * @param access_token
     * @return
     */
    public static String getTicket(String access_token) throws Exception {
        String nowtime = DateHelper.getNow();
        //小于半个小时直接返回之前的 ticket
        if(StringHelper.isNotEmpty(ticket) && DateHelper.getDateSecond(ticket_time,nowtime)<1800){
            return ticket;
        }
        ticket_time = nowtime;
        HttpURLConnection conn = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader bufferedReader = null;
        JSONObject jsonObject = null;
        try {
            String getticket = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token="+access_token;
            String url = String.format(getticket, APPID, APPSECRET);
            URL u = new URL(url);
            conn = (HttpURLConnection) u.openConnection();
            conn.setRequestMethod("GET");
            conn.connect();
            inputStreamReader = new InputStreamReader(conn.getInputStream(), "utf-8");
            bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            StringBuffer buffer = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            jsonObject = JSONObject.fromObject(buffer.toString());
            String ticket = jsonObject.getString("ticket");
            System.out.println("----------------------ticket---------------------------" + ticket);
            return ticket;
        } catch (Exception e) {
            System.out.println("----------------------ticketError---------------------------" + jsonObject);
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
                if (inputStreamReader != null) {
                    inputStreamReader.close();
                }
                if (conn != null) {
                    conn.disconnect();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

3.获取前端jssdk页面配置需要用到的配置参数

/**
     * 前端jssdk页面配置需要用到的配置参数
     *
     * @param url
     * @param ticket
     * @return
     * @throws Exception
     */
    public static Map<String, String> getSignature(String url, String ticket,String appid) throws Exception {
        String noncestr = UUID.randomUUID().toString();
        String timestamp = Long.toString(System.currentTimeMillis() / 1000);
        // 注意这里参数名必须全部小写,且必须有序
        String string1 = "jsapi_ticket=" + ticket +
                "&noncestr=" + noncestr +
                "&timestamp=" + timestamp +
                "&url=" + url;
        MessageDigest crypt = MessageDigest.getInstance("SHA-1");
        crypt.reset();
        crypt.update(string1.getBytes("UTF-8"));
        String signature = byteToHex(crypt.digest());
        HashMap<String, String> jssdk = new HashMap<String, String>();
        jssdk.put("appId", appid);
        jssdk.put("timestamp", timestamp);
        jssdk.put("nonceStr", noncestr);
        jssdk.put("signature", signature);
        return jssdk;
    }

    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

4.获取微信临时素材
https://qyapi.weixin.qq.com/cgi-bin/media/get?access_token=access_token&media_id=mediaId

/**
     * 获取微信临时素材
     *
     * @param mediaId
     * @return
     */
    public static InputStream downloadMedia(String access_token, String mediaId) {
        URLConnection conn = null;
        InputStream is = null;
        BufferedInputStream bis = null;
        String fileSize = "";
        try {
            String requestUrl = "https://qyapi.weixin.qq.com/cgi-bin/media/get?access_token="+access_token+"&media_id="+mediaId;
            URL realUrl = new URL(requestUrl);
            conn = realUrl.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Content-Type",  "application/x-www-form-urlencoded; charset=utf-8");
            conn.setRequestProperty("Accept-Charset", "UTF-8"); //
            conn.setRequestProperty("contentType", "utf-8");

            //获取网络流的头部信息
            Map<String, List<String>> maps = conn.getHeaderFields();
            for (String key : maps.keySet()) {
                System.out.println(key + "---> " + maps.get(key));
                if ("Content-Length".equals(key)) {
                    fileSize = maps.get(key).get(0);//获取文件大小
                }
            }
            // 获取网络流的内容
            bis = new BufferedInputStream(conn.getInputStream());
            byte[] data = getByte(bis); // 获取当前条目的字节数组
            is = new ByteArrayInputStream(data); // 把当前条目的字节数据转换成Inputstream流
            return is ;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 获取条目byte[]字节
     *
     * @param is
     * @return
     */
    public static byte[] getByte(InputStream is) {
        try {
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            byte[] temp = new byte[1024];
            byte[] buf = null;
            int length = 0;
            while ((length = is.read(temp, 0, 1024)) != -1) {
                bout.write(temp, 0, length);
            }
            buf = bout.toByteArray();
            bout.close();
            return buf;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

5. 欢迎留言 https://blog.csdn.net/jia814583973/

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
企业微信H5 JS-SDK是一个用于开发企业微信H5应用的SDK工具,可以实现企业微信的认证、JSAPI调用等功能。下面是企业微信H5 JS-SDK的调试方法: 1. 在企业微信开发者后台创建应用,并获取到应用的CorpID和Secret。 2. 在需要调试的H5页面中引入企业微信H5 JS-SDKSDK文件,例如: ```html <script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script> ``` 3. 在页面的JS代码中,初始化企业微信H5 JS-SDK,并配置需要使用的接口,例如: ```javascript wx.config({ beta: true, debug: true, appId: 'CorpID', timestamp: '', nonceStr: '', signature: '', jsApiList: ['checkJsApi', 'chooseImage', 'previewImage'] }); ``` 需要将上述代码中的CorpID替换为自己应用的CorpID,timestamp、nonceStr和signature需要根据后端生成的签名参数进行获取。 4. 配置完成后,可以通过调用企业微信H5 JS-SDK提供的接口进行调试。例如,调用企业微信H5 JS-SDK中的chooseImage接口选择图片: ```javascript wx.chooseImage({ count: 1, success: function (res) { var localIds = res.localIds; alert(localIds); // 显示选择的图片的本地ID列表 } }); ``` 5. 在手机上打开需要调试的H5页面,使用企业微信扫描二维码或直接打开链接,即可进行调试。 通过上述步骤,就可以进行企业微信H5 JS-SDK的调试,通过调试可以验证SDK的功能是否正常,同时可以根据实际需求进行业务逻辑的开发和调试。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值