微信網頁授權
我知道我知道,網上這類的文章已經太多太多了,主要是自己整理一下
什么時候需要網頁授權?
你自己做了一個網站,可以使用微信登陸,你需要記錄一些關於該微信用戶的一些信息,最簡單的就是歡迎界面你得知道用戶的昵稱吧。微信網頁授權,就是可以將微信用戶的信息授權給你的網站。
准備工作
微信服務器在用戶和服務商之間,充當一個轉發服務器的角色。用戶在微信客戶端的各種請求先是到達微信的服務器,微信服務器再轉發給服務商的服務器。開發的時候我們並沒有公網服務器,公網服務器上也不方便調試,所以我們需要一個能夠穿透內網的工具,natapp,收費也不貴,非常好用。
先下載它的客戶端,是一個單獨的.exe文件natapp.exe,它需要一個authtoken參數,當你注冊並擁有一個隧道后,就能得到這個authtoken。
連接成功之后如下圖
這樣的話,外網對這個地址的請求都會映射到本地的127.0.0.1:80端口。
創建一個MVC工程
打開vs創建一個mvc工程,並修改web屬性
注意: 這里要能夠成功修改必須要有管理員權限
然后配置IIS,物理路徑選擇工程所在的路徑,ip地址填寫127.0.0.1,端口為80即可。
弄好這些,我們來用外網地址訪問一下站點
成功啦!
微信網頁授權
配置授權回調域名
我們用微信的測試接口來做這個
意思就是,通過微信授權成功后的回調頁面必須在這個域名
下面。
請求code
查看微信網頁授權的文檔,在獲取用戶信息之前要先獲取code,基本的請求連接為
https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect
appid:測試號的appid
redirect_url:授權之后的回調地址
response_type:填寫code即可
state:傳遞給回調頁面的參數,包含業務信息,加密傳遞即可
scope:這里有兩種級別,snsapi_base和snsapi_userinfo
snsapi_base:不需要用戶確認授權,直接跳轉到回調頁面,這種方式僅僅能獲取到openId
snsapi_userinfo:需要用戶點擊確認按鈕授權,授權后跳轉回調頁面,這種方式可以獲取到更多微信用戶的信息,包括昵稱,頭像,性別等等
發起授權請求如下:
public ActionResult Do()
{
var reUrl = "http://你的域名/test/index";
var scope = "snsapi_base";
var scope2 = "snsapi_userinfo";
var args = "1";
var url =
"https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope={2}&state={3}#wechat_redirect";
url = string.Format(url, _appid, reUrl, scope2, args);
return Redirect(url);
}
獲取code,換取access_token
在上一步,我們填寫的回調地址是test控制器下的index方法,回調時,會將code和state參數帶過來,利用這個code參數可以換取access_token,用access_token又可以獲取到更多的用戶信息
基本的請求連接為:
https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code
appid和secret為測試微信號的id和密碼,code即上一步回調過來的參數
public ActionResult Index(string code, string state)
{
var url =
"https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code";
url = string.Format(url, _appid, _appsecret, code);
//獲取access_token
var data = GetRequest(url);
var json = JsonConvert.DeserializeObject<Result>(data);
ViewBag.OpenId = json.openid;
ViewBag.State = state;
//通過access_token獲取用戶信息
var url2 = "https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}&lang=zh_CN";
url2 = string.Format(url2, json.access_token, json.openid);
var json2 = GetRequest(url2);
return View();
}
public class Result
{
public string access_token
{
get; set;
}
public int expires_in
{
get; set;
}
public string refresh_token
{
get; set;
}
public string openid
{
get; set;
}
public string scope
{
get; set;
}
public string unionid
{
get; set;
}
}
private string GetRequest(string url)
{
var request = WebRequest.CreateHttp(url);
request.Method = "POST";
var response = request.GetResponse();
using (var stream = response.GetResponseStream())
{
var sr = new StreamReader(stream);
var data = sr.ReadToEnd();
return data;
}
}
整個過程還是比較輕松愉快的,主要是有了natapp這個工具,開發調試都非常方便