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 小时前
微信小程序输入框光标从中间删除跳到最后bug解决
微信小程序·uniapp·ios光标
小皮虾5 小时前
护航隐私!小程序纯前端“证件加水印”:OffscreenCanvas 全屏平铺实战
前端·javascript·微信小程序
白宇横流学长5 小时前
基于SpringBoot医院复查开药网站和微信小程序的设计
spring boot·后端·微信小程序
项目題供诗8 小时前
微信小程序黑马优购(项目)(七)
微信小程序·小程序
2501_915918418 小时前
HTTPS 端口深度解析,443 并不是唯一入口,理解 TLS 流量行为与抓包策略
网络协议·http·ios·小程序·https·uni-app·iphone
2501_916008899 小时前
iOS 开发者工具全景图,构建从编码、调试到性能诊断的多层级工程化工具体系
android·ios·小程序·https·uni-app·iphone·webview
qq_124987075310 小时前
基于微信小程序的家电维修平台的设计与实现(源码+论文+部署+安装)
微信小程序·小程序·毕业设计
2501_9159214310 小时前
从需求到上架,现代 iOS 开发流程的工程化方法论
android·ios·小程序·https·uni-app·iphone·webview
用户66006766853911 小时前
微信小程序实战:手把手搭建路虎汽车展示小程序
微信小程序
说私域12 小时前
开源AI智能名片链动2+1模式商城小程序在淘宝首页流量生态中的应用与影响研究
人工智能·小程序·开源