欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

微信公共服务平台开发(.Net 的实现)2-------获得ACCESSTOKEN

程序员文章站 2022-05-28 19:33:52
成为了开发者之后微信平台会给您appid和secret,在订阅号中是没有的,所以因该申请一下服务号 有了accesstoken才能做添加菜单,上传/下载图片等功能 private string g...

成为了开发者之后微信平台会给您appid和secret,在订阅号中是没有的,所以因该申请一下服务号

有了accesstoken才能做添加菜单,上传/下载图片等功能

private string gettoken()
     {

         // 也可以这样写:
         //return  getpage("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=你的appid&secret=你的secret", "");
       
         string res = "";
         httpwebrequest req = (httpwebrequest)httpwebrequest.create("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential
&appid=你的appid&secret=你的secret");
 req.method = "get";
         using (webresponse wr = req.getresponse())
         {
             httpwebresponse myresponse = (httpwebresponse)req.getresponse();


             streamreader reader = new streamreader(myresponse.getresponsestream(), encoding.utf8);


             string content = reader.readtoend();
   
             list myaccesstoken = json.jsonstringtolist(content);
             res = myaccesstoken[0].access_token;
 
         }


         return res;
     }
     public string getpage(string posturl, string postdata)
     {
         stream outstream = null;
         stream instream = null;
         streamreader sr = null;
         httpwebresponse response = null;
         httpwebrequest request = null;
         encoding encoding = encoding.utf8;
         byte[] data = encoding.getbytes(postdata);
         // 准备请求...
         try
         {
             // 设置参数
             request = webrequest.create(posturl) as httpwebrequest;
             cookiecontainer cookiecontainer = new cookiecontainer();
             request.cookiecontainer = cookiecontainer;
             request.allowautoredirect = true;
             request.method = "post";
             request.contenttype = "application/x-www-form-urlencoded";
             request.contentlength = data.length;
             outstream = request.getrequeststream();
             outstream.write(data, 0, data.length);
             outstream.close();
             //发送请求并获取相应回应数据
             response = request.getresponse() as httpwebresponse;
             //直到request.getresponse()程序才开始向目标网页发送post请求
             instream = response.getresponsestream();
             sr = new streamreader(instream, encoding);
             //返回结果网页(html)代码
             string content = sr.readtoend();
             string err = string.empty;
             return content;
         }
         catch (exception ex)
         {
             string err = ex.message;
             response.write(err);
             return string.empty;
         }
     }