公衆號第三方平臺開發 教程四 代公衆號發起網頁受權說明

公衆號第三方平臺開發 教程一 建立公衆號第三方平臺

公衆號第三方平臺開發 教程二 component_verify_ticket和accessToken的獲取

公衆號第三方平臺開發 教程三 微信公衆號受權第三方平臺

公衆號第三方平臺開發 教程四 代公衆號發起網頁受權說明

公衆號第三方平臺開發 教程五 代公衆號處理消息和事件

公衆號第三方平臺開發 教程六 代公衆號使用JS SDK說明

另,感謝一下這個大蝦的博客,這幾篇東西都是在他的博文基礎上完成的,他的博客裏也有一些接口代碼能夠下載
微信開發系列教程html

 
 
 
 
 
 
 
受權流程

微信目前支持Authorization code受權模式,主要流程分爲兩步:api

  1. 1. 獲取code微信

  2. 2. 經過code換取accesstoken微信開發

首先,引導用戶在微信客戶端打開如下連接app

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函數

獲取受權連接的函數url

/// <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以及appidspa

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

若用戶禁止受權,則重定向後不會帶上code參數,僅會帶上state參數component

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);
        }
相關文章
相關標籤/搜索