獲取code
就一個get請求連接,只要在微信內請求,弄個href訪問就行,我在controllers中實現如下;
String appid ="微信appid ";
String redirect_uri="回調地址";
String url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid + "&redirect_uri=" + redirect_uri+"&response_type=code&scope=snsapi_userinfo&state=jetcms#wechat_redirect";
try {
PrintWriter out = response.getWriter();
out.println("<script>window.location.href=''</script>");
out.flush();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
獲取openid
通過上面的回調地址將第一步獲取的code傳過來獲取openid和accessToken,在哪裏請求都是一樣,controllers中我是這樣實現的。
@RequestMapping(value = "/weixinOpenid")
public String weixinLogin(String code, String redirectUrl, HttpServletRequest request, HttpServletResponse response,
ModelMap model) throws IOException {
String tokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?grant_type=authorization_code";
tokenUrl = tokenUrl + "&appid=" + appid + "&secret=" + secret + "&code=" + code;
JSONObject json = null;
try {
json = new JSONObject(NetUtils.getNetData(tokenUrl, "GET", ""));
// ------------在這裏把使用過的code存入到緩存中--------
} catch (JSONException e2) {
e2.printStackTrace();
}
String openId = "";
String accessToken = "";
String[] s = new String[2];
if (json != null) {
try {
openId = json.getString("openid");
accessToken = json.getString("access_token");
s[0] = openId;
s[1] = accessToken;
System.out.println("手機登錄 獲取用戶授權:" + json);
} catch (JSONException e) {
String errcode = null;
try {
errcode = json.getString("errcode");
System.out.println("手機登錄 獲取用戶授權失敗" + errcode);
} catch (JSONException e1) {
e1.printStackTrace();
}
}
}
//實際上可以在這裏保存openid並綁定用戶號碼、設備IMEI等等
return redirectUrl;
}
獲取用戶信息
根據openid和accessToken獲取用戶信息,同時可以獲取unionid。
/**
* 獲取用戶信息 拉取用戶信息(需scope爲 snsapi_userinfo) 只有在用戶將公衆號綁定到微信開放平臺帳號後,可以獲取unionid
*
* @param
* @param
* @return
*/
public String[] getUserInfo(String openid, String accessToken) {
String userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?lang=zh_CN";
userInfoUrl = userInfoUrl + "&access_token=" + accessToken + "&openid=" + openid;
JSONObject json = null;
try {
json = new JSONObject(NetUtils.getNetData(userInfoUrl, "GET", ""));
} catch (JSONException e2) {
e2.printStackTrace();
}
String nickname = ""; // 用戶暱稱
String sex = ""; // 用戶的性別
String province = ""; // 用戶個人資料填寫的省份
String city = ""; // 普通用戶個人資料填寫的城市
String country = ""; // 國家,如中國爲CN
String headimgurl = ""; // 用戶頭像,
String[] s = new String[6];
if (json != null) {
try {
nickname = json.getString("nickname");
sex = json.getString("sex");
province = json.getString("province");
city = json.getString("city");
country = json.getString("country");
headimgurl = json.getString("headimgurl");
s[0] = nickname;
s[1] = sex;
s[2] = province;
s[3] = city;
s[4] = country;
s[5] = headimgurl;
System.out.println("獲取用戶信息成功" + json);
} catch (JSONException e) {
String errcode = null;
try {
errcode = json.getString("errcode");
System.out.println("獲取用戶信息失敗" + errcode);
} catch (JSONException e1) {
e1.printStackTrace();
}
}
}
return s;
}
獲取基礎access_token
不能直接用上面獲取openid時獲取的到的access_token來調用發送模板消息接口,具體用下面這個方法來獲取;
public String weixinToken() throws IOException {
String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret="
+ secret;
System.out.println("weixinToken_url:" + url);
String res = NetUtils.getNetData(url, "GET", "");
System.out.println("weixinToken_res:" + res);
JSONObject json = null;
try {
json = new JSONObject(res);
System.out.println("weixinToken_access_token:" + json.getString("access_token"));
return json.getString("access_token");
} catch (JSONException e2) {
e2.printStackTrace();
}
return null;
}
發送模版消息
通過上面幾個步驟獲取到openid和token後,就可以請求發送模板消息了,具體方法如下。
/**
* 發送公衆號模板消息推送
*
* @param access_token
* @param appid
*/
private void sendTemplate(String access_token, String appid) {
// TODO Auto-generated method stub
String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + access_token;
System.out.println("url:" + url);
JSONObject json = new JSONObject();
json.put("touser", appid);
json.put("template_id", "模版id");
json.put("url", "http://weixin.qq.com/download");
json.put("topcolor", "#FF0000");
// 具體的模版數據,根據模版來傳
JSONObject dataJson = new JSONObject();
dataJson.put("first", getValue("奧捷迅科技"));
dataJson.put("keyword1", getValue(new Data().toString()));
dataJson.put("keyword2", getValue("深圳市寶安區奧捷迅科技"));
dataJson.put("keyword3", getValue("NB煙感"));
dataJson.put("keyword4", getValue("NB煙感煙霧報警"));
dataJson.put("keyword5", getValue("玉念聿輝"));
dataJson.put("remark", getValue("貴司存在嚴重電氣火災安全隱患,爲避免造成不可挽救後果,請及時處理!謝謝!"));
json.put("data", dataJson);
System.out.println("json:" + json);
String res = NetUtils.getNetData(url, "POST", json.toString());
System.out.println("res:" + res);
}
private JSONObject getValue(String value) {
// TODO Auto-generated method stub
JSONObject json = new JSONObject();
json.put("value", value);
json.put("color", "#173177");
return json;
}
寫在最後
沒什麼技術含量,就是看文檔花了我很多時間,特意抽時間把代碼和思路貼出來,希望對有相關需求的朋友有所幫助。
就只是以上這麼簡單的幾步代碼,想看我到底是踩了多大的坑,才狠下決心要過來貼代碼的朋友請點擊這裏。