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工具依赖

<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.8.16</version>
</dependency>

在下面工具类中配置自己的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之后便可以通过查询数据库实现一键登录了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值