微信公众号登录授权

海豚精灵https://mgo.whhtjl.com

相信大家已在网上找了各种资料,也看过了各种文档,对于整个流程我就不再重复啦,有疑惑的小伙伴可以移步微信开放平台查看详情,网页地址:https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html

废话不多说,直接上代码:

我这里后端使用的SpringBoot,Maven项目,代码如下:

<!--公众号(包括订阅号和服务号) -->
<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>

在application.properties中配置相关信息

微信APP支付这块是需要证书,大家自行去微信开放平台配置下载后放入resources目录下,可直接用classpath:xxxxxx.p12引入

#微信公众号
wx.mp.appId=wx8a7616f79d831d5e
wx.mp.appSecret=8cebe186c621dbec26387a5eec999820

创建实体类

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

}

创建控制层

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

}

猜你喜欢

转载自blog.csdn.net/qq_35393693/article/details/107383326