微信公众号网页授权思路解析及具体代码
微信开发文档
实现方式也是两种:
1.静默授权登录
授权登录以snsapi_base为scope发起的网页授权,是用来获取进入页面的用户的openid的,并且是静默授权并自动跳转到回调页的。用户感知的就是直接进入了回调页(往往是业务页面)特点:用户无感知;
2.非静默授权登录
非静默授权以snsapi_userinfo为scope发起的网页授权,是用来获取用户的基本信息的。但这种授权需要用户手动同意,并且由于用户同意过,所以无须关注,就可在授权后获取该用户的基本信息。
(区别:除了scope不一样,以及调用微信接口不一样,功能上,静默授权不需要用户确认,只需要用户访问某个网页,属于嵌套在普通网页里的授权形式,但是只能获取到用户的唯一标示openid和union id,无法拿到用户的微信头像、微信名称等个人信息,对于用户的简单认证还是很有用的。)
非静默授权
微信公众号技术开发文档: [https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1445241432]
首先编写一个工具类
package com.wlw.util;
import java.io.IOException;
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 net.sf.json.JSONObject;
/**
*
* 工具类
* 用来根据接口地址进行网络请求
* @author wlw
*
*/
public class AuthUtil {
public static final String APP_ID = "****************"; //填写自己的APPID
public static final String APP_SECRET = "**************"; //填写自己的APPSECRET
public static JSONObject doGetJson(String url) throws Exception, IOException {
JSONObject jsonObject=null;
//初始化httpClient
DefaultHttpClient client=new DefaultHttpClient();
//用Get方式进行提交
HttpGet httpGet=new HttpGet(url);
//发送请求
HttpResponse response= client.execute(httpGet);
//获取数据
HttpEntity entity=response.getEntity();
//格式转换
if (entity!=null) {
String result=EntityUtils.toString(entity,"UTF-8");
jsonObject=JSONObject.fromObject(result);
}
//释放链接
httpGet.releaseConnection();
return jsonObject;
}
}
1.引导用户进入授权页面同意授权,获取code
主要是发送请求:https://open.weixin.qq.com/connect/oauth2/authorize?appid=“+wx_appid+”&redirect_uri=“+api.wx_reg+”&response_type=code&scope=snsapi_login,snsapi_userinfo&state=1,0#wechat_redirect
其中各个参数的意义:
2.如果用户同意授权,页面将跳转至 redirect_uri并且携带"?code=CODE&state=STATE"
通过code换取网页授权access_token(后台操作)以及通过access_token换取用户信息
package com.wlw.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.wlw.util.AuthUtil;
import net.sf.json.JSONObject;
/**
* 回调地址
*
* @author wlw
*
*/
@WebServlet("/redirect_uri")
public class CallBackServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
/**
* 获取code
*/
String code=req.getParameter("code");
String url="https://api.weixin.qq.com/sns/oauth2/access_token?appid="+AuthUtil.APP_ID
+ "&secret="+AuthUtil.APP_SECRET
+ "&code="+code
+ "&grant_type=authorization_code";
JSONObject jsonObject;
try {
jsonObject = AuthUtil.doGetJson(url);
String openid=jsonObject.getString("openid");
String token=jsonObject.getString("access_token");
/**
* 拉取用户信息
*/
String infoUrl="https://api.weixin.qq.com/sns/userinfo?access_token="+token
+ "&openid="+openid
+ "&lang=zh_CN";
JSONObject userInfo=AuthUtil.doGetJson(infoUrl);//这里的userInfo已经是用户的信息了
System.out.println(userInfo);
//使用微信用户信息直接登录,无需注册和绑定
req.setAttribute("info", userInfo);
req.getRequestDispatcher("/index1.jsp").forward(req, resp);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
super.doPost(req, resp);
}
}
这里解释一下回调函数:回调地址是当我们用户同意授权后,程序会进行对回调地址的访问。所以回调地址必须在公网上能够进行访问的。(用我自己的理解就相当于是你给腾讯平台发送请求,获取用户的信息,当你参数携带正确的情况下,腾讯就会向你发送一个请求,而这个请求的路径就是上面的redirect_uri所指的路径,所以回调函数的调用只有可能在公网上进行调用)
以上就是微信非静默授权登录的代码部分,至于微信公众平台里的配置,看我下一个文章吧~
一下是另外两种登录的api,跟上面类似步骤,知识参数不一样而已,详细看开发文档,对应参数,详细你一定可以解决的…………
网站的微信授权登录是以二维码的形式 api网址 api https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419316505&token=&lang=zh_CN
手机端微信授权登录api网址 https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419317851&token=&lang=zh_CN
特殊情况:html页面,controller不方便控制页面跳转的情况,公众平台上菜单的地址就不能写接口的地址,但是如果对微信接口的回调参数理解透彻的话,就很好吧,公众平台的菜单地址同样可以直接写它自身的授权接口,同时,回调地址写进入的页面,这样,相当于是通过菜单直接调微信授权接口,然后微信再跳转到你的网页页面上,同时可以携带上需要的code,页面上从路径中截取到code发送给后台,后台再进行access_token和openid的值的请求,就能正常的走通……
参考文献
在确保微信公众账号拥有授权作用域(scope参数)的权限的前提下(服务号获得高级接口后,默认拥有scope参数中的snsapi_base和snsapi_userinfo),引导关注者打开如下页面:
https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect 若提示“该链接无法访问”,请检查参数是否填写错误,是否拥有scope参数对应的授权作用域权限。
尤其注意:由于授权操作安全等级较高,所以在发起授权请求时,微信会对授权链接做正则强匹配校验,如果链接的参数顺序不对,授权页面将无法正常访问
参考链接(请在微信客户端中打开此链接体验):
scope为snsapi_base
https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx520c15f417810387&redirect_uri=https%3A%2F%2Fchong.qq.com%2Fphp%2Findex.php%3Fd%3D%26c%3DwxAdapter%26m%3DmobileDeal%26showwxpaytitle%3D1%26vb2ctag%3D4_2030_5_1194_60&response_type=code&scope=snsapi_base&state=123#wechat_redirect
scope为snsapi_userinfo
https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxf0e81c3bee622d60&redirect_uri=http%3A%2F%2Fnba.bluewebgame.com%2Foauth_response.php&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
尤其注意:跳转回调redirect_uri,应当使用https链接来确保授权code的安全性。
//授权登录回调跳转,第一步先获取code参数,从而请求access_token
var getRequest = GetRequest();
var code = null;
if (getRequest.code) {
code = getRequest.code;
var data = {};
var url = getWeiContextPath() + "接口路径";
data.code = code;//课程
//同步ajax,供方法中调接口
$.ajax({
type: "POST",
cache: false,
data: data,
async: false,
url: url,
success: function (result) {
//信息完整,直接进入测试页面
window.location.href = "index.html"
},
error: function (result) {
alert(result.msg)
}
});
} else {
//没有code,再次请求获取code
var pageUrl = window.location.href
.replace(/[/]/g, "%2f")
.replace(/[:]/g, "%3a")
.replace(/[#]/g, "%23")
.replace(/[&]/g, "%26")
.replace(/[=]/g, "%3d");
var url =
"https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
"wx7813bb6299b9b52a" +
"&redirect_uri=" +
pageUrl +
"&response_type=code&scope=snsapi_base&state=STATE&connect_redirect=1#wechat_redirect";
window.location.href = url;
}
//获取页面请求路径中的参数
function GetRequest() {
var url = location.search; //获取url中"?"符后的字串
var theRequest = new Object();
if (url.indexOf("?") != -1) {
var str = url.substr(1);
strs = str.split("&");
for (var i = 0; i < strs.length; i++) {
theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
}
}
return theRequest;
}