一:配置接口
注意:这里填写的是域名(是一个字符串),而不是URL,因此请勿加 http:// 等协议头,
二:定义一个公众号菜单,跳转授权页面(或者链接直接跳转)
String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx59be073ef6eac757&redirect_uri=http://wx.intmote.com/debo_wx/index.html&response_type=code&scope=snsapi_base&state=123#wechat_redirect";
CommonButton btn11 = new CommonButton();
btn11.setName("跳转授权页面");
btn11.setType("view");
btn11.setUrl(url);
appid 公众号的唯一标识
redirect_uri 授权后重定向的回调链接地址, 请使用 urlEncode 对链接进行处理
response_type 返回类型,请填写code
scope 应用授权作用域,snsapi_base (不弹出授权页面,直接跳转,只能获取用户openid),snsapi_userinfo (弹出授权页面,可通过openid拿到昵称、性别、所在地。并且, 即使在未关注的情况下,只要用户授权,也能获取其信息 )
state 重定向后会带上state参数,开发者可以填写a-zA-Z0-9的参数值,最多128字节
#wechat_redirect 是无论直接打开还是做页面302重定向时候,必须带此参数
三:获取code
点击菜单按钮后,页面将跳转至 http://wx.intmote.com/debo_wx/index.html/?code=CODE&state=STATE。
返回错误码说明:
10003 redirect_uri域名与后台配置不一致
10004 此公众号被封禁
10005 此公众号并没有这些scope的权限
10006 必须关注此测试号
10009 操作太频繁了,请稍后重试
10010 scope不能为空
10011 redirect_uri不能为空
10012 appid不能为空
10013 state不能为空
10015 公众号未授权第三方平台,请检查授权状态
10016 不支持微信开放平台的Appid,请使用公众号Appid
在index.html页面获取code
var code = GetQueryString("code");
//获取地址栏后面的参数
function GetQueryString(name){
var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg);
if(r!=null)return unescape(r[2]); return null;
}
四:根据code去获取access_token
前端ajax请求:
//获取用户的openId
$.ajax({
url : "getOpenId.action",
dataType : "json",
type : "get",
data : "code="+GetQueryString("code"),
success : function(data){
//返回的data即为openid,拿到openid实现业务
}
})
Controller:
/**
* 网页授权获取用户openid
* @Title: getOpenId
* @param @param code
* @throws
*/
@RequestMapping(value = "getOpenId", method = RequestMethod.GET)
@ResponseBody
public String getOpenId(@RequestParam("code") String code)
{
System.out.println("cede="+code);
//通过code获取openId
JSONObject jsonDate = CommonUtil.getOpenId(code);
if(jsonDate.isNull("errcode")){
return jsonDate.getString("openid");
}
return "";
}
/**
* 网页授权获取openId
* @Title: getOpenId
* @Description: TODO
* @param code
* @return JSONObject
*/
public static JSONObject getOpenId(String code) {
String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
String requestUrl = url.replace("APPID", WeChatInfo.WX_APPID).replace("SECRET", WeChatInfo.WX_APPSECRET).replace("CODE", code);
JSONObject jsonObject = httpsRequest(requestUrl, "GET", null);
return jsonObject;
}
appid 公众号的唯一标识
secret 公众号的appsecret
code 填写第一步获取的code参数
grant_type 填写为authorization_code
WeCharInfo:
public class WeChatInfo {
public static final String WX_APPID = "wx59bte0732ef6eeac757";
public static final String WX_APPSECRET = "3ade4c386340aa47bb55dae0d9b9ac7d73";
}
requestUrl请求完成返回的JSON数据包如下:
{ "access_token":"ACCESS_TOKEN",
"expires_in":7200,
"refresh_token":"REFRESH_TOKEN",
"openid":"OPENID",
"scope":"SCOPE" }
参数
描述
{"errcode":40029,"errmsg":"invalid code"}
结束了,如果要获取用户的其他信息,参考微信开发文档,我是直接根据openid去数据库查询用户信息(关注时保存用户信息到数据库)