微信开发java开源代码:
https://github.com/Wechat-Group/weixin-java-tools
申请微信测试接口:
http://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login
![](https://box.kancloud.cn/bca593f9ae3f48ab0bb852aaacdb94c2_1440x900.png)
设置授权回调页面域名:
![](https://box.kancloud.cn/db84a9d16623d31274a939c18cedd9a7_1033x432.png)
![](https://box.kancloud.cn/a97e5bd13ebe31d6a9079503522d198a_1440x860.png)
微信网页授权开发流程参见:
https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842
第一步:用户同意授权,获取code
https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect
其中:REDIRECT_URI需要编码成utf-8
~~~
/**
* URL编码(utf-8)
*
* @param source
* @return
*/
public static String urlEncodeUTF8(String source) {
String result = source;
try {
result = java.net.URLEncoder.encode(source, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return result;
}
~~~
第二步:通过code换取网页授权access_token和openid
https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
正确时返回的JSON数据包如下:
~~~
{ "access_token":"ACCESS_TOKEN",
"expires_in":7200,
"refresh_token":"REFRESH_TOKEN",
"openid":"OPENID",
"scope":"SCOPE" }
~~~
第三步:拉取用户信息(需scope为 snsapi_userinfo)
https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
正确时返回的JSON数据包如下:
~~~
{"openid":" OPENID",
" nickname": NICKNAME,
"sex":"1",
"province":"PROVINCE"
"city":"CITY",
"country":"COUNTRY",
"headimgurl": "http://thirdwx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/46",
"privilege":[ "PRIVILEGE1" "PRIVILEGE2" ],
"unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
}
~~~
参考代码:
~~~
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.neuedu.utils.CommonUtil;
import net.sf.json.JSONObject;
@Controller
public class WeiXinController {
@RequestMapping("/getcode")
public String getCode(HttpServletRequest request)
{
//1.得到微信返给的code
String code = request.getParameter("code");
//2.根据code得到access_token和openid
String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
url = url.replace("APPID", "wxbf9210646fd3bb89");
url = url.replace("SECRET", "9c7874ad52b1f5ba54c5985e52ef1b82");
url = url.replace("CODE", code);
JSONObject obj = CommonUtil.httpsRequest(url, "GET");
//3.根据access_token和openid得到用户信息
String url2 = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
url2 = url2.replace("ACCESS_TOKEN", obj.getString("access_token"));
url2 = url2.replace("OPENID", obj.getString("openid"));
JSONObject obj2 = CommonUtil.httpsRequest(url2, "GET");
//4.把当前用户信息放在session中
request.getSession().setAttribute("userinfo", obj2);
//5. 页面跳转到index.html
return "redirect:index.html?aid=1";
}
}
~~~
发送https请求的工具类
~~~
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ConnectException;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import net.sf.json.JSONObject;
/**
*
* 发送https请求
*
*/
public class CommonUtil {
/**
* 发送https请求
*
* @param requestUrl 请求地址
* @param requestMethod 请求方式(GET、POST)
* @param outputStr 提交的数据
* @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
*/
public static JSONObject httpsRequest(String requestUrl, String requestMethod) {
JSONObject jsonObject = null;
try {
// 创建SSLContext对象,并使用我们指定的信任管理器初始化
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL url = new URL(requestUrl);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(ssf);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
// 设置请求方式(GET/POST)
conn.setRequestMethod(requestMethod);
// 从输入流读取返回内容
InputStream inputStream = conn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
StringBuffer buffer = new StringBuffer();
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
System.out.println("返回信息:"+buffer);
// 释放资源
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
inputStream = null;
conn.disconnect();
jsonObject = JSONObject.fromObject(buffer.toString());
} catch (ConnectException ce) {
System.out.println(ce.toString());
//log.error("连接超时:{}", ce);
} catch (Exception e) {
//log.error("https请求异常:{}", e);
System.out.println(e.toString());
}
return jsonObject;
}
public static void main(String[] args) {
//根据code得到accesstoken, openid
JSONObject o = httpsRequest("https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx0156cb18976c3f90&secret=1bcb2d21ce527777ca4593bf452f48dc&code=071ZFuGj05fLQn1GszGj00fuGj0ZFuGa&grant_type=authorization_code","GET");
String access_token = o.getString("access_token");
String openid = o.getString("openid");
//根据accesstoken, openid得到用户信息
String url = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
url = url.replace("ACCESS_TOKEN", access_token);
url = url.replace("OPENID", openid);
System.out.println(url);
JSONObject o2 = httpsRequest(url,"GET");
System.out.println("昵称是:"+o2.getString("nickname"));
System.out.println("姓名是:"+o2.getString("sex"));
System.out.println("头像是:"+o2.getString("headimgurl"));
}
}
~~~
用户发送https请求的X509TrustManager
~~~
public class MyX509TrustManager implements X509TrustManager {
// 检查客户端证书
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
// 检查服务器端证书
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
// 返回受信任的X509证书数组
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
~~~