Dolphin Elf : https://mgo.whhtjl.com
I believe you have found various materials on the Internet and read various documents. I will not repeat the whole process. If you have any doubts, you can check the details on the WeChat open platform. Web address: https:// developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html
Not much nonsense, just go to the code:
The SpringBoot and Maven project that I use for the back end here, the code is as follows:
<!--公众号(包括订阅号和服务号) -->
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-mp</artifactId>
<version>2.7.0</version>
</dependency>
<!--微信支付 -->
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-pay</artifactId>
<version>3.0.0</version>
</dependency>
Configure related information in application.properties
WeChat APP payment requires a certificate. You can go to the WeChat open platform to configure and download it and put it in the resources directory. You can directly import it with classpath:xxxxxx.p12
#微信公众号
wx.mp.appId=wx8a7616f79d831d5e
wx.mp.appSecret=8cebe186c621dbec26387a5eec999820
Create entity class
package com.ltf.config;
import lombok.Data;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* 微信支付商户基本信息
* @author xhz
*
*/
@Data
@Component
@ConfigurationProperties(prefix = "wx.mp")
public class WeChatMpProperties {
/**
* appId
*/
private String appId;
/**
* 公众平台密钥
*/
private String appSecret;
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this,
ToStringStyle.MULTI_LINE_STYLE);
}
}
Create a control layer
package com.ltf.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSONObject;
import com.ltf.config.WeChatMpProperties;
import com.ltf.entity.User;
import com.ltf.utils.SingletonLoginUtils;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.servlet.http.HttpServletRequest;
/**
* 微信授权
* @author xhz
*
*/
@RestController
@RequestMapping(value = "/api/client/weChatAuthorization/")
public class WeChatAuthorizationController extends BaseController {
private static final Logger logger = LoggerFactory
.getLogger(WeChatAuthorizationController.class);
@Autowired
private WeChatMpProperties weChatMpProperties;
/**
* 获取access_token
* @return
*/
public String getAccessToken() {
String access_token = "";
try {
String grant_type = "client_credential";// 获取access_token填写client_credential
String AppId = weChatMpProperties.getAppId();// 第三方用户唯一凭证
String secret = weChatMpProperties.getAppSecret();// 第三方用户唯一凭证密钥,即appsecret
// 这个url链接地址和参数皆不能变
String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=" + grant_type + "&appid=" + AppId + "&secret="+ secret;
URL urlGet = new URL(url);
HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
http.setRequestMethod("GET"); // 必须是get方式请求
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
http.setDoOutput(true);
http.setDoInput(true);
System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
http.connect();
InputStream is = http.getInputStream();
int size = is.available();
byte[] jsonBytes = new byte[size];
is.read(jsonBytes);
String message = new String(jsonBytes, "UTF-8");
JSONObject demoJson = JSONObject.parseObject(message);
access_token = demoJson.getString("access_token");
is.close();
} catch (Exception e) {
logger.error("UserController.getAccessTokes()--eror", e);
}
return access_token;
}
/**
* 判断是否关注
* @param access_token
* @param openid
* @return
*/
public boolean judgeIsFollow(String access_token,String openid){
Integer subscribe = 0;
try {
String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token="+access_token+"&openid="+openid+"&lang=zh_CN";
URL urlGet = new URL(url);
HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
http.setRequestMethod("GET"); // 必须是get方式请求
http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
http.setDoOutput(true);
http.setDoInput(true);
http.connect();
InputStream is = http.getInputStream();
int size = is.available();
byte[] jsonBytes = new byte[size];
is.read(jsonBytes);
String message = new String(jsonBytes, "UTF-8");
JSONObject demoJson = JSONObject.parseObject(message);
subscribe = demoJson.getIntValue("subscribe"); // 此字段为关注字段 关注为1 未关注为0
is.close();
} catch (Exception e) {
logger.error("UserController.judgeIsFollow()--eror", e);
}
return 1==subscribe?true:false;
}
/**
* 检查用户是否已关注公众号
* @param request
* @return
*/
@SuppressWarnings("static-access")
@PostMapping("WhetherToFollow")
@ResponseBody
public JSONObject WhetherToFollow(HttpServletRequest request) {
try {
User user=SingletonLoginUtils.getLoginUser(request);
if(user!=null){
if(user.getIsAvailable()==2){
return this.formatJSON(500, "抱歉,冻结状态下无法获取授权!", null);
}else{
boolean bool=judgeIsFollow(getAccessToken(),user.getUnionId());
System.out.println("关注结果:"+bool);
if(bool){
return this.formatJSON(200, "true", null);
}else{
return this.formatJSON(200, "false", null);
}
}
}else{
return this.formatJSON(500, "登录状态已失效,请重新登录!", null);
}
} catch (Exception e) {
logger.error("UserController.WhetherToFollow()----error", e);
return this.formatJSON(500, "核实公众号失败!", null);
}
}
}