编辑代码

import org.apache.http.HttpResponse;
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.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.net.URLEncoder;

@SpringBootApplication
@RestController
public class WechatLoginDemo {

    // 替换为你的微信应用配置
    private static final String APP_ID = "chenming_123";
    private static final String APP_SECRET = "chenming_APP";
    private static final String REDIRECT_URI = "http://chenming.com/22723";

    public static void main(String[] args) {
        SpringApplication.run(WechatLoginDemo.class, args);
    }

    // 第一步:生成微信登录链接
    @GetMapping("/login")
    public String wechatLogin() throws Exception {
        String encodedRedirectUri = URLEncoder.encode(REDIRECT_URI, "UTF-8");
        String wechatUrl = "https://open.weixin.qq.com/connect/qrconnect?" +
                "appid=" + APP_ID +
                "&redirect_uri=" + encodedRedirectUri +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=STATE#wechat_redirect";
        return "Redirect to: <a href=\"" + wechatUrl + "\">微信登录</a>";
    }

    // 第二步:处理微信回调
    @GetMapping("/callback")
    public String callback(@RequestParam("code") String code,
                           @RequestParam(value = "state", required = false) String state) throws IOException {
        // 使用code获取access_token
        String tokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
                "appid=" + APP_ID +
                "&secret=" + APP_SECRET +
                "&code=" + code +
                "&grant_type=authorization_code";

        String tokenResponse = sendHttpGet(tokenUrl);
        
        // 解析返回的JSON获取access_token和openid(实际开发应使用JSON解析库)
        System.out.println("Token Response: " + tokenResponse);

        // 获取用户信息(需要根据实际返回参数处理)
        String userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?" +
                "access_token=ACCESS_TOKEN&openid=OPENID";
        String userInfo = sendHttpGet(userInfoUrl);
        
        return "Login Success! User Info: " + userInfo;
    }

    private String sendHttpGet(String url) throws IOException {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet request = new HttpGet(url);
            HttpResponse response = httpClient.execute(request);
            return EntityUtils.toString(response.getEntity());
        }
    }
}