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";
    }
}
相关推荐
龙兵科技小付说17 小时前
不同价格的上门做饭小程序APP都有什么功能?
小程序·软件开发·上门做饭
2501_9160074719 小时前
如何查看 iOS 设备系统与硬件信息,iOS系统信息显示工具
android·ios·小程序·https·uni-app·iphone·webview
逆龙泰氽20 小时前
微信小程序开发04-1(小程序API)
微信小程序·小程序
说私域20 小时前
AI智能名片S2B2C商城小程序在微商中的应用与影响
大数据·人工智能·小程序·流量运营
苏苏哇哈哈21 小时前
微信小程序实现高性能动态配置水滴凹槽、凸起Tabbar 组件
微信小程序·小程序
逆龙泰氽21 小时前
微信小程序开发03(WXML语法)
微信小程序·小程序
2501_9160074721 小时前
iOS APP 开发,从项目创建、证书与描述文件配置、安装测试和IPA 上传
android·ios·小程序·https·uni-app·iphone·webview
CHU72903521 小时前
淘宝扭蛋机小程序前端功能详解:以交互设计赋能趣味体验
java·前端·小程序·php
CHU7290352 天前
安心陪伴,便捷就医:陪诊代办小程序的温暖设计
前端·小程序·php
CHU7290352 天前
线上扭蛋机拆盒小程序前端功能版块解析
前端·小程序·php