码迷,mamicode.com
首页 > 微信 > 详细

微信第三方平台开头篇--MVC代码(第三方获取ticket和公众号授权)

时间:2016-08-11 17:20:40      阅读:1664      评论:0      收藏:0      [点我收藏+]

标签:

微信公众号授权给开放平台

公众号授权给第三方平台的技术实现流程比较简单

技术分享

这个步骤遗漏了开头获取第三方平台自己的accessToken

先说下流程

如何注册开放平台的第三方信息看截图

技术分享

 

 其他不说了,此文只说代码部分。

先获取第三方10分一次的ticket。

 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。

然后就开始做第三方的token事情!

拿accesstoken

技术分享
                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);
        }
View Code

然后就可以做授权跳转

        /// <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

 若有问题请评论留言~

 

微信第三方平台开头篇--MVC代码(第三方获取ticket和公众号授权)

标签:

原文地址:http://www.cnblogs.com/Zatsugaku-code/p/5761539.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!