zoukankan      html  css  js  c++  java
  • 微信网页授权

    先附上微信公众平台的相关链接:
    微信公众平台:https://mp.weixin.qq.com/
    微信公众平台开发文档:https://mp.weixin.qq.com/wiki
     
    说明:
    1.回调域
    开发者需要先到公众平台官网中的开发者中心页配置授权回调域名。
     
    2.授权scope

    以snsapi_base为scope发起的网页授权,是用来获取进入页面的用户的openid的,并且是静默授权并自动跳转到回调页的。用户感知的就是直接进入了回调页。

    以snsapi_userinfo为scope发起的网页授权,是用来获取用户的基本信息的。但这种授权需要用户手动同意,并且由于用户同意过,所以无须关注,就可在授权后获取该用户的基本信息。(见下图)

     

    流程:

    1、引导用户进入授权页面同意授权,获取code 

    2、通过code换取网页授权access_token(与基础支持中的access_token不同) 

    3、如果需要,开发者可以刷新网页授权access_token,避免过期 

    4、通过网页授权access_token和openid获取用户基本信息(支持UnionID机制) 

     
    代码(C#):
     public static string appid = ConfigurationManager.AppSettings["WeiXinAppID"].ToString();
     public static string secret = ConfigurationManager.AppSettings["WeiXinAppSecret"].ToString();
     public static string domain = ConfigurationManager.AppSettings["WeiXinDomain"].ToString();
     public static string GetMethod(string url)
            {
                string result = string.Empty;
                try
                {
                    UTF8Encoding encoding = new UTF8Encoding();
                    HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
                    myRequest.Method = "GET";
                    HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
                    if (myResponse.StatusCode == HttpStatusCode.OK)
                    {
                        StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
                        result = reader.ReadToEnd();
                    }
                }
                catch
                {
                    result = string.Empty;
                }
                return result;
            }
     public static string GetCodeUrl(string callback, string scope = "snsapi_base")
            {
                return string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}{2}&response_type=code&scope={3}&state=state#wechat_redirect", appid, domain, callback, scope);
            }
     public static string GetOpenID(string code)
            {
                string openid = string.Empty;
                string apiUrl = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", appid, secret, code);
                string result = GetMethod(apiUrl);
                if (!string.IsNullOrEmpty(result))
                {
                    JObject jo = (JObject)JsonConvert.DeserializeObject(result);
                    openid = jo["openid"].ToString();
                }
                return openid;
            }
  • 相关阅读:
    Java-数据字符串进行四舍五入
    Git本地安装及汉化
    Navicat安装教程
    Jdk+maven安装
    系列文章
    @PathVariable
    feign组件
    Lombok
    常见Jar包的用途
    iOS archive(归档)的总结
  • 原文地址:https://www.cnblogs.com/talentzemin/p/5462125.html
Copyright © 2011-2022 走看看