参考文章:https://blog.csdn.net/Santiago_M/article/details/79109154 ;
https://www.cnblogs.com/jilu/p/6123447.html
参考地址微信公众号开发文档:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1445241432
前提:需要申请认证的微信公众号;获取对应的APPID和APPSECRET;并且还需要获取到用户信息权限(点击“修改“添加服务器的域名地址),前期工作安装测试账号为例给大家展示下:
1)、公众测试账号获取
访问上面的连接,选择“接口测试号申请”获得直接打开http://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?action=showinfo&t=sandbox/index通过微信客户端扫码登录即可登录。
登录完即可获取到一个测试公众账号的信息。主要有appId和appsecret两个参数,这将唯一标示一个公众号,并且需要将他们作为参数获取用户的信息。
2)、关注公众号
用户只有关注了这个公众号了,才能通过打开有公众号信息的链接去授权第三方登录,并获取用户信息的操作。故我们还需要用我们的微信关注微信号,操作如下:
还是刚刚那个登录成功后跳转的页面,我们可以看到,该页面有一个二维码,我们可以通过扫描该二维码进行关注,关注成功在右边的“用户列表”会多一个用户的信息。如下图所示:
3)配置回调函数
我们在微信客户端访问第三方网页(即我们自己的网页)的时候,我们可以通过微信网页授权机制,我们不仅要有前面获取到的appid和appsecret还需要有当用户授权之后,回调的域名设置,即用户授权后,页面会跳转到哪里。具体的配置如下:
还是在刚刚的页面,有一个“网页授权获取用户基本信息”,点击后面的修改
填写回调的域名:请注意,这里填写的是域名(是一个字符串),而不是URL,因此请勿加 http:// 等协议头;
如果你的网址没有被列入过黑名单,就会在顶部出现
然后,域名配置就成功了!可以进行开发了。
一。授权开发的流程(详情的东西请以官网为准,在此就不多说了):具体而言,网页授权流程分为四步:
1、引导用户进入授权页面同意授权,获取code
2、通过code换取网页授权access_token(与基础支持中的access_token不同)
3、如果需要,开发者可以刷新网页授权access_token,避免过期
4、通过网页授权access_token和openid获取用户基本信息(支持UnionID机制)
二。导入依赖相关的依赖pom.xml(我这里用的是springboot)
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.8</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.11</version>
</dependency>
<!-- https://mvnrepository.com/artifact/net.sf.json-lib/json-lib -->
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier><!-- 有两个jdk版本的实现:json-lib-2.1-jdk13.jar和json-lib-2.1-jdk15.jar 此行不能省略-->
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.57</version>
</dependency>
<!--日志依赖-->
<!-- 忽略自带的日志框架. -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
三、按照如上流程我就不多说废话直接粘代码供大家参考,请大家多多指教(代码里的所有APPID,APPSECRET都是使用的官网提供测试账号)
1.工具类
package com.example.demo.util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
public class AuthUtil {
public static final String APPID = "wxcdc9c9683d73579c";
public static final String APPSECRET = "b785306bef23c75c66992589a224d319";
public static JSONObject doGetJson(String url) throws ClientProtocolException, IOException {
JSONObject jsonObject = null;
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
if (entity != null) {
// 把返回的结果转换为JSON对象
String result = EntityUtils.toString(entity, "UTF-8");
jsonObject = JSON.parseObject(result);
}
return jsonObject;
}
}
2.微信登录的实现类(控制层)
package com.example.demo.controller;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.util.AuthUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
@Controller
@RequestMapping("/wx")
public class WXLoginController {
private static final Logger logger = Logger.getLogger(WXLoginController.class);
@Autowired
private HttpServletRequest request;
@Autowired
private HttpServletResponse response;
/**
* 公众号微信登录授权
*
* @return
* @throws ParseException
* @parameter
*/
@RequestMapping(value = "/wxLogin", method = RequestMethod.GET)
public String wxLogin() throws ParseException {
// 这个url的域名必须要进行再公众号中进行注册验证,这个地址是成功后的回调地址
String backUrl = "http://192.168.1.17:8088/wx/callBack";
// 第一步:用户同意授权,获取code
String getCodeUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + AuthUtil.APPID + "&redirect_uri="
+ URLEncoder.encode(backUrl) + "&response_type=code" + "&scope=snsapi_userinfo"
+ "&state=STATE#wechat_redirect";
logger.info("获取code, getCodeUrl=" + getCodeUrl);
// response.sendRedirect(url);
return "redirect:" + getCodeUrl;// 必须重定向,否则不能成功
}
/**
* 公众号微信登录授权回调函数
*
* @return
* @throws ServletException
* @throws IOException
* @parameter
*/
@RequestMapping(value = "/callBack", method = RequestMethod.GET)
@ResponseBody
public String callBack() throws ServletException, IOException {
String code = request.getParameter("code");
// 第二步:通过code换取网页授权access_token
String getTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + AuthUtil.APPID + "&secret="
+ AuthUtil.APPSECRET + "&code=" + code + "&grant_type=authorization_code";
logger.info("获取token,getTokenUrl=" + getTokenUrl);
JSONObject getTokenJson = AuthUtil.doGetJson(getTokenUrl);
/*
* { "access_token":"ACCESS_TOKEN", "expires_in":7200,
* "refresh_token":"REFRESH_TOKEN", "openid":"OPENID", "scope":"SCOPE" }
*/
logger.info("获取token,getTokenJson=" + getTokenJson.toJSONString());
String openid = getTokenJson.getString("openid");
String access_token = getTokenJson.getString("access_token");
String refresh_token = getTokenJson.getString("refresh_token");
// 第五步验证access_token是否失效;展示都不需要
String vlidTokenUrl = "https://api.weixin.qq.com/sns/auth?access_token=" + access_token + "&openid=" + openid;
logger.info("验证token,vlidTokenUrl=" + vlidTokenUrl);
JSONObject validTokenJson = AuthUtil.doGetJson(vlidTokenUrl);
logger.info("验证token,validTokenJson=" + validTokenJson.toJSONString());
if (!"0".equals(validTokenJson.getString("errcode"))) {
// 第三步:刷新access_token(如果需要)-----暂时没有使用,参考文档https://mp.weixin.qq.com/wiki,
String refreshTokenUrl = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=" + openid
+ "&grant_type=refresh_token&refresh_token=" + refresh_token;
logger.info("刷新token,refreshTokenUrl=" + refreshTokenUrl);
JSONObject refreshTokenJson = AuthUtil.doGetJson(refreshTokenUrl);
/*
* { "access_token":"ACCESS_TOKEN", "expires_in":7200,
* "refresh_token":"REFRESH_TOKEN", "openid":"OPENID", "scope":"SCOPE" }
*/
logger.info("刷新token,refreshTokenJson=" + refreshTokenJson.toJSONString());
access_token = refreshTokenJson.getString("access_token");
}
// 第四步:拉取用户信息(需scope为 snsapi_userinfo)
String getUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openid
+ "&lang=zh_CN";
logger.info("获取用户信息,getUserInfoUrl=" + getUserInfoUrl.toString());
JSONObject getUserInfoJson = AuthUtil.doGetJson(getUserInfoUrl);
/*
* { "openid":" OPENID", " nickname": NICKNAME, "sex":"1", "province":"PROVINCE"
* "city":"CITY", "country":"COUNTRY", "headimgurl":
* "http://wx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/46",
* "privilege":[ "PRIVILEGE1" "PRIVILEGE2" ], "unionid":
* "o6_bmasdasdsad6_2sgVt7hMZOPfL" }
*/
logger.info("获取用户信息,getUserInfoJson=" + getUserInfoJson.toString());
/*
* end 获取微信用户基本信息
*/
// 获取到用户信息后就可以进行重定向,走自己的业务逻辑了。。。。。。
// 接来的逻辑就是你系统逻辑了,请自由发挥
return getUserInfoJson.toString();
}
}
3.login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
</head>
<body>
<div>
<h1>登录页面</h1>
<div>
<span>用户名:<input id="telephone"type="text"/></span>
<span>密 码:<input id="pwd" type="password"/></span><br>
<button type="button" onclick="login();">登录</button>
</div>
</div>
</body>
<script src="js/jquery-1.9.1.min.js"></script>
<script src="js/swiper.min.js"></script>
<script>
$(function(){
window.location.href="wx/wxLogin";
})
</script>
</html>
四、使用微信开发工具测试
1.点击公众号网页,扫描图中二维码
2.输入访问的url地址
3. 授权获取信息
四、返回授权获取的微信账号信息