微信公眾號授權登入
說明:如果使用者在微信客戶端中訪問第三方網頁,公眾號可以通過微信網頁授權機制,來獲取使用者基本資訊,進而實現業務邏輯。
1、授權回撥域名
首先,先登入微信公眾平臺填寫授權回撥頁面域名(可以申請公眾平臺測試賬號進行開發),回撥頁面域名是你的第三方跳轉域名,不需要加http,如截圖所示:
2、授權流程分為4步:
a、引導使用者進入授權頁面同意授權,獲取code
b、通過code換取網頁授權access_token(與基礎支援中的access_token不同)
c、如果需要,開發者可以重新整理網頁授權access_token,避免過期 (這一步可以省略)
d、通過網頁授權access_token和openid獲取使用者基本資訊(支援UnionID機制)
3、流程演示例子
第一步:引導使用者進入授權頁面同意授權
點選連結: https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxf0e81c3bee622d60&redirect_uri=http%3A%2F%2toSetOpenidForWechat.do&response_type=code&scope=
snsapi_userinfo&state=STATE#wechat_redirect
引數講解:appid是你的公眾號的唯一標識appid,redirect_uri是你的跳轉連結,必須要用urlEncode
例子:
@RequestMapping(value = "/toSetOpenidForWechat", method = RequestMethod.GET) public ModelAndView toSetOpenidForWechat(HttpServletRequest req, HttpServletResponse res ,String code) throws Exception { //根據code獲取使用者的access_token和openid ModelAndView view = new ModelAndView(); Session session = SecurityUtils.getSubject().getSession(); String urlForWechat = (String) session.getAttribute("urlForWechat"); net.sf.json.JSONObject userInfo = getToken(req, res, code); view.addObject("openid", userInfo.getString("openid")); view.setViewName("wechat/setOpenid"); return view; }
第二步:通過code換取網頁授權access_token和openid
使用者點選授權後,獲取到code,進行下一步處理,通過code換取網頁授權access_token和openid,請求下面連結
連結:https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
引數講解:code是你上一步獲取的code,appid是你的公眾號的唯一標識appid,secret是你的公眾號的appsecret,其他引數照著寫,經過這一步後,會返回一個access_token和openid引數
第三步:通過access_token和openid拉取使用者資訊
獲取到access_token和openid引數,通過access_token和openid拉取使用者資訊,請求下面連結
連結:https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
引數講解:access_token和openid引數是你上一步驟獲取的引數,其他引數照著寫,經過這一步後,微信會以json方式返回使用者資訊給你
正確時返回的JSON資料包如下:
{ "openid":" OPENID",
" nickname": NICKNAME,
"sex":"1",
"province":"PROVINCE"
"city":"CITY",
"country":"COUNTRY",
"headimgurl": "http://wx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ
4eMsv84eavHiaiceqxibJxCfHe/46",
"privilege":[ "PRIVILEGE1" "PRIVILEGE2" ],
"unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
}
以下是本人專案中的例子,由於第二步,第三步操作相同,所有我只寫到一個方法中
例子:
public net.sf.json.JSONObject getToken(HttpServletRequest req,HttpServletResponse res,String code) throws Exception {
//獲取微信服務appid和密碼
String appid = "";//你公眾號的appid
String appsecret = "";//你公眾號的appsecret
//根據code獲取使用者的access_token和openid
String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appid+"&secret="+appsecret+"&code="+code+"&grant_type=authorization_code";
net.sf.json.JSONObject json = AuthUtil.doGetJson(url);
String openid = json.getString("openid");
String token = json.getString("access_token");
//根據access_token和openid獲取使用者的資訊
String infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token="+token+"&openid="+openid+"&lang=zh_CN";
net.sf.json.JSONObject userInfo = AuthUtil.doGetJson(infoUrl);
System.out.println(userInfo);
return userInfo;
}
在程式碼中用到了一個工具類AuthUtil
package com.ed.login;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import net.sf.json.JSONObject;
public class AuthUtil {
public static JSONObject doGetJson(String url) throws ParseException, IOException{
JSONObject jsonObject = null;
//DefaultHttpClient client = new DefaultHttpClient();
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response = null;
//HttpResponse response = null;
try {
response = httpclient.execute(httpGet);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HttpEntity entity = response.getEntity();
if(entity != null){
String result = EntityUtils.toString(entity,"UTF-8");
jsonObject = JSONObject.fromObject(result);
}
httpGet.releaseConnection();
return jsonObject;
}
}
最後,你就能獲取到使用者資訊了,本帖子例子舉例的是應用授權作用域為scope=snsapi_userinfo(彈出授權頁面,可通過openid拿到暱稱、性別、所在地等),如有不明之處或寫的不好地方,歡迎留言討論