目錄
一、小程序登錄微信登錄接口演示
1.1 項(xiàng)目導(dǎo)入
1.2 method1?
1.3 method2
二、小程序授權(quán)登錄
2.1 登錄過程
2.1.1 詳解
2.1.2 圖解
2.2 后端代碼導(dǎo)入
2.3 前端代碼導(dǎo)入
?編輯
2.4 案例演示
前端代碼如下:
2.4.1 前端調(diào)用接口地址
2.4.2 個(gè)人中心
后端代碼如下:
2.5 效果演示?
?文章來源地址http://www.zghlxwxcb.cn/news/detail-785866.html
一、小程序登錄微信登錄接口演示
1.1 項(xiàng)目導(dǎo)入
然后選擇要上傳的文件夾,輸入appid后點(diǎn)擊確認(rèn)導(dǎo)入就可以了。
1.2 method1?
method1方法獲取用戶信息存在一定風(fēng)險(xiǎn),并不安全。
把執(zhí)行方法改成false,如下:
模擬器效果展示:
下面就是更為安全的method2方法獲取用戶信息了,即推薦使用?wx.getUserProfile?獲取用戶信息,開發(fā)者每次通過該接口獲取用戶個(gè)人信息均需用戶確認(rèn)。
1.3 method2
method2方式獲取用戶信息須經(jīng)用戶本人確認(rèn)才會(huì)獲取相應(yīng)信息,相對與method1方式來說給為安全。
把執(zhí)行方法改成true,如下:
模擬器展示效果如下:
二、小程序授權(quán)登錄
2.1 登錄過程
2.1.1 詳解
微信小程序的授權(quán)登錄過程通常包括以下幾個(gè)步驟:
-
小程序初始化: 在小程序初始化的時(shí)候,可以調(diào)用
wx.login
接口獲取臨時(shí)登錄憑證 code。這個(gè) code 的有效期很短,通常只有幾分鐘,所以需要在獲取到 code 后盡快使用。 -
將 code 發(fā)送到開發(fā)者服務(wù)器: 小程序前端通過網(wǎng)絡(luò)請求將獲取到的 code 發(fā)送到開發(fā)者服務(wù)器。
-
開發(fā)者服務(wù)器獲取 session_key 和 openid: 開發(fā)者服務(wù)器收到 code 后,可以將其發(fā)送到微信服務(wù)器的登錄憑證校驗(yàn)接口,換取 session_key 和 openid。session_key 是會(huì)話密鑰,用于加密數(shù)據(jù)傳輸,openid 是用戶在當(dāng)前小程序的唯一標(biāo)識。
-
校驗(yàn)登錄狀態(tài): 開發(fā)者服務(wù)器使用獲取到的 session_key 和 openid 創(chuàng)建一個(gè)用戶登錄態(tài),同時(shí)生成一個(gè)自定義的登錄態(tài)標(biāo)識,例如 token,并將這個(gè)標(biāo)識返回給小程序前端。
-
小程序前端存儲登錄態(tài): 小程序前端收到開發(fā)者服務(wù)器返回的登錄態(tài)標(biāo)識后,可以將它存儲在本地,一般存儲在緩存中。
-
后續(xù)請求攜帶登錄態(tài): 小程序前端在后續(xù)的網(wǎng)絡(luò)請求中,可以在請求的 header 中攜帶這個(gè)登錄態(tài)標(biāo)識,以表明當(dāng)前請求是一個(gè)已登錄用戶發(fā)起的。
需要注意的是,session_key 是敏感信息,不應(yīng)該暴露到小程序前端,而是應(yīng)該由開發(fā)者服務(wù)器進(jìn)行存儲和管理。微信小程序提供了相關(guān)的加解密 API,可以使用 session_key 對用戶數(shù)據(jù)進(jìn)行加解密,確保數(shù)據(jù)傳輸?shù)陌踩?。在?shí)際開發(fā)中,我們還需要處理登錄失敗、session 過期等異常情況,并且注意用戶隱私和數(shù)據(jù)安全。
2.1.2 圖解
2.2 后端代碼導(dǎo)入
?
2.3 前端代碼導(dǎo)入
2.4 案例演示
前端代碼如下:
2.4.1 前端調(diào)用接口地址
api.js:
// 以下是業(yè)務(wù)服務(wù)器API地址
// 本機(jī)開發(fā)API地址
var WxApiRoot = 'http://localhost:8080/oapro/wx/';
// 測試環(huán)境部署api地址
// var WxApiRoot = 'http://192.168.191.1:8080/oapro/wx/';
// 線上平臺api地址
//var WxApiRoot = 'https://www.oa-mini.com/demo/wx/';
module.exports = {
IndexUrl: WxApiRoot + 'home/index', //首頁數(shù)據(jù)接口
SwiperImgs: WxApiRoot+'swiperImgs',
MettingInfos: WxApiRoot+'meeting/list',
AuthLoginByWeixin: WxApiRoot + 'auth/login_by_weixin', //微信登錄
UserIndex: WxApiRoot + 'user/index', //個(gè)人頁面用戶相關(guān)信息
AuthLogout: WxApiRoot + 'auth/logout', //賬號登出
AuthBindPhone: WxApiRoot + 'auth/bindPhone' //綁定微信手機(jī)號
};
注意 :? ?需要對應(yīng)后臺的請求地址之后進(jìn)行數(shù)據(jù)的訪問。
2.4.2 個(gè)人中心
index.wxml:
<view class="page-container">
<view class="user-info-container">
<view class="user-info" bindtap="goLogin">
<image class="user-img" mode="scaleToFill" src="{{userInfo.avatarUrl}}" />
<text class="user-info-name">{{userInfo.nickName}}</text>
</view>
<image class="user-update" src="/static/tabBar/component.png" bindtap='goPages' data-url='/pages/ucenter/user/user'/>
</view>
<view class="boundary" />
<view class="cells-container">
<view class="cell-wrap">
<image class="cell-icon" src="/static/tabBar/sdk.png" />
<text class="cell-text">我主持的會(huì)議</text>
<view class="cell-right">
<view class="cell-list-num">{{metting_pubs}}</view>
<view class="cell-arrow"></view>
</view>
</view>
<view class="cell-wrap">
<image class="cell-icon" src="/static/tabBar/sdk.png" />
<text class="cell-text">我參與的會(huì)議</text>
<view class="cell-right">
<view class="cell-list-num">{{metting_joins}}</view>
<view class="cell-arrow"></view>
</view>
</view>
</view>
<view class="boundary" />
<view class="cells-container">
<view class="cell-wrap">
<image class="cell-icon" src="/static/tabBar/sdk.png" />
<text class="cell-text">我發(fā)布的投票</text>
<view class="cell-right">
<view class="cell-list-num">1</view>
<view class="cell-arrow"></view>
</view>
</view>
<view class="cell-wrap">
<image class="cell-icon" src="/static/tabBar/sdk.png" />
<text class="cell-text">我參與的投票</text>
<view class="cell-right">
<view class="cell-list-num">10</view>
<view class="cell-arrow"></view>
</view>
</view>
</view>
<view class="boundary" />
<view class="cells-container">
<view class="cell-wrap">
<image class="cell-icon" src="/static/tabBar/template.png" />
<text class="cell-text">消息</text>
<view class="cell-right">
<view class="cell-list-num"></view>
<view class="cell-arrow"></view>
</view>
</view>
<view class="cell-wrap">
<image class="cell-icon" src="/static/tabBar/component.png" />
<text class="cell-text">設(shè)置</text>
<view class="cell-right">
<view class="cell-list-num"></view>
<view class="cell-arrow"></view>
</view>
</view>
</view>
</view>
在index.js中編寫數(shù)據(jù)請求方法,如下:
index.js:
// pages/ucenter/index/index.js
var util = require('../../../utils/util.js');
var api = require('../../../config/api.js');
const app = getApp();
Page({
/**
* 頁面的初始數(shù)據(jù)
*/
data: {
userInfo: {
nickName: '點(diǎn)擊登錄',
avatarUrl: '/static/images/avatar.png'
},
hasLogin: false,
metting_pubs: '',
metting_joins: ''
},
/**
* 生命周期函數(shù)--監(jiān)聽頁面加載
*/
onLoad(options) {
},
/**
* 生命周期函數(shù)--監(jiān)聽頁面顯示
*/
onShow() {
this.getUserInfo();
},
getUserInfo() {
// console.log('ucenter.index.app.globalData.hasLogin='+app.globalData.hasLogin)
//獲取用戶的登錄信息
if (app.globalData.hasLogin) {
let userInfo = wx.getStorageSync('userInfo');
this.setData({
userInfo: userInfo,
hasLogin: true
});
//查詢個(gè)人統(tǒng)計(jì)信息
util.request(api.UserIndex).then(res => {
if (res.errno === 0) {
this.setData({
metting_pubs: res.data.metting_pubs,
metting_joins: res.data.metting_joins
});
}
});
}
},
goLogin() {
if (!this.data.hasLogin) {
wx.navigateTo({
url: "/pages/auth/login/login"
});
}
},
/**
* 頁面跳轉(zhuǎn)
*/
goPages: function (e) {
if (this.data.hasLogin) {
wx.navigateTo({
url: e.currentTarget.dataset.url
});
} else {
wx.navigateTo({
url: "/pages/auth/login/login"
});
};
}
})
創(chuàng)建一個(gè)用戶登入后的設(shè)置頁面為 : user。其中各頁面代碼如下:
user.js:
var util = require('../../../utils/util.js');
var api = require('../../../config/api.js');
var user = require('../../../utils/user.js');
var app = getApp();
Page({
/**
* 頁面的初始數(shù)據(jù)
*/
data: {
userInfo: {},
hasLogin: false,
userSharedUrl: ''
},
/**
* 生命周期函數(shù)--監(jiān)聽頁面加載
*/
onLoad: function (options) {
},
onShow: function () {
let that = this;
//獲取用戶的登錄信息
let userInfo = wx.getStorageSync('userInfo');
this.setData({
userInfo: userInfo,
hasLogin: true
});
},
getPhoneNumber: function (e) {
let that = this;
if (e.detail.errMsg !== "getPhoneNumber:ok") {
// 拒絕授權(quán)
return;
}
if (!this.data.hasLogin) {
wx.showToast({
title: '綁定失?。赫埾鹊卿?,
icon: 'none',
duration: 2000
});
return;
}
util.request(api.AuthBindPhone, {
iv: e.detail.iv,
encryptedData: e.detail.encryptedData
}, 'POST').then(function (res) {
if (res.errno === 0) {
let userInfo = wx.getStorageSync('userInfo');
userInfo.phone = res.data.phone;//設(shè)置手機(jī)號碼
wx.setStorageSync('userInfo', userInfo);
that.setData({
userInfo: userInfo,
hasLogin: true
});
wx.showToast({
title: '綁定手機(jī)號碼成功',
icon: 'success',
duration: 2000
});
}
});
},
exitLogin: function () {
wx.showModal({
title: '',
confirmColor: '#b4282d',
content: '退出登錄?',
success: function (res) {
if (!res.confirm) {
return;
}
util.request(api.AuthLogout, {}, 'POST');
app.globalData.hasLogin = false;
wx.removeStorageSync('token');
wx.removeStorageSync('userInfo');
wx.reLaunch({
url: '/pages/index/index'
});
}
})
}
})
user.wxml:
<!--pages/ucenter/user/user.wxml-->
<form bindsubmit="formSubmit">
<view class='personal-data'>
<view class='list'>
<view class='item acea-row row-between-wrapper'>
<view>頭像</view>
<view class='pictrue'>
<image src='{{userInfo.avatarUrl}}'></image>
</view>
</view>
<view class='item acea-row row-between-wrapper'>
<view>名字</view>
<view class='input'><input type='text' disabled='true' name='nickname' value='{{userInfo.nickName}}'></input></view>
</view>
<view class='item acea-row row-between-wrapper'>
<view>手機(jī)號碼</view>
<button name='phone' class='phone' value='{{userInfo.phone}}' wx:if="{{!userInfo.phone}}" bindgetphonenumber="getPhoneNumber" hover-class='none' open-type='getPhoneNumber'>
點(diǎn)擊獲取
</button>
<view class='input acea-row row-between-wrapper' wx:else>
<input type='text' disabled='true' name='phone' value='{{userInfo.phone}}' class='id'></input>
<text class='iconfont icon-suozi'></text>
</view>
</view>
<view class='item acea-row row-between-wrapper'>
<view>ID號</view>
<view class='input acea-row row-between-wrapper'>
<input type='text' value='1000{{userInfo.userId}}' disabled='true' class='id'></input>
<text class='iconfont icon-suozi'></text>
</view>
</view>
</view>
<button class='modifyBnt' bindtap="exitLogin">退 出</button>
</view>
</form>
user.wxss:
@import '/static/font/iconfont.wxss';
.personal-data .list {
margin-top: 15rpx;
background-color: #fff;
}
.personal-data .list .item {
padding: 30rpx 30rpx 30rpx 0;
border-bottom: 1rpx solid #f2f2f2;
margin-left: 30rpx;
font-size: 32rpx;
color: #282828;
}
.personal-data .list .item .phone {
background-color: #85c43f;
width: 160rpx;
height: 56rpx;
font-size: 24rpx;
color: #fff;
line-height: 56rpx;
border-radius: 32rpx
}
.personal-data .list .item .pictrue {
width: 88rpx;
height: 88rpx;
}
.personal-data .list .item .pictrue image {
width: 100%;
height: 100%;
border-radius: 50%;
}
.personal-data .list .item .input {
width: 415rpx;
text-align: right;
color: #868686;
}
.personal-data .list .item .input .id {
width: 365rpx;
}
.personal-data .list .item .input .iconfont {
font-size: 35rpx;
}
.personal-data .modifyBnt {
/* background-color: #85c43f; */
/* background: linear-gradient(to left right, #85c43f, #fefefd); */
background: radial-gradient(circle at 50%,#85c43f,#CDDC39);
font-size: 32rpx;
color: #fff;
width: 690rpx;
height: 90rpx;
border-radius: 50rpx;
display: flex;
justify-content: center;
align-items: center;
line-height: 90rpx;
margin: 76rpx auto 0 auto;
}
.acea-row{display:flex;flex-wrap:wrap;}
.acea-row.row-top{align-items:flex-start;}
.acea-row.row-middle{align-items:center;}
.acea-row.row-bottom{align-items:flex-end;}
.acea-row.row-left{justify-content:flex-start;}
.acea-row.row-center{justify-content:center;}
.acea-row.row-right{justify-content:flex-end;}
.acea-row.row-between{justify-content:space-between;}
.acea-row.row-around{justify-content:space-around;}
.acea-row.row-column{flex-direction:column;}
.acea-row.row-column-between{flex-direction:column;justify-content:space-between;}
.acea-row.row-column-around{flex-direction:column;justify-content:space-around;}
.acea-row.row-center-wrapper{align-items:center;justify-content:center;}
.acea-row.row-between-wrapper{align-items:center;justify-content:space-between;}
view, image, text, navigator {
box-sizing: border-box;
padding: 0;
margin: 0;
}
后端代碼如下:
在后臺編寫的控制器,來進(jìn)行出來前端的請求及數(shù)據(jù)處理并且反饋帶前端
WxAuthController :?
package com.zking.ssm.wxcontroller;
/**
* @Autho donkee
* @Since 2022/6/27
*/
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import com.alibaba.fastjson.JSONObject;
import com.zking.ssm.annotation.LoginUser;
import com.zking.ssm.model.UserInfo;
import com.zking.ssm.model.WxLoginInfo;
import com.zking.ssm.model.WxUser;
import com.zking.ssm.service.UserToken;
import com.zking.ssm.service.UserTokenManager;
import com.zking.ssm.service.WxUserService;
import com.zking.ssm.util.JacksonUtil;
import com.zking.ssm.util.ResponseUtil;
import com.zking.ssm.util.UserTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import javax.servlet.http.HttpServletRequest;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* 鑒權(quán)服務(wù)
*/
@Slf4j
@RestController
@RequestMapping("/wx/auth")
public class WxAuthController {
@Autowired
private WxMaService wxService;
@Autowired
private WxUserService userService;
/**
* 微信登錄
*
* @param wxLoginInfo
* 請求內(nèi)容,{ code: xxx, userInfo: xxx }
* @param request
* 請求對象
* @return 登錄結(jié)果
*/
@PostMapping("login_by_weixin")
public Object loginByWeixin(@RequestBody WxLoginInfo wxLoginInfo, HttpServletRequest request) {
//客戶端需攜帶code與userInfo信息
String code = wxLoginInfo.getCode();
UserInfo userInfo = wxLoginInfo.getUserInfo();
if (code == null || userInfo == null) {
return ResponseUtil.badArgument();
}
//調(diào)用微信sdk獲取openId及sessionKey
String sessionKey = null;
String openId = null;
try {
long beginTime = System.currentTimeMillis();
//
WxMaJscode2SessionResult result = this.wxService.getUserService().getSessionInfo(code);
// Thread.sleep(6000);
long endTime = System.currentTimeMillis();
log.info("響應(yīng)時(shí)間:{}",(endTime-beginTime));
sessionKey = result.getSessionKey();//session id
openId = result.getOpenid();//用戶唯一標(biāo)識 OpenID
} catch (Exception e) {
e.printStackTrace();
}
if (sessionKey == null || openId == null) {
log.error("微信登錄,調(diào)用官方接口失?。簕}", code);
return ResponseUtil.fail();
}else{
log.info("openId={},sessionKey={}",openId,sessionKey);
}
//根據(jù)openId查詢wx_user表
//如果不存在,初始化wx_user,并保存到數(shù)據(jù)庫中
//如果存在,更新最后登錄時(shí)間
WxUser user = userService.queryByOid(openId);
if (user == null) {
user = new WxUser();
user.setUsername(openId);
user.setPassword(openId);
user.setWeixinOpenid(openId);
user.setAvatar(userInfo.getAvatarUrl());
user.setNickname(userInfo.getNickName());
user.setGender(userInfo.getGender());
user.setUserLevel((byte) 0);
user.setStatus((byte) 0);
user.setLastLoginTime(new Date());
user.setLastLoginIp(IpUtil.client(request));
user.setShareUserId(1);
userService.add(user);
} else {
user.setLastLoginTime(new Date());
user.setLastLoginIp(IpUtil.client(request));
if (userService.updateById(user) == 0) {
log.error("修改失?。簕}", user);
return ResponseUtil.updatedDataFailed();
}
}
// token
UserToken userToken = null;
try {
userToken = UserTokenManager.generateToken(user.getId());
} catch (Exception e) {
log.error("微信登錄失敗,生成token失敗:{}", user.getId());
e.printStackTrace();
return ResponseUtil.fail();
}
userToken.setSessionKey(sessionKey);
log.info("SessionKey={}",UserTokenManager.getSessionKey(user.getId()));
Map<Object, Object> result = new HashMap<Object, Object>();
result.put("token", userToken.getToken());
result.put("tokenExpire", userToken.getExpireTime().toString());
userInfo.setUserId(user.getId());
if (!StringUtils.isEmpty(user.getMobile())) {// 手機(jī)號存在則設(shè)置
userInfo.setPhone(user.getMobile());
}
try {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String registerDate = df.format(user.getAddTime() != null ? user.getAddTime() : new Date());
userInfo.setRegisterDate(registerDate);
userInfo.setStatus(user.getStatus());
userInfo.setUserLevel(user.getUserLevel());// 用戶層級
userInfo.setUserLevelDesc(UserTypeEnum.getInstance(user.getUserLevel()).getDesc());// 用戶層級描述
} catch (Exception e) {
log.error("微信登錄:設(shè)置用戶指定信息出錯(cuò):"+e.getMessage());
e.printStackTrace();
}
result.put("userInfo", userInfo);
log.info("【請求結(jié)束】微信登錄,響應(yīng)結(jié)果:{}", JSONObject.toJSONString(result));
return ResponseUtil.ok(result);
}
/**
* 綁定手機(jī)號碼
*
* @param userId
* @param body
* @return
*/
@PostMapping("bindPhone")
public Object bindPhone(@LoginUser Integer userId, @RequestBody String body) {
log.info("【請求開始】綁定手機(jī)號碼,請求參數(shù),body:{}", body);
String sessionKey = UserTokenManager.getSessionKey(userId);
String encryptedData = JacksonUtil.parseString(body, "encryptedData");
String iv = JacksonUtil.parseString(body, "iv");
WxMaPhoneNumberInfo phoneNumberInfo = null;
try {
phoneNumberInfo = this.wxService.getUserService().getPhoneNoInfo(sessionKey, encryptedData, iv);
} catch (Exception e) {
log.error("綁定手機(jī)號碼失敗,獲取微信綁定的手機(jī)號碼出錯(cuò):{}", body);
e.printStackTrace();
return ResponseUtil.fail();
}
String phone = phoneNumberInfo.getPhoneNumber();
WxUser user = userService.selectByPrimaryKey(userId);
user.setMobile(phone);
if (userService.updateById(user) == 0) {
log.error("綁定手機(jī)號碼,更新用戶信息出錯(cuò),id:{}", user.getId());
return ResponseUtil.updatedDataFailed();
}
Map<Object, Object> data = new HashMap<Object, Object>();
data.put("phone", phone);
log.info("【請求結(jié)束】綁定手機(jī)號碼,響應(yīng)結(jié)果:{}", JSONObject.toJSONString(data));
return ResponseUtil.ok(data);
}
/**
* 注銷登錄
*/
@PostMapping("logout")
public Object logout(@LoginUser Integer userId) {
log.info("【請求開始】注銷登錄,請求參數(shù),userId:{}", userId);
if (userId == null) {
return ResponseUtil.unlogin();
}
try {
UserTokenManager.removeToken(userId);
} catch (Exception e) {
log.error("注銷登錄出錯(cuò):userId:{}", userId);
e.printStackTrace();
return ResponseUtil.fail();
}
log.info("【請求結(jié)束】注銷登錄成功!");
return ResponseUtil.ok();
}
}
在?application.yml?文件中進(jìn)行配置后臺的數(shù)據(jù)庫及微信小程序的AppID(小程序ID)及AppSecret(小程序密鑰),來幫助訪問微信的接口服務(wù)。
2.5 效果演示?
最后后臺開啟服務(wù),在前端進(jìn)行數(shù)據(jù)訪問及微信授權(quán)登入,如下:
?最后微信小程序進(jìn)階——后臺交互個(gè)人中心授權(quán)登錄就到這里,祝大家在敲代碼的路上一路通暢!
感謝大家的觀看 !
文章來源:http://www.zghlxwxcb.cn/news/detail-785866.html
?
到了這里,關(guān)于微信小程序進(jìn)階——后臺交互個(gè)人中心授權(quán)登錄的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!