现成代码块(拿来即用)
- 模板结构
<template> <view class="content"> <image class="logo" src="/static/logo.png"></image> <view class="text-area"> <text class="title">{{title}}</text> </view> <view class=""> <button v-if="canIUseGetUserProfile" type="default" lang="zh_CN" @click="getUserProfile">新版登录</button> <button v-else style="margin-bottom: 20px;" type="primary" lang="zh_CN" open-type="getUserInfo" @getuserinfo="bindgetuserinfo">旧版登录</button> </view> </view> </template>
- script部分
<script> export default { data() { return { title: 'Hello', canIUseGetUserProfile: false } }, onLoad() { // 如果存在就是支持新版登录方式 if (wx.getUserProfile) { this.canIUseGetUserProfile = true } }, methods: { // 旧版登录方式 bindgetuserinfo(e) { if (e.detail.userInfo) { console.log(e.detail.userInfo); uni.showLoading({ title: '用户登录中' }) this.WXLiginCode(e.detail.userInfo) uni.hideLoading() } else { // 可以给失败提示 } }, // 新版微信授权 getUserProfile() { uni.getUserProfile({ lang: 'zh_CN', desc: '用于获取个人信息', success: (res) => { console.log(res); if (res.userInfo) { uni.showToast({ title: '获取用户信息成功', icon: 'success' }) this.WXLiginCode(res.userInfo) } else { uni.showToast({ title: '获取用户信息失败', icon: 'error' }) } }, fail: (res) => { console.log(res); uni.showToast({ title: '您取消了授权', icon: 'error' }) } }) }, // 封装的登录请求,等待后端接口 WXLiginCode(e) { wx.login({ success: res => { console.log(res); if (res.code) { this.code = res.code console.log(e1); console.log(e2); console.log(res, '有code'); // 再次发送网络请求 // 请求后端给的登录接口,把res.code等相关参数带上 // 使用获取到的code请求微信登录接口,获取 openid 和 session_key uni.request({ url: 'http://xxx.x.x.x:8080/wxh5/wx/user/' + 'wx55822xxxx75e422' + '/login/', data: { code: this.code, }, }).then((res) => { //获取到 openid 和 session_key 后,自己的逻辑 console.log('授权登录', res[1].data); console.log(res[1].data.openid); console.log(res[1].data.session_key); }); console.log('res', res); } else { // 可以给失败提示 } } }) } } } </script>
以上总结于up主“riny的奇妙冒险之旅”