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";
    }
}
相关推荐
空中海4 小时前
微信小程序 - 03 工程实践层与综合 Demo
微信小程序·小程序·notepad++
小徐_23336 小时前
Wot UI v1 升级 v2?这份迁移指南帮你少踩坑!
前端·微信小程序·uni-app
优睿远行7 小时前
微信小程序云开发环境搭建与REST API混合架构实战
微信小程序·小程序
Greg_Zhong8 小时前
解决绘制的雷达图在页面有滚动时,雷达图出现`轻微上下偏移`的问题
微信小程序·canvans绘制雷达图
空中海8 小时前
微信小程序 - 02 基础概念层与核心能力层
微信小程序·小程序
無名路人9 小时前
小程序点餐页吸顶滚动
前端·微信小程序·ai编程
游戏开发爱好者810 小时前
使用Fiddler设置HTTPS抓包诊断Power Query网络问题
android·ios·小程序·https·uni-app·iphone·webview
七月的冰红茶11 小时前
【开发工具】使用cursor实现点单小程序
小程序
Greg_Zhong12 小时前
微信小程序中使用canvas实现雷达图及标签对角显示(实现雷达图标签的标准做法)
微信小程序·小程序canvas实现雷达图·标签不通过canvas绘制
码农客栈13 小时前
小程序学习(十八)之“骨架屏”
小程序