此篇僅為個人的學(xué)習(xí)記錄。參考地址:https://blog.csdn.net/weixin_42236466/article/details/107225625
我在uniapp的H5頁面使用微信登錄需要前后端配合加矛,項目目錄結(jié)構(gòu)為:
image.png
啟動頁為:pages/login/login (也就是我項目啟動后,直接訪問的話會直接訪問到login這個頁面)
image.png
但是我項目的入口不是login殴蹄,是另一個:index
image.png
再看login頁面:login頁面內(nèi)的js獲取微信傳過來的code,然后用這個code作為參數(shù)去訪問我的后臺接口
image.png
uniapp的manifest.json 源碼視圖
image.png
后端接口(springboot項目):
@GetMapping("/openid")
@ApiOperation("獲取微信用戶信息")
//以下僅為demo咽扇,實際開發(fā)中請再做優(yōu)化
public ResponseBean getOpenId(String code) {
System.out.println("2333");
if (code == null) {
return ResponseBean.error("code為空");
}
String wxAuthPath = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=你的appID&secret=你的appsecret&code=%s&grant_type=authorization_code";
String url = String.format(wxAuthPath, code);//拼接鏈接
RestTemplate restTemplate = new RestTemplate();//發(fā)送請求類
String res = restTemplate.getForObject(url, String.class);// openid access_token
JSONObject jsonObject = new JSONObject(res);
String openid = jsonObject.getStr("openid");
if (openid == null) {
return ResponseBean.error("openid為空");
}
String accessToken = jsonObject.getStr("access_token");
String obtainHeadImage = "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s";
String newUrl = String.format(obtainHeadImage, accessToken, openid);
String result = restTemplate.getForObject(newUrl, String.class);
result = toUTF8(result);
Map<String, Object> map = new HashMap<>();
map.put("openid", openid);
map.put("user", result);
return ResponseBean.success(map);
}
這是我的測試號
image.png
image.png
我的nginx配置 (打包的H5 --> nginx的80端口 --> http://fe2akx.natappfree.cc )
(訪問 http://fe2akx.natappfree.cc/api 相當(dāng)于訪問127.0.0.1:7979)
image.png
所有的配置以及結(jié)構(gòu)就是這樣了,可以獲取到openId以及用戶信息(頭像陕壹、地區(qū)等)质欲,也可以直接讓微信把code傳到你的接口里,不過這樣的話又要做websocket糠馆,懶得弄了嘶伟,所以采用了這么麻煩的方式,這也是我第一次做微信的登錄又碌,僅做為個人筆記九昧,以上绊袋。
流程:打開http://fe2akx.natappfree.cc/#/pages/index/index 跳轉(zhuǎn)至http://fe2akx.natappfree.cc(也就是login頁面)再訪問wx/openid接口,返回用戶信息