zoukankan      html  css  js  c++  java
  • .Net实现微信公众平台开发接口(二) 之 “获取access_token”

    access_token是公众号的全局唯一票据,公众号调用各接口时都需使用access_token。

    接口调用请求说明

    http请求方式: GET
    https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET

    参数说明

    参数是否必须说明
    grant_type 获取access_token填写client_credential
    appid 第三方用户唯一凭证
    secret 第三方用户唯一凭证密钥,即appsecret

    返回说明

    正常情况下,微信会返回下述JSON数据包给公众号:

    {"access_token":"ACCESS_TOKEN","expires_in":7200}
    
    参数说明
    access_token 获取到的凭证
    expires_in 凭证有效时间,单位:秒


    错误时微信会返回错误码等信息,JSON数据包示例如下(该示例为AppID无效错误):

    {"errcode":40013,"errmsg":"invalid appid"}

    具体实现的代码如下:
    //获取微信凭证access_token的接口
            public static string getAccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}";
    
            #region 获取微信凭证
            public string GetAccessToken(string wechat_id)
            {
                string accessToken = "";
                //获取配置信息Datatable
                DataTable dtwecaht = wechatdal.GetList("wechat_id='" + wechat_id + "'").Tables[0];
    
                if (dtwecaht.Rows.Count > 0)
                {
                    string respText = "";
                    //获取appid和appsercret
                    string wechat_appid = dtwecaht.Rows[0]["wechat_appid"].ToString();
                    string wechat_appsecret = dtwecaht.Rows[0]["wechat_appsecret"].ToString();
                    //获取josn数据
                    string url = string.Format(getAccessTokenUrl, wechat_appid, wechat_appsecret);
    
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    
                    using (Stream resStream = response.GetResponseStream())
                    {
                        StreamReader reader = new StreamReader(resStream, Encoding.Default);
                        respText = reader.ReadToEnd();
                        resStream.Close();
                    }
                    JavaScriptSerializer Jss = new JavaScriptSerializer();
                    Dictionary<string, object> respDic = (Dictionary<string, object>)Jss.DeserializeObject(respText);
                    //通过键access_token获取值
                    accessToken = respDic["access_token"].ToString();
                }
    
                return accessToken;
            }
            #endregion 获取微信凭证

    后面调用接口的时候,就直接调用这个方法获取access_token即可。

  • 相关阅读:
    羊皮卷的故事第三章
    羊皮卷的故事第五章
    羊皮卷的故事第八章羊皮卷之一
    羊皮卷的故事第十一章羊皮卷之四
    羊皮卷的故事第四章
    羊皮卷的故事第十章羊皮卷之三
    羊皮卷的故事第九章羊皮卷之二
    羊皮卷的故事第十二章羊皮卷之五
    POJ3264 Balanced Lineup RMQ
    HDUPattern and Text 枚举
  • 原文地址:https://www.cnblogs.com/shuang121/p/4009321.html
Copyright © 2011-2022 走看看