微信公衆號受權給開放平臺json
公衆號受權給第三方平臺的技術實現流程比較簡單api
這個步驟遺漏了開頭獲取第三方平臺本身的accessToken微信
先說下流程app
如何註冊開放平臺的第三方信息看截圖ide
其餘不說了,此文只說代碼部分。工具
先獲取第三方10分一次的ticket。url
1 using (var streamReader = new StreamReader(Request.InputStream)) 2 { 3 string stringInput = streamReader.ReadToEnd(); 4 string sMsg = ""; //解析以後的明文 5 int ret = 0; 6 ret = wxcpt.DecryptMsg(signature, timestamp, nonce, stringInput, ref sMsg); 7 if (ret != 0) 8 return Content(string.Format("解析錯誤{0}", ret)); 9 var xDoc = XDocument.Parse(sMsg); 10 var q = (from c in xDoc.Elements() select c).ToList(); 11 var infoType = q.Elements("InfoType").First().Value; 12 switch (infoType) 13 { 14 case "component_verify_ticket": 15 var ComponentVerifyTicket = q.Elements("ComponentVerifyTicket").First().Value; 16 var wxOpen = (WebProject_GlobalConfig)WCFHelper.Invoke("WebProject_GlobalConfig", WcfFunName.SelectSingle.ToString(), 17 new object[] { "4add738c-369d-4570-ad18-77542e18a47a"});//這條請無視,只是wcf取數據。 18 wxOpen.KeyValue = ComponentVerifyTicket; 19 wxOpen.ModifyTime = DateTime.Now; 20 wxOpen = (WebProject_GlobalConfig)WCFHelper.Invoke("WebProject_GlobalConfig", WcfFunName.Save.ToString(), 21 new object[] { wxOpen }); 22 return Content("success"); 23 case "unauthorized": 24 return Content(string.Format("{0} 已取消受權", q.Elements("AuthorizerAppid").First().Value)); 25 default: 26 break; 27 } 28 } 29 return Content("參數錯誤!");
獲取到的信息解密,並保存component_verify_ticket。spa
而後就開始作第三方的token事情!3d
拿accesstokencode
var accessTokenTime = wxOpen.ModifyTime; if (accessTokenTime < DateTime.Now.AddSeconds(-7200) | String.IsNullOrEmpty(wxOpen.KeyValue)) { dynamic authorizerResult = ComponenToken(); wxOpen.ModifyTime = DateTime.Now; wxOpen.KeyValue = authorizerResult.component_access_token; WCFHelper.Invoke("WebProject_GlobalConfig", WcfFunName.Save.ToString(), new object[] { wxOpen }); } /// <summary> /// Ticket票據讀取第三方token /// </summary> /// <returns></returns> public static dynamic ComponenToken() { var url = "https://api.weixin.qq.com/cgi-bin/component/api_component_token"; var jsonDate = new { component_appid = GetConfig("ComponentAppid"), component_appsecret = GetConfig("ComponentSercet"), component_verify_ticket = GetConfig("ComponentVerifyTicket") }; return CommonJsonSend.Send<dynamic>(null, url, jsonDate); }
而後就能夠作受權跳轉
/// <summary> /// 跳轉受權 /// </summary> /// <returns></returns> public ActionResult WxRedirect() { var url = "https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid={0}&pre_auth_code={1}&redirect_uri={2}";//跳轉網頁 var proResult = WeChatTokenHelper.GetProCode();//預受權碼 url = String.Format(url, WeChatTokenHelper.GetConfig("ComponentAppid"), proResult.pre_auth_code, "http://XXXXX/DptWxOpen/AuthInfo"); return Redirect(url); }
不知道怎麼拿預受權碼?好吧,看代碼!
/// <summary> /// 第三方token讀取預受權讀取 /// </summary> /// <param name="Ticket"></param> /// <returns></returns> public static dynamic GetProCode() { var url = "https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token={0}"; var jsonData = new { component_appid = GetConfig("ComponentAppid") }; return CommonJsonSend.Send<dynamic>(GetOpenToken(), url, jsonData); }
最後的悲哀受權成功回調~
/// <summary> /// 微信回調url /// </summary> /// <param name="auth_code"></param> /// <returns></returns> public ActionResult AuthInfo(String auth_code) { var admin = Session["WebAdmin"] as WebProject_Admin; //登錄身份而已,別太在乎 if (admin == null) return Redirect("/DptPages/Login"); dynamic tokenResult = WeChatTokenHelper.GetWeChat(auth_code);//換受權碼 dynamic authorizationInfo = tokenResult.authorization_info; String appId = authorizationInfo.authorizer_appid; var authorizerInfo = (WebProject_AuthorizerWeChat)WCFHelper.Invoke("WebProject_AuthorizerWeChat", WcfFunName.SelectSingle.ToString(), new object[] { "x.WebId == " + admin.WebId, true }); if (authorizerInfo == null) { authorizerInfo = new WebProject_AuthorizerWeChat { WebId = admin.WebId }; authorizerInfo = (WebProject_AuthorizerWeChat)WCFHelper.Invoke("WebProject_AuthorizerWeChat", WcfFunName.Save.ToString(), new object[] { authorizerInfo }); } if (authorizerInfo == null) return Content("對象報錯!"); authorizerInfo.AppId = appId; authorizerInfo.AccessToken = authorizationInfo.authorizer_access_token; authorizerInfo.AccessTokenTime = DateTime.Now; authorizerInfo.RefreshToken = authorizationInfo.authorizer_refresh_token; var Func = JSON.Deserialize<func_info>(funcinfo(authorizationInfo.func_info)); var Json = ""; foreach (var i in Func.Info) { i.funcscope_category.FuncType = i.funcscope_category.id > 0 ? (FuncType)i.funcscope_category.id : FuncType.Error; Json += JSON.ToJson(i); } authorizerInfo.FuncInfo = Json; authorizerInfo = (WebProject_AuthorizerWeChat)WCFHelper.Invoke("WebProject_AuthorizerWeChat", WcfFunName.Save.ToString(), new object[] { authorizerInfo }); return Redirect("WeChatInfo?state=true"); }
好人作到底,受權碼方法:
/// <summary> /// 受權碼code換身份 /// </summary> /// <param name="authCode"></param> /// <returns></returns> public static dynamic GetWeChat(String authCode) { var url = "https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token={0}"; var jsonData = new { component_appid = GetConfig("ComponentAppid"), authorization_code = authCode }; return CommonJsonSend.Send<dynamic>(GetOpenToken(), url, jsonData); }
幾個關於受權信息的類工具:
#region AuthorInfo Helper public string funcinfo(dynamic info) { string newinfo = "{\"Info\":" + info + "}"; return newinfo; } public class func_info { public List<InfoList> Info { get; set; } } public class InfoList { public Info funcscope_category { get; set; } } public class Info { public Int32 id { get; set; } public FuncType FuncType { get; set; } } #endregion
如有問題請評論留言~