微信企业号开发:获取AccessToken

  微信企业号开发,需要调用微信企业号的相关接口,则必须使用AccessToken,但AccessToken需要corpid,corpsecret两个参数调用相关接口才能获取。

而且每一个接口都有一定的次数限制,当然获取AccessToken的接口也有这个限制。每一个AccessToken的有效期为7200秒,也就是两个小时,在有效期内调用接口,则自动续期。因此建议在获取到AccessToken后,保存在在某一个地方,等到快过期时在重新获取。其实AccessToken有点类似于web程序中的session,这个有效期7200秒相当于session的有效期,调用接口,则自动续期,就相当于web程序中用户登陆后,和服务端有交互,session的有效期自然延长了。


核心代码AccessTokenInfo类:

public class AccessTokenInfo
    {
        /// <summary>
        /// access_token
        /// </summary>
       public string access_token { get; set; }

        /// <summary>
        /// 凭证有效时间,单位:秒 
        /// </summary>
       public long expires_in { get; set; }

        /// <summary>
        /// 获取时间
        /// </summary>
        public DateTime GetTime { get; set; }
    }

BLLAccessToken类

    /// <summary>
    /// 获取企业登陆access_token
    /// </summary>
   public static class BLLAccessToken
    {
       static AccessTokenInfo TokenInfo = null;     
       public static string GetAccessToken()
       {
            string AccessToken = "";
           DateTime now=DateTime.Now;
           if (TokenInfo == null)  //首次获取
           {
               TokenInfo = UpDateAccessToken();
           }
           else
           {
               if (TokenInfo.GetTime.AddSeconds(TokenInfo.expires_in - 30) < now) //提前30秒重新获取
               {
                   TokenInfo = UpDateAccessToken();
               }
           }
           AccessToken = TokenInfo.access_token;
           return AccessToken;
       }
       private static AccessTokenInfo UpDateAccessToken()
       {
           string CorpId = AppIdInfo.GetCorpId();//corpid
           string Secret = AppIdInfo.GetSecret(); //corpsecret
           AccessTokenInfo info = new AccessTokenInfo();
           WebUtils ut = new WebUtils();
           /// https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=wxb7f1db8fd6aa9d68&corpsecret=aoxZ7D5-SgLRUbKY2fwQykW36RqxoIdNIn1pIiGy9iSdXgMHwQCzUsniQVAsBCTt
           string urlFormat = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={0}&corpsecret={1}";
           var url = string.Format(urlFormat, CorpId, Secret);
           string temp = ut.DoGet(url);         
           try
           {
               AccessTokenInfo tempAccessTokenjson = Tools.JsonStringToObj<AccessTokenInfo>(temp);
               info.access_token = tempAccessTokenjson.access_token;
               info.expires_in = tempAccessTokenjson.expires_in;
               info.GetTime = DateTime.Now;              
           }
           catch(Exception ex)
           {
               LogInfo.Error("获取AccessToken异常", ex);
           }
           return info;
       }

    }


微信企业号开发:常用的参数

微信企业号开发:corpsecret到底在哪块呢?

获取AccessToken官方文档



  


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
希垦园区项目。。企业微信微信企业public class Util{ private static final String UPLOAD_URL = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE"; public static String uploadFile(String filePath, String accessToken, String type) throws Exception{ File file = new File(filePath); if(!file.exists() || !file.isFile()) { throw new IOException("文件不存在!"); } String url = UPLOAD_URL.replace("ACCESS_TOKEN", accessToken).replace("TYPE", type); URL urlObj = new URL(url); //连接 HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection(); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); //请求头 conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Charset", "UTF-8"); //conn.setRequestProperty("Content-Type","multipart/form-data;"); //设置边界 String BOUNDARY = "----------" + System.currentTimeMillis(); conn.setRequestProperty("Content-Type","multipart/form-data;boundary="+BOUNDARY); StringBuilder sb = new StringBuilder(); sb.append("--"); sb.append(BOUNDARY); sb.append("\r\n"); sb.append("Content-Disposition:form-data;name=\"file\";filename=\""+file.getName()+"\"\r\n"); sb.append("Content-Type:application/octet-stream\r\n\r\n"); byte[] head = sb.toString().getBytes("utf-8"); //输出流 OutputStream out = new DataOutputStream(conn.getOutputStream()); out.write(head); //文件正文部分 DataInputStream in = new DataInputStream(new FileInputStream(file)); int bytes = 0; byte[] bufferOut = new byte[1024]; while((bytes = in.read(bufferOut))!=-1) { out.write(bufferOut,0,bytes); } in.close(); //结尾 byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8"); out.write(foot); out.flush(); out.close(); //获取响应 StringBuffer buffer = new StringBuffer(); BufferedReader reader = null; String result = null; reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = null; while((line = reader.readLine()) != null) { buffer.append(line); } if(result == null) { result = buffer.toString(); } reader.close();

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值