一、获取apikey,appsecret与商户号
注册公众号、商户号
二、获取用户的OpenId
1.设置【授权回调页面域名】
官方解释:用户在网页授权页同意授权给公众号后,微信会将授权数据传给一个回调页面,回调页面需在此域名下,以确保安全可靠。回调页面域名不支持ip地址。
2.用户同意授权
我是把这个url写在微信菜单下的,当进入这个页面的时候就让用户同意。注意:好像是静默授权的,用户不知道
1.url:
https://open.weixin.QQ.com/connect/oauth2/authorize?appid=appid&redirect_uri=url&response_type=code&scope=snsapi_userinfo&state=park#wechat_redirect
参数:appid:公众号的唯一标识
redirect_uri:重定向的url,就是授权后要跳转的页面
scope:应用授权作用域
snsapi_base:不弹出授权页面,直接跳转,只能获取用户openid
snsapi_userinfo:弹出授权页面,可通过openid拿到昵称、性别、所在地
state:重定向后带的参数
2.用户同意后会产生一个code,只有5分钟时间的有效期。
1String code = request.getParameter("code")
3.code换openId
/*** 常量类
*@authorrory.wu
**/publicclassConstants {//第三方用户唯一凭证publicstaticString appid = "";//第三方用户唯一凭证密钥publicstaticString appsecret = "";//商户IDpublicstaticString mch_id="";//获取openIdpublicstaticString oauth2_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
}
1/**2* 通用工具类3*@authorrory.wu4*@version1.05*@since2015年08月05日6*/7publicclassCommonUtil {89PRivatestaticLogger log = Logger.getLogger(CommonUtil.class);10publicstaticJSONObject httpsRequestToJsonObject(String requestUrl, String requestMethod, String outputStr) {11JSONObject jsonObject =null;12try{13StringBuffer buffer =httpsRequest(requestUrl, requestMethod, outputStr);14jsonObject =JSONObject.fromObject(buffer.toString());15}catch(ConnectException ce) {16log.error("连接超时:"+ce.getMessage());17}catch(Exception e) {18log.error("https请求异常:"+e.getMessage());19}20returnjsonObject;21}222324privatestaticStringBuffer httpsRequest(String requestUrl, String requestMethod, String output)25throwsNoSuchAlgorithmException, NoSuchProviderException, KeyManagementException, MalformedURLException,26IOException, ProtocolException, UnsupportedEncodingException {2728URL url =newURL(requestUrl);29HttpsURLConnection connection =(HttpsURLConnection) url.openConnection();3031connection.setDoOutput(true);32connection.setDoInput(true);33connection.setUseCaches(false);34connection.setRequestMethod(requestMethod);35if(null!=output) {36OutputStream outputStream =connection.getOutputStream();37outputStream.write(output.getBytes("UTF-8"));38outputStream.close();39}4041//从输入流读取返回内容42InputStream inputStream =connection.getInputStream();43InputStreamReader inputStreamReader =newInputStreamReader(inputStream, "utf-8");44BufferedReader bufferedReader =newBufferedReader(inputStreamReader);45String str =null;46StringBuffer buffer =newStringBuffer();47while((str = bufferedReader.readLine()) !=null) {48buffer.append(str);49}5051bufferedReader.close();52inputStreamReader.close();53inputStream.close();54inputStream =null;55connection.disconnect();56returnbuffer;57}58}
1/**2* 获取用户的openId,并放入session3*@paramcode 微信返回的code4*/5privatevoidsetOpenId(String code) {6session.put("code", code);7String oauth2_url = Constants.oauth2_url.replace("APPID", Constants.appid).replace("SECRET", Constants.appsecret).replace("CODE", String.valueOf(session.get("code")));8log.info("oauth2_url:"+oauth2_url);9JSONObject jsonObject = CommonUtil.httpsRequestToJsonObject(oauth2_url, "POST",null);10log.info("jsonObject:"+jsonObject);11Object errorCode = jsonObject.get("errcode");12if(errorCode !=null) {13log.info("code不合法");14}else{15String openId = jsonObject.getString("openid");16log.info("openId:"+openId);17session.put("openId", openId);18}19}
oauth2_url返回的格式是:
{
"access_token":"ACCESS_TOKEN",
"expires_in":7200,
"refresh_token":"REFRESH_TOKEN",
"openid":"OPENID", "scope":"SCOPE",
"unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
}
Code无效时:
{
"errcode":40029
,"errmsg":"invalid code"
}