Пример #1
0
        public void GetOpenidAndAccessToken(HttpContext context, string redirectUrl, string state = "STATE", string scope = "snsapi_base")
        {
            if (!string.IsNullOrEmpty(context.Request.QueryString["code"]))
            {
                //获取code码,以获取openid和网页授权access_token
                string code = context.Request.QueryString["code"];
                GetOpenidAndAccessTokenFromCode(code);
            }
            else
            {
                //构造网页授权获取code的URL
                //string host = context.Request.Url.Host;
                //string path = context.Request.Path;
                //string redirect_uri = HttpUtility.UrlEncode("http://" + host + path);
                if (String.IsNullOrEmpty(redirectUrl))
                {
                    redirectUrl = context.Request.Url.AbsoluteUri.ToString();
                }
                string redirect_uri = HttpUtility.UrlEncode(redirectUrl);
                var    data         = new ParamsData();
                data.SetValue("appid", APPID);
                data.SetValue("redirect_uri", redirect_uri);
                data.SetValue("response_type", "code");
                data.SetValue("scope", scope);
                data.SetValue("state", state + "#wechat_redirect");
                string url = "https://open.weixin.qq.com/connect/oauth2/authorize?" + data.ToUrl();

                context.Response.Redirect(url);
            }
        }