uni-app中的小程序微信登录

条件:

1.绑定好微信开放平台

2.登录小程序后台,开发-开发管理-开发设置 得到AppSecret小程序密钥

3.应用中配置小程序密钥

uni-app中的应用

登录页地址是固定的,pages/ucenter/userinfo/userinfo.vue这个页面

结合 http文件夹中封装的request进行访问

  1. 小程序调用uni.login() 登录,将自动跳转至pages/ucenter/userinfo/userinfo.vue这个页面

http/baseApi.js 中配置api服务器地址

如果访问的接口与服务器地址不一致 可直接写http开头的url

import api from '@/http/'

uni.login({
    provider: 'weixin',
    success: function (loginRes) {
        console.log(JSON.stringify(loginRes));
    }
});

成功时返回

{"errMsg":"login:ok","code":"071dbKkl2WwMq949Ujol22mPsz3dbKkC"}
  1. 后台API通过code得到session_key var oauthResponse = await wechat.SendAsync<RsCode.WeChat.MP.Auth.Code2SessionResponse>(new RsCode.WeChat.MP.Auth.Code2SessionRequest(option.AppId, option.AppSecret, code)); 得到会话密钥
{
    "openid": "oREAY0WgZhCEw_b4Ac3f_sIErtHM",
    "session_key": "B1n7agvgFKGSCFGNgzDWdg==",
    "unionid": "oa9ptxL8G7EpsKDthnW97xxx",
    "errcode": 0,
    "errmsg": null
}

保存信息至redis缓存 string cacheKey = $"sessionkey_{mpAppId}_{user.UserId}"; api接口返回自定义用户token信息

  1. 小程序保存accessToken
uni.setStorage({
    key: 'token',
    data: token
});

通过uni.getUserInfo()获取当前用户信息
文档open in new window

uni.getProvider()获取当前运行的环境

uni.getProvider({
    service:'oauth',
    success:function(res){
        console.log(res.provider)
		if (~res.provider.indexOf('qq')) {
			
		}
    }
})

uniapp消息监听

父页面定义事件

onLoad(){
    let that=this
    uni.$on('myEvent',function(data){
    that.getUserDeptCompany() 
    })
}


onUnload() { //销毁
    uni.$off('myEvent')
},

子页面发送事件

uni.$emit('myEvent',{msg:'页面更新'})
上次更新:
贡献者: kuiyu