WeChat公式アカウントログイン認証

イルカエルフhttps : //mgo.whhtjl.com

インターネットでさまざまな資料を見つけて、さまざまなドキュメントを読んだと思います。プロセス全体を繰り返すことはしません。疑問がある場合は、WeChatオープンプラットフォームで詳細を確認できます。Webアドレス: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で関連情報を構成します

WeChat APPの支払いには証明書が必要です。WeChatオープンプラットフォームに移動して構成し、ダウンロードしてリソースディレクトリに配置できます。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