如何通过code获取openid等用户信息

获得code后,您需要通过code换取access_token和openid。具体步骤如下:

  1. 发送请求到微信服务器:使用获得的code,appid和secret向微信服务器发送请求。

  2. 解析响应数据:微信服务器会返回包含access_token和openid的JSON数据,您需要解析这个数据。

第一步:index.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Welcome</title>
    <script src="https://res.wx.qq.com/open/js/jweixin-1.4.0.js"></script>
    <script>
        function getOpenId() {
            const appId = document.getElementById('wechatAppId').value;
            const redirectUri = document.getElementById('wechatRedirectUri').value;

            console.log('AppID:', appId);
            console.log('Redirect URI:', redirectUri);

            if (!appId) {
                alert('AppID 不能为空');
                return;
            }
            const encodedAppId = encodeURIComponent(appId);
            const encodedRedirectUri = encodeURIComponent(redirectUri);

            const url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${encodedAppId}&redirect_uri=${encodedRedirectUri}&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect`;
            console.log('URL:', url);
            window.location.href = url;
        }
    </script>
</head>
<body>
<h1 th:text="${message}">Welcome to Spring Boot!</h1>
<h2>Your OpenID is: <span th:text="${openid}">OpenID</span></h2>
<input type="hidden" id="wechatAppId" th:value="${wechatAppId}" />
<input type="hidden" id="wechatRedirectUri" th:value="${wechatRedirectUri}" />
<button onclick="getOpenId()">点击获取OpenID</button>
</body>
</html>

第二步:WeChatController

package com.example.demo.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Controller
public class
WeChatController {

    private static final Logger logger = LoggerFactory.getLogger(WeChatController.class);

    @Value("${wechat.appid}")
    private String wechatAppId;

    @Value("${wechat.redirect_uri}")
    private String wechatRedirectUri;

    @GetMapping("/wechat")
    public String wechat(Model model) {
        logger.info("wechatAppId: {}", wechatAppId);
        logger.info("wechatRedirectUri: {}", wechatRedirectUri);

        model.addAttribute("message", "Welcome to Spring Boot!");
        model.addAttribute("openid", ""); // 添加 openid 变量,暂时设为空字符串
        model.addAttribute("wechatAppId", wechatAppId);
        model.addAttribute("wechatRedirectUri", wechatRedirectUri);
        return "index";
    }
}

第三步:callback.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Callback</title>
</head>
<body>
<h1 th:text="${message}">Callback</h1>
<p>Authorization Code: <span th:text="${code}">No Code</span></p>
<p>Your OpenID is: <span th:text="${openid}">OpenID</span></p>
<p>Your Nickname is: <span th:text="${nickname}">Nickname</span></p>
<p>Your Profile Picture: <img th:src="${headimgurl}" alt="Profile Picture"></p>
</body>
</html>

第四步:WeChatCallbackController

package com.example.demo.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

@Controller
public class WeChatCallbackController {

    @Value("${wechat.appid}")
    private String appId;

    @Value("${wechat.appsecret}")
    private String appSecret;

    @GetMapping("/wechat/callback")
    public String callback(@RequestParam("code") String code, Model model) {
        String tokenUrl = String.format(
            "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code",
            appId, appSecret, code
        );

        RestTemplate restTemplate = new RestTemplate();
        String tokenResponse = restTemplate.getForObject(tokenUrl, String.class);

        ObjectMapper objectMapper = new ObjectMapper();
        try {
            JsonNode tokenNode = objectMapper.readTree(tokenResponse);
            String accessToken = tokenNode.get("access_token").asText();
            String openId = tokenNode.get("openid").asText();

            String userInfoUrl = String.format(
                "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN",
                accessToken, openId
            );

            String userInfoResponse = restTemplate.getForObject(userInfoUrl, String.class);
            JsonNode userInfoNode = objectMapper.readTree(userInfoResponse);

            model.addAttribute("openid", openId);
            model.addAttribute("nickname", userInfoNode.get("nickname").asText());
            model.addAttribute("headimgurl", userInfoNode.get("headimgurl").asText());
            model.addAttribute("code", code);
        } catch (IOException e) {
            e.printStackTrace();
            model.addAttribute("openid", "Error parsing JSON response");
        }

        return "callback";
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值