本文用項目架構為spring boot
本文旨在簡介微信第三方登陸的主要步驟,
網站微信第三方登陸需要幾個條件
1.擁有微信開放平台
如果沒有的話需要到https://open.weixin.qq.com/申請
2.進入開放平台,并在網站應用下建立相應的應用
微信官方文檔
https://open.weixin.qq.com/connect/qrconnect?appid=appid&redirect_uri=跳轉連結&response_type=code&scope=snsapi_login&state=STATE#wechat_redirect
生成頁面,掃碼登陸後位址欄會附帶code參數
2.拿到位址欄的code,通過code擷取登陸使用者的資訊
代碼如下:(這裡将第二步和第三部結合到了一起)
/**
* 擷取微信使用者資訊
* @param code
* @return
*/
@GetMapping("/weixin/userInfo")
@ResponseBody
public ResponseEntity<Result> getWeixinUserInfo(@RequestParam(value="code") String code){
return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON_UTF8)
.body(Result.build().content(weixinService.getUserInfo(code)));
}
/**
* @author Lichenyi
* @date 2017-7-5
*/
@SuppressWarnings("all")
@Service("IWeixinService")
public class WeixinService implements IWeixinService {
private Logger logger = LogManager.getLogger(getClass());
@Autowired
private RestTemplate restTemplate;
@Value("${weixin.open.connect}")
private String weixin_open_connect;//網站跳轉
@Value("${weixin.open.sns.oauth2}")
private String weixin_open_sns_oauth2;//擷取access token
@Value("${weixin.open.sns.userinfo}")
private String weixin_open_sns_userinfo;//根據access token 擷取使用者資訊
/**
* 擷取access_token
*
* @param code
* @return
*/
private JSONObject getAccessToken(String code) {
String tokenJson = null;
String url = String.format(weixin_open_sns_oauth2, code);
String resultStr = restTemplate.getForObject(url, String.class);
JSONObject result = JSONObject.parseObject(resultStr);
if (result.getString("access_token") != null) {
return result;
}
logger.error(String.format("擷取accesstoken錯誤 %s", result.toJSONString()));
return result;
}
/**
* 擷取使用者資訊
*
* @param code
* @return
*/
@Override
public JSONObject getUserInfo(String code) {
try {
JSONObject accessToken = getAccessToken(code);
if (accessToken.getString("access_token") == null) {
return accessToken;
}
String token = accessToken.getString("access_token");
String openid = accessToken.getString("openid");
String url = String.format(weixin_open_sns_userinfo, token, openid);
String resultStr = restTemplate.getForObject(url, String.class);
resultStr = new String(resultStr.getBytes("ISO-8859-1"), "UTF-8");
JSONObject result = JSONObject.parseObject(resultStr);
if (result.getString("openid") != null) {
return result;
}
logger.error(String.format("擷取使用者資訊錯誤 %s", result.toJSONString()));
return result;
}catch (UnsupportedEncodingException e){
logger.error(String.format("轉碼錯誤 %s", e.getMessage()));
e.printStackTrace();
}
return null;
}
}
application.properties檔案
server.port=
##微信相關接口
weixin.open.appid=
weixin.open.secret=
weixin.open.redirect_uri=http://m.mjiahome.com/index.html
#生成二維碼的頁面
weixin.open.connect=https://open.weixin.qq.com/connect/qrconnect?appid=${weixin.open.appid}&redirect_uri=${weixin.open.redirect_uri}&response_type=code&scope=snsapi_login&state=STATE#wechat_redirect
weixin.open.sns.oauth2=https://api.weixin.qq.com/sns/oauth2/access_token?appid=${weixin.open.appid}&secret=${weixin.open.secret}&code=%s&grant_type=authorization_code
weixin.open.sns.userinfo=https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s
項目最後傳回結果:
{
"errorCode": ,
"errorDescription": "success",
"requestId": "a9026ed2-2986-434c-8762-88deb14cb54d",
"result": {
"country": "CN",
"unionid": "oV6Xy0rmk13eJp_TCOHKOKcbzGFI",
"province": "Henan",
"city": "Luoyang",
"openid": "oe9Uv01iSHLbUR439JUY-nT3Rpbg",
"sex": ,
"nickname": "一壺酒",
"headimgurl": "http://wx.qlogo.cn/mmopen/muJQmcibTZam2heIDTXUseWtwyxiarxFXtACucoib1w5PibiaDun7EJibw6ibfC0z1XxSpmjmickKK0Ms2nwCOezy9WYLp14rH1RhjEib/0",
"language": "zh_CN",
"privilege": []
}
}
項目位址:https://github.com/lichenyigit/oauth.weixin.git