公众号第三方平台开发 教程四 代公众号发起网页授权说明

发布时间:2017/12/26 来源: 浏览:浏览次数:1102
标签:

公众号第三方平台开发 教程一 创建公众号第三方平台

公众号第三方平台开发 教程二 component_verify_ticket和accessToken的获取

公众号第三方平台开发 教程三 微信公众号授权第三方平台

公众号第三方平台开发 教程四 代公众号发起网页授权说明

公众号第三方平台开发 教程五 代公众号处理消息和事件

公众号第三方平台开发 教程六 代公众号使用JS SDK说明


授权流程

微信目前支持Authorization code授权模式,主要流程分为两步:

  1. 1. 获取code

  2. 2. 通过code换取accesstoken

首先,引导用户在微信客户端打开以下链接

https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE&component_appid=component_appid#wechat_redirect

获取授权链接的函数


/// <summary> /// 获取授权连接 /// </summary> /// <param name="appId">公众号的appid </param> /// <param name="redirectUrl">重定向地址,需要urlencode,这里填写的应是服务开发方的回调地址 </param> /// <param name="scope">授权作用域,拥有多个作用域用逗号(,)分隔 </param>  /// <param name="state">重定向后会带上state参数,开发者可以填写任意参数值,最多128字节 </param> /// <param name="component_appid">服务方的appid,
在申请创建公众号服务成功后,可在公众号服务详情页找到</param>   /// <param name="responseType">默认为填code</param>  /// <returns>URL</returns> public static string GetAuthorizeUrl(string appId,
                                                               string redirectUrl,
                  OAuthScope scope,string state, string component_appid,string responseType = "code")
        { var url = string.Format
("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}
&redirect_uri={1}&response_type={2}&scope={3}&state={4}&component_appid={5}#wechat_redirect",
                                appId, redirectUrl.UrlEncode(),
 responseType, scope, state,component_appid); return url;
        } 

返回说明

用户允许授权后,将会重定向到redirect_uri的网址上,并且带上code, state以及appid

redirect_uri?code=CODE&state=STATE&appid=APPID   

若用户禁止授权,则重定向后不会带上code参数,仅会带上state参数

redirect_uri?state=STATE   

第二步:通过code换取access_token

复制代码
        /// <summary> /// 通过code换取access_token /// </summary>  /// <param name="appId">公众号的appid</param> /// <param name="code">填写第一步获取的code参数</param> /// <param name="componentAppId">服务开发方的appid</param> /// <param name="componentAccessToken">服务开发方的access_token</param> /// <param name="grantType">填authorization_code</param> /// <returns></returns> public static ResponseOAuthOpenAccessToken GetOpenAccessToken( string appId, string code, string componentAppId, string componentAccessToken, string grantType 
= "authorization_code")      
{ var url = string.Format( "https://api.weixin.qq.com/sns/oauth2/component/access_token?appid={0}
&code={1}&grant_type={2}&component_appid={3}&component_access_token={4}",
                    appId, code, grantType, componentAppId, componentAccessToken);
 return Get.GetJson<ResponseOAuthOpenAccessToken>(url);
        }

 

客服
热线

4000-277-886
7*24小时客服服务热线

关注
微信

关注官方微信