> 技术文档 > uniapp实现微信小程序一键登录_uniapp 微信小程序登录

uniapp实现微信小程序一键登录_uniapp 微信小程序登录


前言

实现微信一键登录的流程:

① 微信小程序端获取临时凭证codecode只能被消费一次

② 将code交给后端

③ 后端拿到code,向微信服务器发起请求,拿到openidopenid代表微信用户在一个小程序中的唯一标识,另外拓展一下unionid代表微信用户在企业中的唯一标识

④ 后端查询数据库是否存在这个openid,存在则登录,返回token;不存在则注册账号,登录,返回token

一、复制 AppID 和 AppSecret

去 微信公众平台 -> 开发与服务 -> 开发管理 :微信公众平台 (qq.com)

复制AppIDAppSecret

三、通过uni.login() 拿到临时凭证code

uni.login({ provider: \'weixin\', success: function (loginRes) { //打印临时凭证 console.log(loginRes.code) }});

 另外,可以通过uni.getUserInfo()获取到用户的头像、昵称、手机号等信息,不过手机号需要企业身份才可以,如:

// 登录成功uni.getUserInfo({ provider: \'weixin\', success: function(info) { // 获取用户信息成功, info.authResult是用户信息 const wxUserInfo = info.userInfo//打印头像url console.log(wxUserInfo.avatarUrl) //打印昵称 console.log(wxUserInfo.nickName) //打印用户详细信息 console.log(wxUserInfo) }})

四、后端用临时凭证code换取openid

 在spring-web工程中导入maven工具依赖

 cn.hutool hutool-all 5.8.16

在下面工具类中配置自己的AppID,AppSecret后即可使用

import cn.hutool.http.HttpResponse;import cn.hutool.http.HttpUtil;import cn.hutool.json.JSONObject;import cn.hutool.json.JSONUtil;import org.springframework.web.util.UriComponentsBuilder;public class WechatUtil {//配置自己的app_id、app_secret private static final String APP_ID = \"Your_APP_ID\"; private static final String APP_SECRET = \"Your_APP_SERCERT\"; public static String getOpenId(String loginCode) { String url = \"https://api.weixin.qq.com/sns/jscode2session\"; String requestUrl = UriComponentsBuilder.fromHttpUrl(url) .queryParam(\"appid\", APP_ID) .queryParam(\"secret\", APP_SECRET) .queryParam(\"js_code\", loginCode) .queryParam(\"grant_type\", \"authorization_code\") .toUriString(); HttpResponse response = HttpUtil.createGet(requestUrl).execute(); // 获取 session_key 和 openid JSONObject parseObj = JSONUtil.parseObj(response.body()); String openid = (String) parseObj.get(\"openid\"); return openid; }}

 拿到openid之后便可以通过查询数据库实现一键登录了