在微信公众号请求用户网页授权之前,开发者需要先到公众平台官网中的开发者中心页配置授权回调域名。请注意,这里填写的是域名(是一个字符串),而不是URL,因此请勿加 http:// 等协议头。
(1)登陆微信公众号后台,点击权限接口点修改如图:
(2)修改如图
配置时要下载个MP_verify_BZf0ox6nPYbl3Fdv.txt文件放到授权web项目下,部署的时候放到webapps/weixinpt目录下面。说明:是地址加项目名:本次是weixinpt举例的
在微信端填的url:标准
https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect
https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx58d26d9c02734fe8&redirect_uri=http%3a%2f%2fsdxcgs.shuiqitosedng.com%2fwxgwpdest%2fwxcxpt%2fLoginAndWagewqg%2fLoginopenid.jsp&response_type=code&scope=snsapi_base&state=123#wechat_redirect
注意:redirect_uri地址必须urlencode处理
处理:这个地址是给微信公众号的地址,要把地址里面的红色值换掉,你现在用的微信公众号的appid的值。redirect_uri地址要urlencode编码再换到地址里面去。把上面的地址放到,微信公众号后台自定义菜单里面
代码实现:
OAuth
cn.com.zhongway.im.wechat.OAuth
OAuth
/OAuth
java类
/***********************************************************************
* Module: PublicAction.java
* Author: Administrator
* Purpose: Defines the Class PublicAction
***********************************************************************/
package cn.com.zhongway.im.wechat;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.log4j.Logger;
import com.sun.corba.se.spi.legacy.connection.Connection;
public class OAuth extends HttpServlet {
/**
* 通过code换取网页授权access_token,根据授权返回页面获取的code值获取openid
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String wxCode = request.getParameter("code");
String appid = request.getParameter("appid");
String secret = request.getParameter("secret");
//第一次请求 获取access_token 和 openid
String requestUrl = "";
String oppid="";
JSONObject oppidObj =null;
String access_token ="";
String openid ="";
String requestUrl2="";
String userInfoStr="";
JSONObject wxUserInfo=null;
try {
//获取code后,请求以下链接获取access_token
requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appid+"&secret="+secret+"&code="+wxCode+"&grant_type=authorization_code";
oppid = new HttpRequestor().doGet(requestUrl);
oppidObj =JSONObject.fromObject(oppid);
//获取access_token
access_token = (String) oppidObj.get("access_token");
//获取openid
openid = (String) oppidObj.get("openid");
//测试输出
request.setAttribute("openid", openid);
//response.getWriter().print("openid:"+openid);
//拉取用户信息(需scope为 snsapi_userinfo)就是微信平台填的链接,
//scope:snsapi_base (不弹出授权页面,直接跳转,只能获取用户openid)
//snsapi_userinfo (弹出授权页面,可通过openid拿到昵称、性别、所在地。并且,即使在未关注的情况下,只要用户授权,也能获取其信息)
/*requestUrl2 = "https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openid+"&lang=zh_CN";
userInfoStr = new HttpRequestor().doGet(requestUrl2);
wxUserInfo =JSONObject.fromObject(userInfoStr);*/
response.getWriter().print(openid);
response.getWriter().flush();
response.getWriter().close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void destroy() {
super.destroy();
}
@Override
public void init() throws ServletException {
super.init();
}
public boolean isChinese(String str) {
boolean result = false;
for (int i = 0; i < str.length(); i++) {
int chr1 = (char) str.charAt(i);
if (chr1 >= 19968 && chr1 <= 171941) {// 汉字范围 \u4e00-\u9fa5 (中文)
result = true;
}
}
return result;
}
private Map pubErrorContent(Exception e,String id){
Map errorcontent = new HashMap();
String[] es = e.toString().split(":");
String type = "";
String keywords = "";
String content = "";
for(int i = 0 ; i < es.length ; i++){
if(i==0){
type = es[i];
}
if(i==1){
keywords = es[i];
}
if(i==3){
keywords = es[i];
}
}
errorcontent.put("id", id);
errorcontent.put("type", type);
errorcontent.put("keywords", keywords);
errorcontent.put("content", content);
return errorcontent;
}
private Map pubInfoContent(String keywords,String info){
return null;
}
}
package cn.com.zhongway.im.wechat;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.Map;
/**
*处理OAuth2Service类微信链接url的的工具类,自己能处理可以不调用
*/
public class HttpRequestor {
private String charset = "utf-8";
private Integer connectTimeout = null;
private Integer socketTimeout = null;
private String proxyHost = null;
private Integer proxyPort = null;
/**
* Do GET request
*
* @param url
* @return
* @throws Exception
* @throws IOException
*/
public String doGet(String url) throws Exception {
URL localURL = new URL(url);
URLConnection connection = openConnection(localURL);
HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
httpURLConnection.setRequestProperty("Accept-Charset", charset);
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
InputStream inputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader reader = null;
StringBuffer resultBuffer = new StringBuffer();
String tempLine = null;
if (httpURLConnection.getResponseCode() >= 300) {
throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
}
try {
inputStream = httpURLConnection.getInputStream();
inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
reader = new BufferedReader(inputStreamReader);
while ((tempLine = reader.readLine()) != null) {
resultBuffer.append(tempLine);
}
} finally {
if (reader != null) {
reader.close();
}
if (inputStreamReader != null) {
inputStreamReader.close();
}
if (inputStream != null) {
inputStream.close();
}
}
return resultBuffer.toString();
}
/**
* Do POST request
*
* @param url
* @param parameterMap
* @return
* @throws Exception
*/
public String doPost(String url, Map, ?> parameterMap) throws Exception {
/* Translate parameter map to parameter date string */
StringBuffer parameterBuffer = new StringBuffer();
if (parameterMap != null) {
Iterator> iterator = parameterMap.keySet().iterator();
String key = null;
String value = null;
while (iterator.hasNext()) {
key = (String) iterator.next();
if (parameterMap.get(key) != null) {
value = (String) parameterMap.get(key);
} else {
value = "";
}
parameterBuffer.append(key).append("=").append(value);
if (iterator.hasNext()) {
parameterBuffer.append("&");
}
}
}
System.out.println("POST parameter : " + parameterBuffer.toString());
URL localURL = new URL(url);
URLConnection connection = openConnection(localURL);
HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Accept-Charset", charset);
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpURLConnection.setRequestProperty("Content-Length", String.valueOf(parameterBuffer.length()));
OutputStream outputStream = null;
OutputStreamWriter outputStreamWriter = null;
InputStream inputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader reader = null;
StringBuffer resultBuffer = new StringBuffer();
String tempLine = null;
try {
outputStream = httpURLConnection.getOutputStream();
outputStreamWriter = new OutputStreamWriter(outputStream);
outputStreamWriter.write(parameterBuffer.toString());
outputStreamWriter.flush();
if (httpURLConnection.getResponseCode() >= 300) {
throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
}
inputStream = httpURLConnection.getInputStream();
inputStreamReader = new InputStreamReader(inputStream);
reader = new BufferedReader(inputStreamReader);
while ((tempLine = reader.readLine()) != null) {
resultBuffer.append(tempLine);
}
} finally {
if (outputStreamWriter != null) {
outputStreamWriter.close();
}
if (outputStream != null) {
outputStream.close();
}
if (reader != null) {
reader.close();
}
if (inputStreamReader != null) {
inputStreamReader.close();
}
if (inputStream != null) {
inputStream.close();
}
}
return resultBuffer.toString();
}
private URLConnection openConnection(URL localURL) throws IOException {
URLConnection connection;
if (proxyHost != null && proxyPort != null) {
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
connection = localURL.openConnection(proxy);
} else {
connection = localURL.openConnection();
}
return connection;
}
/*
* Getter & Setter
*/
public Integer getConnectTimeout() {
return connectTimeout;
}
public void setConnectTimeout(Integer connectTimeout) {
this.connectTimeout = connectTimeout;
}
public Integer getSocketTimeout() {
return socketTimeout;
}
public void setSocketTimeout(Integer socketTimeout) {
this.socketTimeout = socketTimeout;
}
public String getProxyHost() {
return proxyHost;
}
public void setProxyHost(String proxyHost) {
this.proxyHost = proxyHost;
}
public Integer getProxyPort() {
return proxyPort;
}
public void setProxyPort(Integer proxyPort) {
this.proxyPort = proxyPort;
}
public String getCharset() {
return charset;
}
public void setCharset(String charset) {
this.charset = charset;
}
}