java 微信小程序注册和登录 (精简demo)

复制代码
1. 前端通过 wx.login 接口获得临时登录凭证 code, 传给后台
复制代码
前端wx.login (API)

https://developers.weixin.qq.com/miniprogram/dev/api/open-api/login/wx.login.html
复制代码
复制代码
2. 后台调用jscode2session接口, 使用 code 换取 openid、unionid、session_key 等信息
复制代码
小程序登录 (服务端)

https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-login/code2Session.html
复制代码
3. 注册和登录实现代码
复制代码
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class LoginController {


    /**
     * 微信小程序注册和登录
     *
     * @param code  用户登录凭证(有效期五分钟)
     * @return
     */
    @RequestMapping("/login")
    public Object login(String code){

        if (StringUtils.isEmpty(code)) {
            return AjaxResult.error("登录凭证不能为空");
        }

        try {
            String appid = "AppID(小程序ID)";
            String secret = "AppSecret(小程序密钥)";
            String grant_type = "authorization_code";

            CloseableHttpClient httpClient = HttpClients.createDefault();
            // 小程序登录
            String url = "https://api.weixin.qq.com/sns/jscode2session?appid="+appid+"&secret="+secret+"&js_code="+code+"&grant_type="+grant_type;
            HttpGet get = new HttpGet(url);
            CloseableHttpResponse response = httpClient.execute(get);
            String result = EntityUtils.toString(response.getEntity(), "utf-8");
            JSONObject json = JSONObject.parseObject(result);
            if (!json.containsKey("errcode")) {
                String openid = json.getString("openid");
                String unionid = json.getString("unionid");

                // TODO 存数据库

                return "success";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "error";
    }
}
相关推荐
沐子a~几秒前
小程序实战:萌宠案例
小程序
火眼金睛记单词17 分钟前
零基础成人重拾英语:第一个月的30天行动地图
前端·经验分享·学习·小程序
xinraynet26 分钟前
沈阳企业小程序开发选型:五个可核验维度,附设备数据采集与私域商城的技术实现要点
大数据·科技·ai·微信小程序·小程序
小码哥06815 小时前
Java医院陪诊系统陪护系统陪诊小程序,三端齐全可定制
大数据·小程序·陪诊陪护·陪诊小程序·陪护系统·陪诊系统·陪护小程序
连涨- AI脑波英语16 小时前
机构小程序对接词汇课程,测试账号怎样与正式学生账号隔离?
小程序·接口安全·脑机单词速记
liangshanbo121520 小时前
前端面试题:微信小程序怎么优化性能?
前端·微信小程序·notepad++
扶风ff1 天前
练题簿在线免费刷题:题目导入、章节管理、Excel 与 Word 导出,让题库更好用
学习·小程序·word·excel
拖孩1 天前
一个全程 AI 写的小程序「厨菜记」,上线 20 天跑通流量主,收入几块钱,开心得不行
前端·后端·微信小程序
程序猿_极客1 天前
【免费】分享一套优质的基于微信小程序的音乐播放器系统的设计与实现,源码+文档+视频详解(讲解)
微信小程序·小程序·springboot·音乐播放器小程序·音乐管理系统
愚公搬代码1 天前
【愚公系列】《微信小程序项目实战(AI编程+视频图解)》015-测试
微信小程序·小程序·ai编程