目录
一、方达易充用户信息登录
index.wxml
<view class="content">
<view class="view_head_img">
<image class="head_img" src="{{ siteInfo.mini_logo }}"></image>
</view>
<view class="title">{{ siteInfo.mini_name }}</view>
<view class="hr"></view>
<block wx:if="{{ bindPhone }}">
<view class="sectitle">请同意授权您的手机号码</view>
<view class="sectitle2">· 以便{{ siteInfo.mini_name }}为你提供充电桩更好的服务</view>
<view class="margin-top padding flex">
<button open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber" class="flex-sub cu-btn round bg-olive lg">确认授权手机号码</button>
</view>
</block>
<block wx:else>
<view class="sectitle">请同意授权用户信息</view>
<view class="sectitle2">· 以便{{ siteInfo.mini_name }}为你提供充电桩更好的服务</view>
<view class="margin-top padding flex">
<button class="flex-sub cu-btn round bg-olive lg" bindtap="getUserProfile" wx:if="{{canIUseGetUserProfile}}">确认授权用户信息</button>
<button class="flex-sub cu-btn round bg-olive lg" open-type="getUserInfo" bindgetuserinfo="onGetAuthorize" wx:else>确认授权用户信息</button>
</view>
<view class="padding flex">
<button class="flex-sub cu-btn round line-gray lg" bindtap="toHome">取消授权</button>
</view>
</block>
</view>
index.js
data: {
siteInfo: '',
bindPhone:false,
},
onLoad(options) {
let that = this;
that.setData({
siteInfo: app.globalData.siteInfo,
canIUseGetUserProfile: wx.getUserProfile ? true: false,
})
console.log(that.data.canIUseGetUserProfile);
setTimeout(() => {
that.getCode()
}, 1000)
// wx.showLoading({
// title: '正在登陆~',
// mask: true
// })
wx.login({
success(res) {
console.log('登录成功!',res)
that.setData({
loginCode: res.code
})
app.get('wxapi/login', {
code: res.code,
login_type: 1
}).then(res => {
console.log('@@@@@ 登录接口成功',res)
console.log(res.user_id, res.mobile)
if (res.user_id && res.mobile){
wx.setStorageSync('open_id', res.open_id)
wx.setStorageSync('user_id', res.user_id)
wx.setStorageSync('token', res.token)
wx.showToast({
type: 'success',
title: '登陆成功'
});
that.getInfo()
} else {
setTimeout(() => {
that.getCode()
}, 1000)
wx.hideLoading()
}
})
}
})
},
/**
* 获取用户信息
*/
getUserProfile(e) {
let that = this
// 推荐使用wx.getUserProfile获取用户信息,开发者每次通过该接口获取用户个人信息均需用户确认
wx.getUserProfile({
desc: '用于完善您的个人信息', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
success: (res) => {
that.setData({
encryptedData: encodeURIComponent(res.encryptedData),
iv: res.iv,
bindPhone:app.globalData.siteInfo.register_user_moblie_wx == 1
},()=>{
console.log(that.data.bindPhone)
if (!that.data.bindPhone) {
that.byUserLogin(res)
}
})
},
fail(){
wx.showModal({
title: 'Sorry',
content: '很遗憾,授权失败或您拒绝了微信授权',
showCancel: false,
success(res) {
if (res.confirm) {
wx.redirectTo({
url: '/pages/index/index'
})
}
}
})
}
})
},
byUserLogin(e){
console.log(e)
let that = this
that.getNum = that.getNum || 0
if (e.errMsg == 'getUserProfile:ok') {
wx.showLoading({
title: '登录中~~~',
mask: true
})
app.get('wxapi/login', {
code: that.data.loginCode,
encryptedData: that.data.encryptedData,
iv: that.data.iv,
login_type: 2,
otherCode: true
}).then(data => {
console.log(data)
if(data.code == 0){
wx.hideLoading()
let res = data.data
wx.setStorageSync('open_id', res.open_id);
wx.setStorageSync('user_id', res.user_id);
wx.setStorageSync('token', res.token);
wx.showToast({
type: 'success',
title: '授权成功'
})
that.getInfo()
} else if (data.code == 3){
that.getNum++
if (that.getNum >= 3){
wx.reLaunch({
url: '/pages/index/index'
})
}else{
that.getCode().then(cres => {
that.byUserLogin()
}).catch(err => {
that.getCode()
})
}
} else {
wx.hideLoading()
wx.showToast({
icon: 'none',
title: data.msg,
duration: 3000
})
}
})
} else {
wx.showModal({
title: 'Sorry',
content: '很遗憾,您拒绝了微信授权,宝宝很伤心',
showCancel: false,
success(res) {
if (res.confirm) {
wx.redirectTo({
url: '/pages/index/index'
})
}
}
})
}
},
wxss
page{
background: var(--white)
}
.view_head_img {
text-align: center;
margin-bottom: 10rpx;
position: relative;
margin-top: 50px;
}
.head_img {
border: 0 solid #ff0000;
border-radius: 100rpx;
width: 200rpx;
height: 200rpx;
}
.title {
text-align: center;
font-weight: bold;
}
.hr {
width: 80%;
height: 1px;
background: #888;
margin-top: 20px;
margin-left: 30px;
}
.sectitle {
margin-left: 30px;
margin-top: 20px;
font-weight: bold;
font-size: 16px;
}
.sectitle2 {
margin-left: 30px;
margin-top: 20px;
font-size: 16px;
}
.btn {
margin: 20px auto;
width: 80%;
}
二、方达智充的登录
第二个获取token的接口
{"success":true,"code":20000,"message":"成功","data":{"jwt":{"access_token":"eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsiYnVzaW5lc3NTZXJ2aWNlIiwibWFjU2VydmljZSJdLCJleHAiOjE2OTMxMzI0NDIsInVzZXJfbmFtZSI6IntcImFjY291bnRcIjpcIm9LM1h2NUFIRzd5S0NfTkJja2tiaURUVVczSUFcIixcImFjY291bnRUeXBlXCI6MixcImZ1bGxuYW1lXCI6XCJ1bmRlZmluZWRcIixcImlkXCI6MTUzOSxcIm1hbmFnZVwiOmZhbHNlLFwibWVyY2hhbnRcIjpmYWxzZX0iLCJqdGkiOiJjM2QyMDJjNS02YjM3LTQ3YmUtYTFjYy04MGRlM2U3Yzc1NDgiLCJjbGllbnRfaWQiOiJidXNpbmVzc1NlcnZpY2UiLCJzY29wZSI6WyJidXNpbmVzc1NlcnZpY2UiLCJtYWNTZXJ2aWNlIl19.XBFRcq_TOqmQCYiy9f-zzGCmBddEK5PoMkJ67BZHuHtC67Er6vSIr0Y-m9M5Dh3vLAYHLLKT5l3L0puD2f9u-pWUyHLjyTyR1WCAdU5OEvdHbS-8rsDuipioLE3nPAvEEwBVL8TIxi9CtEUnPTbacZA9qTeb5Ri0M8Q4xxBHLwEcxpbfBZp1xYVKGBntD5kzx7577oJk8_-E1fPeEicPgRmyJbl4fIs1wV6_-vajz5uTyL0xHe1iZKwx7CPXmPIPNmGomutJL-6uCWhwJbtyGT62lqQnwRezYI-CdgLkoiLSOb9xp3SX7joPicOVknmXkwlG02M2jIgp7Wl0x4IUzA","token_type":"bearer","expires_in":86399,"scope":"businessService macService","jti":"c3d202c5-6b37-47be-a1cc-80de3e7c7548"}}}
第三获取电话号码
<view class="loginContainer">
<view style="display: flex; flex-direction: column; justify-content: center; align-items: center;">
<image src="../../imgs/cd.png" style="width: 300rpx; height: 220rpx;margin-bottom: 50px;"></image>
<button open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber" style="border-radius: 20px; background-color: white;color: 02112F;">手机号快捷登录</button>
<label style="color: #999999; font-size: 12px; margin-top: 10px;">登录后将回到原来的界面,请继续原来操作</label>
</view>
</view>
.loginContainer {
height: 100vmax;
width: 100%;
justify-content: center;
display: flex;
align-items: center;
background-color: #02112F;
}
onShow() {
let that = this
that.codeToSession()
},
codeToSession() {
let that = this
wx.login({
success: (res) => {
wx.request({
url: codeToSession,
method: "GET",
data: {
code: res.code
},
header: {
'content-type': 'application/x-www-form-urlencoded'
},
success: (res) => {
wx.setStorageSync('userInfo2', res.data.data.data);
console.log('userInfo2', res.data.data.data);
let logoPath = wx.getStorageSync('logoPath');
that.setData({
logoPath: logoPath,
item: wx.getStorageSync('logoPath'),
})
}
})
}
})
},
getPhoneNumber: (e) => {
wx.setStorageSync('userInfo3', e.detail)
wx.login({
success: (res) => {
wx.showLoading({
title: "正在登录...",
mask: true
})
let code = res.code;
getJWtFromServerByCode(code);
}
})
}
function getJWtFromServerByCode(_code) {
wx.request({
url: getJWtFromServerByCodeUrl,
data: {
'code': _code,
'client_secret': client_secret,
'client_id': client_id
},
method: "GET",
dataType: "json",
success: (res) => {
wx.hideLoading();
if (res.data.code === 20000) {
let jwt = res.data.data.jwt;
if (jwt != null) {
var timestamp = Date.parse(new Date());
let data = {
'jwt': jwt.access_token,
'session_key': jwt.session_key,
'time': timestamp
}
wx.setStorageSync('jwt', data);
//返回上一页
wx.navigateBack();
wx.getUserInfo({
success: (res) => {
wx.setStorageSync('userInfo', res.userInfo)
updateUserProfile();
},
fail: (res) => {
// 用户未授权,请提示用户授权后重试
}
});
// 返回上一页
wx.navigateBack();
www();
}
} else {
console.log("code!==20000 res:" + JSON.stringify(res))
}
},
fail: (err) => {
wx.hideLoading();
console.log("getJWtFromServerByCode err" + JSON.stringify(err))
}
});
}
// 向后端API发送用户信息和JWT
function updateUserProfile() {
const {
encryptedData,
iv
} = wx.getStorageSync('userInfo3')
const {
session_key
} = wx.getStorageSync('userInfo2')
const {
avatar,
fullName
} = wx.getStorageSync('userInfo')
const {
jwt
} = wx.getStorageSync('jwt');
let requestParams = {
avatar: avatar,
fullName: fullName,
phoneEncryptedData: encryptedData, // 电话号码加密数据
phoneIv: iv, // 电话号码加密向量
sessionKey: session_key // 添加 session_key 参数
};
console.log("one", requestParams);
wx.request({
url: setMeInfo,
method: "POST",
data: requestParams,
header: {
"authorization": "bearer" + jwt,
'content-type': 'application/x-www-form-urlencoded',
// 'sessionKey': session_key // 将 session_key 添加到请求头中
},
success: function (res) {
console.log("请求成功", res)
let logoPath = wx.getStorageSync('logoPath');
that.setData({
logoPath: logoPath,
item: wx.getStorageSync('logoPath'),
})
},
fail: function (err) {
console.error("请求失败", err)
}
});
}
//订阅信息
function www() {
let that = this
let access_token = getJwt();
wx.request({
url: getWechatNoticeTemplateList,
method: "GET",
data: {},
header: {
"authorization": "bearer" + access_token,
'content-type': 'application/x-www-form-urlencoded'
},
success: function (res) {
let data =res.data.data.data.data
let tmplIds =[];
for (let i = 0; i < data.length; i++) {
tmplIds.push(data[i].priTmplId)
}
wx.getSetting({
withSubscriptions: true, // 这里设置为true,下面才会返回mainSwitch
success: function (res) {
// 调起授权界面弹窗
if (res.subscriptionsSetting.mainSwitch) { // 用户打开了订阅消息总开关
// 每次执到这都会拉起授权弹窗
wx.showModal({
title: '提示',
content: '请授权开通服务通知',
showCancel: true,
success: function (ress) {
if (ress.confirm) {
// console.log('用户点击确定')
wx.requestSubscribeMessage({ // 调起消息订阅界面
tmplIds: tmplIds,
success(res) {
console.log('订阅消息 成功 ');
for (var tmplId in res) {
console.log(tmplId + ': ' + res[tmplId]);
}
wx.showLoading({
title:"订阅消息成功",
icon:"none",
duration: 500
})
},
fail(er) {
console.log("订阅消息 失败 ");
// console.log(er);
}
})
} else if (ress.cancel) {
// console.log('用户点击取消')
}
}
})
} else {
console.log('订阅消息未开启')
}
},
fail: function (error) {
console.log(error);
}
})
},
fail: (err) => {
wx.hideLoading()
wx.showToast({
title: "服务器忙",
icon: 'none'
})
}
})
}
三、账号和密码登录
<view class="container">
<view class="logo">Logo</view>
<button bindtap="showLoginPopup">点击登录</button>
<!-- 弹出框 -->
<view wx:if="{{showPopup}}" class="popup">
<input placeholder="用户名" bindinput="inputUsername" />
<input type="password" placeholder="密码" bindinput="inputPassword" />
<button bindtap="login">登录</button>
<button bindtap="hideLoginPopup">关闭</button>
</view>
</view>
// login.js
Page({
data: {
showPopup: false,
username: '',
password: ''
},
// 显示登录弹出框
showLoginPopup() {
this.setData({
showPopup: true
});
},
// 隐藏登录弹出框
hideLoginPopup() {
this.setData({
showPopup: false
});
},
// 输入用户名
inputUsername(event) {
this.setData({
username: event.detail.value
});
},
// 输入密码
inputPassword(event) {
this.setData({
password: event.detail.value
});
},
// 登录
login() {
const { username, password } = this.data;
// 检查用户名和密码是否为空
if (!username || !password) {
wx.showToast({
title: '请输入用户名和密码',
icon: 'none'
});
return;
}
// 发送登录请求到后端服务器
// 请替换以下示例中的 URL 和请求方式
wx.request({
url: 'https://your-api-url.com/login', // 替换成实际的登录接口地址
method: 'POST',
data: {
username: this.data.username,
password: this.data.password
},
success: (res) => {
if (res.data.success) {
// 登录成功,保存用户信息,通常是用户令牌
wx.setStorageSync('token', res.data.token);
// 关闭弹出框
this.hideLoginPopup();
// 跳转到其他页面,例如用户主页
wx.navigateTo({
url: '/pages/home/home'
});
} else {
// 登录失败,显示错误消息
wx.showToast({
title: '登录失败,请检查用户名和密码',
icon: 'none'
});
}
},
fail: (error) => {
// 处理登录请求失败
wx.showToast({
title: '登录请求失败,请重试',
icon: 'none'
});
}
});
}
});
/* login.wxss */
.container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
}
.logo {
font-size: 24px;
margin-bottom: 20px;
}
button {
background-color: #007acc;
color: #fff;
padding: 10px 20px;
border: none;
border-radius: 4px;
cursor: pointer;
}
.popup {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: #fff;
padding: 20px;
border: 1px solid #ccc;
border-radius: 4px;
}