公眾號第三方平台開發 教程一 創建公眾號第三方平台
公眾號第三方平台開發 教程二 component_verify_ticket和accessToken的獲取
公眾號第三方平台開發 教程三 微信公眾號授權第三方平台
公眾號第三方平台開發 教程四 代公眾號發起網頁授權說明
公眾號第三方平台開發 教程五 代公眾號處理消息和事件
公眾號第三方平台開發 教程六 代公眾號使用JS SDK說明
另,感謝一下這個大蝦的博客,這幾篇東西都是在他的博文基礎上完成的,他的博客里也有一些接口代碼可以下載
微信開發系列教程
授權流程
微信目前支持Authorization code授權模式,主要流程分為兩步:
-
1. 獲取code
-
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); }