绵阳的网站制作公司哪家好,营销网站建设一薇,wordpress怎样给目录增加,恶意点击推广神器在我们的完成微信登入授权之前#xff0c;首先我们要完成我们前面所写的代码#xff0c;如果有不会的大家可以去看以下我发的前面几个文章链接我发下面了#xff0c;各位加油#xff01;
微信小程序OA会议系统数据交互-CSDN博客
微信小程序会议OA系统其他页面-CSDN博客
…在我们的完成微信登入授权之前首先我们要完成我们前面所写的代码如果有不会的大家可以去看以下我发的前面几个文章链接我发下面了各位加油
微信小程序OA会议系统数据交互-CSDN博客
微信小程序会议OA系统其他页面-CSDN博客
微信小程序会议OA系统-CSDN博客 如果链接失效了大家可以去看我的首页首页中有哦
在我们的OA项目中我们开始写这个项目我们首先要理解如何去做我们的思路要理清
图片解析 微信小程序登录微信登录接口演示
在我们开始之前在我们的微信小程序端选择好我们要的项目 进行导入 选择我们的微信小程序要的项目 method01
method1方法获取用户信息存在一定风险并不安全所以把执行方法改成false 模拟器效果图片 method02
method2方式获取用户信息须经用户本人确认才会获取相应信息相对与method1方式来说给为安全。 小程序授权登录 登录过程
详解
微信小程序授权登录过程如下 小程序发起登录请求调用 wx.login() 方法。 微信服务器返回 code小程序将该 code 作为参数调用 wx.request() 方法向开发者服务器发起请求获取用户信息。 开发者服务器收到请求后在后台调用微信提供的 API获取 session_key 和 openid。 开发者服务器根据获取的 session_key 和 openid生成自己的登录态如 token、cookie 等并将其返回给小程序。 小程序将登录态保存在本地作为用户的唯一标识在后续的请求中携带该登录态向开发者服务器请求数据。
需要注意的是用户授权登录流程需要在小程序端进行而后续的获取用户信息和生成登录态等操作则需要在开发者服务器端进行。同时在进行用户授权的过程中需要先调用 wx.getSetting() 方法获取用户是否授权的权限信息再根据用户授权情况进行后续操作。
后端代码导入 前端代码导入 前端代码
前端调用的接口地址
api.js
// 以下是业务服务器API地址// 本机开发API地址
var WxApiRoot http://localhost:8080/oapro/wx/;
// 测试环境部署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, //首页数据接口SwiperImgs: WxApiRootswiperImgs,MettingInfos: WxApiRootmeeting/list,AuthLoginByWeixin: WxApiRoot auth/login_by_weixin, //微信登录UserIndex: WxApiRoot user/index, //个人页面用户相关信息AuthLogout: WxApiRoot auth/logout, //账号登出AuthBindPhone: WxApiRoot auth/bindPhone //绑定微信手机号
};
个人中心
index.wxml
view classpage-containerview classuser-info-containerview classuser-info bindtapgoLoginimage classuser-img modescaleToFill src{{userInfo.avatarUrl}} /text classuser-info-name{{userInfo.nickName}}/text/viewimage classuser-update src/static/tabBar/component.png bindtapgoPages data-url/pages/ucenter/user/user//viewview classboundary /view classcells-containerview classcell-wrapimage classcell-icon src/static/tabBar/sdk.png /text classcell-text我主持的会议/textview classcell-rightview classcell-list-num{{metting_pubs}}/viewview classcell-arrow/view/view/viewview classcell-wrapimage classcell-icon src/static/tabBar/sdk.png /text classcell-text我参与的会议/textview classcell-rightview classcell-list-num{{metting_joins}}/viewview classcell-arrow/view/view/view/viewview classboundary /view classcells-containerview classcell-wrapimage classcell-icon src/static/tabBar/sdk.png /text classcell-text我发布的投票/textview classcell-rightview classcell-list-num1/viewview classcell-arrow/view/view/viewview classcell-wrapimage classcell-icon src/static/tabBar/sdk.png /text classcell-text我参与的投票/textview classcell-rightview classcell-list-num10/viewview classcell-arrow/view/view/view/viewview classboundary /view classcells-containerview classcell-wrapimage classcell-icon src/static/tabBar/template.png /text classcell-text消息/textview classcell-rightview classcell-list-num/viewview classcell-arrow/view/view/viewview classcell-wrapimage classcell-icon src/static/tabBar/component.png /text classcell-text设置/textview classcell-rightview classcell-list-num/viewview classcell-arrow/view/view/view/view
/view
index.js
// pages/ucenter/index/index.js
var util require(../../../utils/util.js);
var api require(../../../config/api.js);
const app getApp();
Page({/*** 页面的初始数据*/data: {userInfo: {nickName: 点击登录,avatarUrl: /static/images/avatar.png},hasLogin: false,metting_pubs: ,metting_joins: },/*** 生命周期函数--监听页面加载*/onLoad(options) {},/*** 生命周期函数--监听页面显示*/onShow() {this.getUserInfo();},getUserInfo() {// console.log(ucenter.index.app.globalData.hasLoginapp.globalData.hasLogin)//获取用户的登录信息if (app.globalData.hasLogin) {let userInfo wx.getStorageSync(userInfo);this.setData({userInfo: userInfo,hasLogin: true});//查询个人统计信息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});}},/*** 页面跳转*/goPages: function (e) {if (this.data.hasLogin) {wx.navigateTo({url: e.currentTarget.dataset.url});} else {wx.navigateTo({url: /pages/auth/login/login});};}})
user.js
var util require(../../../utils/util.js);
var api require(../../../config/api.js);
var user require(../../../utils/user.js);
var app getApp();
Page({/*** 页面的初始数据*/data: {userInfo: {},hasLogin: false,userSharedUrl: },/*** 生命周期函数--监听页面加载*/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) {// 拒绝授权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;//设置手机号码wx.setStorageSync(userInfo, userInfo);that.setData({userInfo: userInfo,hasLogin: true});wx.showToast({title: 绑定手机号码成功,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.wxmI
!--pages/ucenter/user/user.wxml--
form bindsubmitformSubmitview classpersonal-dataview classlistview classitem acea-row row-between-wrapperview头像/viewview classpictrueimage src{{userInfo.avatarUrl}}/image/view/viewview classitem acea-row row-between-wrapperview名字/viewview classinputinput typetext disabledtrue namenickname value{{userInfo.nickName}}/input/view/viewview classitem acea-row row-between-wrapperview手机号码/viewbutton namephone classphone value{{userInfo.phone}} wx:if{{!userInfo.phone}} bindgetphonenumbergetPhoneNumber hover-classnone open-typegetPhoneNumber点击获取/buttonview classinput acea-row row-between-wrapper wx:elseinput typetext disabledtrue namephone value{{userInfo.phone}} classid/inputtext classiconfont icon-suozi/text/view/viewview classitem acea-row row-between-wrapperviewID号/viewview classinput acea-row row-between-wrapperinput typetext value1000{{userInfo.userId}} disabledtrue classid/inputtext classiconfont icon-suozi/text/view/view/viewbutton classmodifyBnt bindtapexitLogin退 出/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;
}
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;/*** 鉴权服务*/
Slf4j
RestController
RequestMapping(/wx/auth)
public class WxAuthController {Autowiredprivate WxMaService wxService;Autowiredprivate WxUserService userService;/*** 微信登录** param wxLoginInfo* 请求内容{ code: xxx, userInfo: xxx }* param request* 请求对象* return 登录结果*/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();}//调用微信sdk获取openId及sessionKeyString 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(响应时间:{},(endTime-beginTime));sessionKey result.getSessionKey();//session idopenId result.getOpenid();//用户唯一标识 OpenID} catch (Exception e) {e.printStackTrace();}if (sessionKey null || openId null) {log.error(微信登录,调用官方接口失败{}, code);return ResponseUtil.fail();}else{log.info(openId{},sessionKey{},openId,sessionKey);}//根据openId查询wx_user表//如果不存在初始化wx_user,并保存到数据库中//如果存在更新最后登录时间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();}}// tokenUserToken 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()));MapObject, Object result new HashMapObject, Object();result.put(token, userToken.getToken());result.put(tokenExpire, userToken.getExpireTime().toString());userInfo.setUserId(user.getId());if (!StringUtils.isEmpty(user.getMobile())) {// 手机号存在则设置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(微信登录设置用户指定信息出错e.getMessage());e.printStackTrace();}result.put(userInfo, userInfo);log.info(【请求结束】微信登录,响应结果:{}, JSONObject.toJSONString(result));return ResponseUtil.ok(result);}/*** 绑定手机号码** param userId* param body* return*/PostMapping(bindPhone)public Object bindPhone(LoginUser Integer userId, RequestBody String body) {log.info(【请求开始】绑定手机号码,请求参数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(绑定手机号码失败,获取微信绑定的手机号码出错{}, 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(绑定手机号码,更新用户信息出错,id{}, user.getId());return ResponseUtil.updatedDataFailed();}MapObject, Object data new HashMapObject, Object();data.put(phone, phone);log.info(【请求结束】绑定手机号码,响应结果{}, JSONObject.toJSONString(data));return ResponseUtil.ok(data);}/*** 注销登录*/PostMapping(logout)public Object logout(LoginUser Integer userId) {log.info(【请求开始】注销登录,请求参数userId:{}, userId);if (userId null) {return ResponseUtil.unlogin();}try {UserTokenManager.removeToken(userId);} catch (Exception e) {log.error(注销登录出错userId:{}, userId);e.printStackTrace();return ResponseUtil.fail();}log.info(【请求结束】注销登录成功!);return ResponseUtil.ok();}
}
在 application.yml 文件中进行配置后台的数据库及微信小程序的AppID(小程序ID)及AppSecret(小程序密钥)来帮助访问微信的接口服务。