您的位置:首页 > 移动开发 > 微信开发

微信网页二维码授权登陆

2016-01-13 14:09 573 查看
一、首先要了解微信网页授权登录肯定是先去官网看文档网页授权获取用户基本信息

二、文档里面无非就是几步操作:

下面这个图有必要复制过来,作为一个程序猿,接第三方的功能还是要明白业务流程



1、首先你需要在微信开放平台注册和认证,认证完毕以后网站应用中添加网站应用,在里面添加必要的信息以及很重要的授权回调域,审核通过以后就可以拿到APPID和SECRET,这个就是2个神器参数

2、在你自己的按钮点击事件中去调用微信提供获取code值得url地址:

特别需要注意的是:REDIRECT_URI参数在页面上需要用encodeURIComponent(REDIRECT_URI)编码,不然微信会一直报redirect_uri参数异常,APPID填入上面申请好的scope填写snsapi_login,state主要防止csrf攻击(跨站请求伪造攻击),你自己可以生成随机或者sessionid

<span style="font-size:14px;">      https://open.weixin.qq.com/connect/qrconnect?appid=APPID&redirect_uri=REDIRECT_URI &response_type=code&scope=SCOPE&state=STATE#wechat_redirect</span>
所以根据以上的url我们出来的地址应该是这样:

<span style="font-size:14px;">        var url = encodeURIComponent("http://xxxx.com/pubService/weChatLogin");
window.location.href="https://open.weixin.qq.com/connect/qrconnect?appid=你自己的appid&redirect_uri="+url+"&response_type=code&scope=snsapi_login
&state=3d6be0a4035d839573b04816624a415e#wechat_redirect"</span>


3、现在我们需要写回调代码来处理获取的code值,我们需要通过code获取access_token

<span style="font-size:14px;">   https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code</span>[/code] 
{

"access_token":"ACCESS_TOKEN",

"expires_in":7200,

"refresh_token":"REFRESH_TOKEN",

"openid":"OPENID", 授权用户唯一标识

"scope":"SCOPE",
"unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
}


4、根据返回的openid去获取相应的微信用户信息

<span style="font-size:14px;">     <span' target='_blank'>https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN</span>
<span style="font-size:14px;">{
"openid":"OPENID",
"nickname":"NICKNAME",普通用户昵称
"sex":1,  1为男性,2为女性
"province":"PROVINCE",  省份
"city":"CITY", 城市
"country":"COUNTRY", 国家
"headimgurl": "http://wx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/0",头像
"privilege":[
"PRIVILEGE1",
"PRIVILEGE2"
],  用户特权信息
"unionid": " o6_bmasdasdsad6_2sgVt7hMZOPfL"  用户统一标识

}</span>


5、下面的回调整体代码

<span style="font-size:14px;">package net.dreams9.servlet;

import java.io.IOException;
import java.io.PrintWriter;

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 net.dreams9.util.HttpsConnectUtil;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONObject;

/**
* Servlet implementation class WeinXinChatLogin
*/
@WebServlet("/weChatLogin")
public class WeinXinChatServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
private static final String APPID = "你自己";
private static final String SECRET = "</span><span style="font-size:14px;">你自己的</span><span style="font-size:14px;">";
private static final String SNS_URL = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
private static final Logger log = Logger.getLogger(WeinXinChatServlet.class);
/**
* @see HttpServlet#HttpServlet()
*/
public WeinXinChatServlet() {
super();
// TODO Auto-generated constructor stub
}

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String code = request.getParameter("code");
if(code != null && !"".equals(code)){
try {
String rsp = HttpsConnectUtil.doGet(ACCESS_TOKEN_URL.replace("CODE", code).replace("APPID", APPID).replace("SECRET", SECRET), "", "");
if(rsp != null && !"".equals(rsp)){
JSONObject data = JSONObject.parseObject(rsp);
if(data.containsKey("errcode")){
throw new Exception(data.getString("errmsg"));
}
String access_token = data.getString("access_token");
String openid = data.getString("openid");
//获取当前授权微信用户的信息
rsp = HttpsConnectUtil.doGet(SNS_URL.replace("ACCESS_TOKEN", access_token).replace("OPENID", openid), "", "");
if(rsp != null && !"".equals(rsp)){
data = JSONObject.parseObject(rsp);
if(data.containsKey("errcode")){
throw new Exception(data.getString("errmsg"));
}
log.info("weixin info:"+data.toJSONString());
//返回json信息到网页上面
PrintWriter writer = response.getWriter();
response.setHeader("Pragma", "no-cache");   // HTTP/1.0 caches might not implement Cache-Control and might only implement Pragma: no-cache
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("text/html; charset=UTF-8");
writer.write("<script>window.dialogArguments.callBack('"+data.toJSONString()+"');window.close();</script>");
log.info("<script>window.returnValue='"+data.toJSONString()+"';window.close();</script>");
writer.flush();
writer.close();

}
else{
throw new Exception("获取微信用户信息失败!!");
}
}
else{
throw new Exception("通过code获取access_token失败!!!");
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
}

}</span>


6、实际效果就是在网页是调用第2步的地址就会出现一个二维码,我们手机打开微信,扫描二微码就可以实现微信登录,当然,也可以用[b]wxLogin来处理自定义页面来显示二维码,详细可以看官方文档[/b]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: