微信第三方平台处理授权公众号的网页授权接口

写一OAuthController的MVC控制器,用来接收公众号的网页授权请求

 1 public async Task<ActionResult> RedirectCallback(string state, string code = "", string appid = "", string clienturl = "")
 2         {
 3             if (code.Length == 0)
 4             {
 5                 if (clienturl.IndexOf("?") != -1)
 6                     return Redirect(OAuthCallback + clienturl + "&errcode=-1&errmsg=" + HttpUtility.UrlEncode("用户禁止授权"));
 7                 else
 8                     return Redirect(OAuthCallback + clienturl + "?errcode=-1&errmsg=" + HttpUtility.UrlEncode("用户禁止授权"));
 9             }
10 
11             var ticketValue = "";
12             string path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"configs\WeChat.ThirdpartyPlatform.ComponentVerifyTicket.xml";
13             using (StreamReader sr = new StreamReader(path, Encoding.UTF8))
14             {
15                 string txt = sr.ReadToEnd();
16                 string[] lines = txt.Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
17                 if (lines.Length == 4)
18                     ticketValue = lines[3];
19             }
20             var accessTokenValue = await Authentication.GetComponentAccessToken(AppId, AppSecret, ticketValue);
21             var jsonStr = await Util.HttpGetAsync("https://api.weixin.qq.com/sns/oauth2/component/access_token?appid=" + appid + "&code=" + code + "&grant_type=authorization_code&component_appid=" + AppId + "&component_access_token=" + accessTokenValue);
22             //if (jsonStr.Contains("errcode"))
23             //{
24             //    response.Content = new StringContent(jsonStr, Encoding.UTF8, "text/html");
25             //    return response;
26             //}
27             JObject result = Newtonsoft.Json.JsonConvert.DeserializeObject<JObject>(jsonStr);
28             string openid = result["openid"].Value<string>();
29             if (clienturl.IndexOf("?") != -1)
30                 return Redirect(OAuthCallback + clienturl + "&errcode=0&openid=" + openid);
31             else
32                 return Redirect(OAuthCallback + clienturl + "?errcode=0&openid=" + openid);
33         }

 注意:由第三方平台授权的网页授权,不需要将“公众号设置->功能设置->网页授权域名”特地设置为返回url对应的域名。

 

posted @ 2017-08-03 18:52  妙衍软设  阅读(545)  评论(1编辑  收藏  举报