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

微信公众平台开发之获得ACCESSTOKEN .Net代码解析

程序员文章站 2023-12-14 18:10:10
如何认证成为开发者?请点击文章进行查看,成为了开发者之后微信平台会给您appid和secret,在订阅号中是没有的,所以因该申请一下服务号,有了accesstoken才能做...

如何认证成为开发者?请点击文章进行查看,成为了开发者之后微信平台会给您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<accesstoken> myaccesstoken = json.jsonstringtolist<accesstoken>(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;
     }
   }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

上一篇:

下一篇: