明天的明天 永远的永远 未知的一切 我与你一起承担 ??

是非成败转头空 青山依旧在 几度夕阳红 。。。
随笔 - 1274, 文章 - 0, 评论 - 214, 阅读 - 320万
  博客园  :: 首页  :: 管理
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

Java 微信小程序登录接口获取openid

Posted on   且行且思  阅读(1517)  评论(0编辑  收藏  举报

根据官方文档,wx.login()的回调函数中,需要我们传递生成的用户登录凭证到code2accessToken的接口中

小程序登录方法


code2accessToken的方法中要求传入如下参数

获取Appid与appSecret,登录微信公众平台,知道你申请的小程序,开发者设置中有appid,然后生成secret即可

 



开发者设置

官方文档:

    https://developers.weixin.qq.com/miniprogram/dev/api/open-api/login/wx.login.html

微信公众平台:

    https://mp.weixin.qq.com/

首先,要在微信开发者工具中,修改utils下app.js中的wx.login()方法

复制代码
// 登录
wx.login({
  success: function (res) {
    if (res.code) {
      // 发起网络请求
      wx.request({
        // 这里是接口地址,建议部署配置域名为https,否则可能会出问题,nginx加密证书配置见文章尾
        url: 'http://127.0.0.1:8099/api/v1/minipro/login',
        data: {
          code: res.code
        }
      })
    } else {
      console.log('登录失败!' + res.errMsg)
    }
  }
})
复制代码

 

微信小程序登录 JAVA接口

复制代码
@Controller
@RequestMapping("/api/v1/minipro")
public class MainController implements Serializable {
 
    private static final long serialVersionUID = 1L;
    private static Logger logger = LoggerFactory.getLogger(MainController.class);
 
    /**
     * 登录
     * @param
     */
    @ResponseBody
    @GetMapping(value="/login")
    public Result login(String code) {
        
        // 微信小程序ID
        String appid = "";
        // 微信小程序秘钥
        String secret = "";
        
        // 根据小程序穿过来的code想这个url发送请求
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";
        // 发送请求,返回Json字符串
        String str = WeChatUtil.httpRequest(url, "GET", null);
        // 转成Json对象 获取openid
        JSONObject jsonObject = JSONObject.parseObject(str);
        
        // 我们需要的openid,在一个小程序中,openid是唯一的
        String openid = jsonObject.get("openid").toString();
        
        
        // 然后书写自己的处理逻辑即可
        
    }
 
复制代码

 

微信小程序 JAVA工具类

复制代码
/**
 * 微信工具类
 */
public class WeChatUtil {
 
    public static String httpRequest(String requestUrl,String requestMethod,String output){
        try{
            URL url = new URL(requestUrl);
            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            if(null != output){
                OutputStream outputStream = connection.getOutputStream();
                outputStream.write(output.getBytes("utf-8"));
                outputStream.close();
            }
            // 从输入流读取返回内容
            InputStream inputStream = connection.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            StringBuffer buffer = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null){
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            inputStream = null;
            connection.disconnect();
            return buffer.toString();
        }catch(Exception e){
            e.printStackTrace();
        }
        return "";
    }
}
复制代码

 

因为审核上线的小程序接口都必须要https开头,也就是说必须开启加密证书才可以使用。



 

相关博文:
阅读排行:
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期
· 全程使用 AI 从 0 到 1 写了个小工具
· 从文本到图像:SSE 如何助力 AI 内容实时呈现?(Typescript篇)
历史上的今天:
2020-11-04 mybatis where 中in的使用
2009-11-04 SQL :多条记录取最前面一条或根据条件任取N条。。。。。。
2008-11-04 delegate 与异步调用。。。。。。。。。。。
2008-11-04 下面的代码示例使用 BeginGetRequestStream 方法对流实例发出异步请求。
点击右上角即可分享
微信分享提示