Vue前端开发——微信登录
生活随笔
收集整理的這篇文章主要介紹了
Vue前端开发——微信登录
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1、準備工作
1.1 現在微信開放平臺注冊一個賬號
https://open.weixin.qq.com/
1.2 查看官方文檔
https://developers.weixin.qq.com/doc/oplatform/Website_App/WeChat_Login/Wechat_Login.html- 在進行微信OAuth2.0授權登錄接入之前,在微信開放平臺注冊開發者帳號,并擁有一個已審核通過的網站應用,并獲得相應的AppID和AppSecret,申請微信登錄且通過審核后,可開始接入流程
- 注冊帳號和申請應用都是免費的,必須要有一個線上的網站,才能審核通過(過程還是挺麻煩的),就可以使用微信的登錄了
- 但是如果想使用微信支付的功能,就必須認證開發者資質(認證一次300塊人民幣)
- AppID ?應用ID,唯一標識(身份證號)
- AppSecret?應用的密鑰(密碼)
- code?授權的臨時憑證(例如:臨時身份證)
- access_token?接口調用憑證(例如:真正的身份證,虎符,令牌)
2、引入二維碼
2.1 在Vue中進行安裝 npm install vue-wxlogin 如果不是vue的項目,可以直接引用官方提供的js文件,來生成二維碼 2.2 在Header.vue登錄頁面引入 <script>// import wxlogin from 'vue-wxlogin'; // 引入export default {name: "Header",components:{// wxlogin // 聲明引用的組件},2.3 引入二維碼,首先定義了一個<div id="loginForm">
<!-- 登錄表單--><div id="loginForm"><el-form><el-form-item><h1 style="font-size:30px;color:#00B38A">拉勾</h1></el-form-item><el-form-item><el-input v-model="phone" placeholder="請輸入常用手機號..."></el-input></el-form-item><el-form-item><el-input v-model="password" placeholder="請輸入密碼..."></el-input></el-form-item></el-form><el-buttonstyle="width:100%;margin:0px auto;background-color: #00B38A;font-size:20px"type="primary"@click="login">確 定</el-button><p></p><!-- 微信登錄圖標 --><img@click="goToLoginWX"src="http://www.lgstatic.com/lg-passport-fed/static/pc/modules/common/img/icon-wechat@2x_68c86d1.png"alt=""/></div>然后引入二維碼
<!-- 二維碼 --> <wxlogin id="wxLoginForm" style="display:none" :appid="appid" :scope="scope" :redirect_uri="redirect_uri"> </wxlogin>在data中定義
data() {return {isLogin: false, // 登錄狀態,true:已登錄,false:未登錄userDTO:null, // 用來保存登錄的用戶信息isHasNewMessage: false, // 是否有新的推送消息dialogFormVisible: false, // 是否顯示登錄框,true:顯示,false:隱藏phone: "", // 雙向綁定表單 手機號password: "", // 雙向綁定表單 密碼appid:"數據", // 應用唯一標識,在微信開放平臺提交應用審核通過后獲得scope:"snsapi_login", // 應用授權作用域,網頁應用目前僅填寫snsapi_login即可redirect_uri:"數據", //重定向地址,(回調地址)};},在methods中定義
// 微信登錄goToLoginWX() {// 普通的登錄表單隱藏document.getElementById("loginForm").style.display = "none";// 顯示二維碼的容器document.getElementById("wxLoginForm").style.display = "block";}); },2.4?methods中login()方法
login(){ // 前去登錄return this.axios.get("http://localhost:80/user/login" , {params:{phone:this.phone,password:this.password,nickname:"",headimg:""}}).then( (result)=>{console.log( result );this.dialogFormVisible = false ; //關閉登錄框this.userDTO = result.data; // 保存返回數據中的用戶對象信息this.isLogin = true; // 更新登錄狀態localStorage.setItem("user", JSON.stringify(this.userDTO)); // 將登錄成功的對象信息保存到本地儲存中} ).catch( (error)=>{this.$message.error("登錄失敗!");});},?2.5?created中
created(){// 當刷新頁面,組件創建成功之后,立刻檢測本地儲存中是否存在用戶對象this.userDTO = JSON.parse( localStorage.getItem("user") );if(this.userDTO != null){this.isLogin = true; // 已登錄}else{// 去檢測微信是否登錄過this.axios.get("http://localhost:80/user/checkWxStatus").then( (result)=>{this.userDTO = result.data;this.phone = this.userDTO.content.phone;this.password = this.userDTO.content.password;this.login();// 走普通登錄}).catch( (error)=>{//this.$message.error("登錄失敗!");});}},修改HOSTS文件
文件位置:C:\Windows\System32\drivers\etc\hosts 回調默認指定的是80端口,別忘記將tomcat的8003端口修改成80 127.0.0.1 www.pinzhi365.com3、IDEA代碼
3.1?lagou-edu-web中pom.xml依賴
<!-- 需要使用HttpServletRequest獲得參數 --><dependency><groupId>javax.servlet</groupId><artifactId>servlet-api</artifactId><version>2.4</version><scope>provided</scope></dependency><!-- 需要使用HttpClient發出請求 --><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.12</version></dependency>3.2 在commons中封裝HttpClientUtil
package commons;import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.utils.URIBuilder; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils;import java.net.URI; import java.util.Map;/*** @Description: httpclient的封裝工具類*/ public class HttpClientUtil {public static String doGet(String url) {return doGet(url,null);}/*** get請求,支持request請求方式,不支持restfull方式** @param url 請求地址* @param param 參數* @return 響應的字符串*/public static String doGet(String url, Map<String, String> param) {// 創建httpclient對象CloseableHttpClient httpClient = HttpClients.createDefault();String resultString = "";CloseableHttpResponse response =null;try {// 創建urlURIBuilder builder = new URIBuilder(url);if (param != null) {// 在url后面拼接請求參數for (String key : param.keySet()) {builder.addParameter(key, param.get(key));}}URI uri = builder.build();// 創建http get請求HttpGet httpGet = new HttpGet(uri);// 執行請求response = httpClient.execute(httpGet);// 從響應對象中獲取狀態碼(成功或失敗的狀態)int statusCode = response.getStatusLine().getStatusCode();System.out.println("響應的狀態 = " + statusCode);// 200表示響應成功if (statusCode == 200) {// 響應的內容字符串resultString = EntityUtils.toString(response.getEntity(), "UTF-8");}} catch (Exception e) {e.printStackTrace();}finally{// 釋放資源try {if (response != null) {response.close();}httpClient.close();} catch (Exception e) {e.printStackTrace();}}return resultString;} }3.3?定義從微信返回的數據對象——定義Token對象,轉換為實體類
package entity;/*** @Description: 令牌實體類*/ public class Token {private String access_token ;//接口調用憑證private String expires_in;// access_token接口調用憑證超時時間,單位(秒)private String refresh_token;// 用戶刷新access_tokenprivate String openid;// 授權用戶唯一標識private String scope;// 用戶授權的作用域,使用逗號(,)分隔private String unionid;// 當且僅當該網站應用已獲得該用戶的userinfo授權時,才會出現該字段。public String getAccess_token() {return access_token;}public void setAccess_token(String access_token) {this.access_token = access_token;}public String getExpires_in() {return expires_in;}public void setExpires_in(String expires_in) {this.expires_in = expires_in;}public String getRefresh_token() {return refresh_token;}public void setRefresh_token(String refresh_token) {this.refresh_token = refresh_token;}public String getOpenid() {return openid;}public void setOpenid(String openid) {this.openid = openid;}public String getScope() {return scope;}public void setScope(String scope) {this.scope = scope;}public String getUnionid() {return unionid;}public void setUnionid(String unionid) {this.unionid = unionid;}public Token() {}public Token(String access_token, String expires_in, String refresh_token, String openid, String scope, String unionid) {this.access_token = access_token;this.expires_in = expires_in;this.refresh_token = refresh_token;this.openid = openid;this.scope = scope;this.unionid = unionid;} }3.3 定義WxUser——將json格式的user字符串轉換成實體對象,方便存和取
package entity;/*** @Description: 微信的用戶信息*/ public class WxUser {private String openid;// 普通用戶的標識,對當前開發者帳號唯一private String nickname;// 普通用戶昵稱private String sex;// 普通用戶性別,1為男性,2為女性private String province;// 普通用戶個人資料填寫的省份private String city;// 普通用戶個人資料填寫的城市private String country;// 國家,如中國為CNprivate String headimgurl;// 用戶頭像,最后一個數值代表正方形頭像大小(有0、46、64、96、132數值可選,0代表640*640正方形頭像),用戶沒有頭像時該項為空private String privilege;// 用戶特權信息,json數組,如微信沃卡用戶為(chinaunicom)private String unionid;// 用戶統一標識。針對一個微信開放平臺帳號下的應用,同一用戶的unionid是唯一的。public WxUser() {}public WxUser(String openid, String nickname, String sex, String province, String city, String country, String headimgurl, String privilege, String unionid) {this.openid = openid;this.nickname = nickname;this.sex = sex;this.province = province;this.city = city;this.country = country;this.headimgurl = headimgurl;this.privilege = privilege;this.unionid = unionid;}public String getOpenid() {return openid;}public void setOpenid(String openid) {this.openid = openid;}public String getNickname() {return nickname;}public void setNickname(String nickname) {this.nickname = nickname;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}public String getProvince() {return province;}public void setProvince(String province) {this.province = province;}public String getCity() {return city;}public void setCity(String city) {this.city = city;}public String getCountry() {return country;}public void setCountry(String country) {this.country = country;}public String getHeadimgurl() {return headimgurl;}public void setHeadimgurl(String headimgurl) {this.headimgurl = headimgurl;}public String getPrivilege() {return privilege;}public void setPrivilege(String privilege) {this.privilege = privilege;}public String getUnionid() {return unionid;}public void setUnionid(String unionid) {this.unionid = unionid;} }3.4 lagou-edu-dao
Integer register(@Param("phone") String phone, @Param("password") String password,@Param("nickname") String nickname,@Param("headimg") String headimg); <insert id="register">insert into `user`(`name`,portrait,phone,password,create_time,update_time)values(#{nickname},#{headimg},#{phone},#{password},sysdate(),sysdate()) </insert>3.5?lagou-edu-service
Integer register( String phone, String password,String nickname,String headimg); @Overridepublic Integer register(String phone, String password, String nickname, String headimg) {return userDao.register(phone,password,nickname,headimg);}3.6?lagou-edu-web
Integer register( String phone, String password,String nickname,String headimg);?WxLoginController
package com.lagou.wx;import com.alibaba.druid.sql.visitor.SQLASTOutputVisitor; import com.alibaba.dubbo.config.annotation.Reference; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.lagou.entity.User; import com.lagou.entity.UserDTO; import com.lagou.user.UserService; import commons.HttpClientUtil; import entity.Token; import entity.WxUser; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException;/*** @Description:*/ @RestController @RequestMapping("user") public class WxLoginController {@Reference // 遠程消費private UserService userService;private UserDTO dto = null; // 是否用微信登錄成功,dto為null,則尚未登錄@GetMapping("wxlogin")public String wxlogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// 1. 微信官方發給我們一個臨時憑證String code = request.getParameter("code");System.out.println("【臨時憑證】code = " + code);// 2. 通過code,去微信官方申請一個正式的token(令牌)String getTokenByCode_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxd99431bbff8305a0&secret=60f78681d063590a469f1b297feff3c4&code=" + code + "&grant_type=authorization_code";String tokenString = HttpClientUtil.doGet(getTokenByCode_url);System.out.println("tokenString = " + tokenString);// 將json格式的token字符串轉換成實體對象,方便存和取Token token = JSON.parseObject(tokenString, Token.class);// 3. 通過token,去微信官方獲取用戶的信息String getUserByToken_url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + token.getAccess_token() + "&openid=" + token.getOpenid();String userinfoString = HttpClientUtil.doGet(getUserByToken_url);System.out.println("userinfoString = " + userinfoString);// 將json格式的user字符串轉換成實體對象,方便存和取WxUser wxUser = JSON.parseObject(userinfoString, WxUser.class);System.out.println("微信昵稱 = " + wxUser.getNickname());System.out.println("微信頭像 = " + wxUser.getHeadimgurl());// 拉勾的業務流程! 需要 手機號(wxUser.getUnionid())和密碼(wxUser.getUnionid()),頭像和昵稱User user = null;dto = new UserDTO();// 檢測手機號是否注冊Integer i = userService.checkPhone(wxUser.getUnionid());if(i == 0){// 未注冊,自動注冊并登錄userService.register(wxUser.getUnionid(), wxUser.getUnionid(),wxUser.getNickname(),wxUser.getHeadimgurl());dto.setMessage("手機號尚未注冊,系統已幫您自動注冊,請牢記密碼!");user = userService.login(wxUser.getUnionid(), wxUser.getUnionid());}else{user = userService.login(wxUser.getUnionid(), wxUser.getUnionid());if(user == null){dto.setState(300); //300表示失敗dto.setMessage("帳號密碼不匹配,登錄失敗!");}else{dto.setState(200); //200表示成功dto.setMessage("登錄成功!");}}dto.setContent(user);response.sendRedirect("http://localhost:8080");return null;}@GetMapping("checkWxStatus")public UserDTO checkWxStatus(){return this.dto;}@GetMapping("logout")public Object logout(){this.dto = null;return null;}}?
? ??
總結
以上是生活随笔為你收集整理的Vue前端开发——微信登录的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: selenium模拟 + 鼠标滚动爬取魔
- 下一篇: html5倒计时秒杀怎么做,vue 设