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 {
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);
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());
}
}
}