0,官網(wǎng)地址
https://mp.weixin.qq.com/wiki?t=resource/res_main
1隔嫡,獲取用戶信息:獲取用戶信息主要有微信網(wǎng)頁授權以及UnionID機制(關注后獲取),先來說說網(wǎng)頁授權方式
1.1戈擒,引導授權地址,獲取code
授權需要使用到oauth2認證家坎,首先需要引導用戶打開地址,格式如下
https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect
其中SCOPE為授權作用域(snsapi_userinfo),STATE為參數(shù),可通過state傳參瞬捕,也可以通過傳統(tǒng)url拼接方式(需進行編碼),REDIRECT_URL為授權后回調(diào)地址舵抹,授權后微信會攜帶code跳轉到REDIRECT_URL
例:
https://open.weixin.qq.com/connect/oauth2/authorize?appid=****&redirect_uri=****&response_type=code&scope=snsapi_userinfo&state=#wechat_redirect
1.2肪虎,通過code換取access_token和openid
請求微信接口:
https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
微信方會返回token(此token僅用于步驟4獲取userinfo,不同于其他token)惧蛹,此接口返回openid笋轨,accesstoken秆剪,openid以及refresh_token;
1.3 刷新access_token(非必需)
如果accesstoken過期爵政,可通過refresh_token刷新token仅讽;請求接口為:https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=APPID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN;
1.4拉取用戶信息(需scope為 snsapi_userinfo)
微信方接口
https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN钾挟;
全部代碼如下:
//https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
String openid = "";
String soap_url1 = Constant.WEIXIN.WX_URL + "sns/oauth2/access_token?appid=" + Constant.WEIXIN.APP_ID
+ "&secret=" + Constant.WEIXIN.SECRET + "&code=" + code + "&grant_type=authorization_code";
String ret1 = WeiXinUtil.connectWeiXinInterfaceGet(soap_url1, "");
if (ret1 != null && ret1.trim().length() > 0) {
JSONObject obj = JSONObject.fromObject(ret1);
if (obj.get("errcode") != null) {
// 跳轉到失敗界面去
}else {
openid = obj.getString("openid");
String access_token = obj.getString("access_token");
//https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
String soap_url2 = Constant.WEIXIN.WX_URL + "sns/userinfo?access_token=" + access_token + "&openid="
+ openid + "&lang=zh_CN";
String ret2 = WeiXinUtil.connectWeiXinInterfaceGet(soap_url2, "");
if (ret2 != null && ret2.trim().length() > 0) {
JSONObject obj2 = JSONObject.fromObject(ret2);
if (obj2.get("errcode") != null) {
// 跳轉到失敗界面去
}else {
String nickname = String.valueOf(obj2.get("nickname"));
String sex = String.valueOf(obj2.get("sex"));
String headimgurl = String.valueOf(obj2.get("headimgurl"));
}
}
}
}
附上WeiXinUtil代碼
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class WeiXinUtil {
private static final Logger logger =LoggerFactory.getLogger(WeiXinUtil.class);
public static String connectWeiXinInterfaceGet(String action,String json){
URL url;
try {
url = new URL(action);
HttpURLConnection http = (HttpURLConnection) url.openConnection();
http.setRequestMethod("GET");
http.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
http.setDoOutput(true);
http.setDoInput(true);
System.setProperty("sun.net.client.defaultConnectTimeout", "60000");// 連接超時60秒
System.setProperty("sun.net.client.defaultReadTimeout", "60000"); // 讀取超時60秒
http.connect();
OutputStream os = http.getOutputStream();
os.write(json.getBytes("UTF-8"));// 傳入?yún)?shù)
InputStream is = http.getInputStream();
int size = is.available();
byte[] jsonBytes = new byte[size];
is.read(jsonBytes);
String result = new String(jsonBytes, "UTF-8");
logger.info("請求返回結果:"+result);
os.flush();
os.close();
return result;
} catch (Exception e) {
logger.info("請求微信接口失敗洁灵,失敗信息:"+e.getMessage());
return "";
}
}
public static String connectWeiXinInterfacePost(String action,String json){
URL url;
try {
url = new URL(action);
HttpURLConnection http = (HttpURLConnection) url.openConnection();
http.setRequestMethod("POST");
http.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
http.setDoOutput(true);
http.setDoInput(true);
System.setProperty("sun.net.client.defaultConnectTimeout", "60000");// 連接超時60秒
System.setProperty("sun.net.client.defaultReadTimeout", "60000"); // 讀取超時60秒
http.connect();
OutputStream os = http.getOutputStream();
os.write(json.getBytes("UTF-8"));// 傳入?yún)?shù)
InputStream is = http.getInputStream();
int size = is.available();
byte[] jsonBytes = new byte[size];
is.read(jsonBytes);
String result = new String(jsonBytes, "UTF-8");
logger.info("請求返回結果:"+result);
os.flush();
os.close();
return result;
} catch (Exception e) {
logger.info("請求微信接口失敗,失敗信息:"+e.getMessage());
return "";
}
}
}
2.UnionID機制獲取用戶信息
2.1獲取access_token掺出;
請求微信接口:
https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET,
該接口返回accesstoken徽千。
2.2 獲取用戶基本信息:
請求微信接口:
https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN;
該接口返回subscribe屬性為是否已關注標識汤锨,0為未關注1為已關注双抽,如已關注返回用戶信息如頭像等,如為未關注則不返回用戶信息闲礼,返回數(shù)據(jù)如圖:
代碼如下:
public static Map<String, String> getAccessUserInfo(String openId) {
String result = WeiXinUtil.connectWeiXinInterface(String.format(Constant.URL.USER_INFO, getAccessToken(), openId), "");
return JSON.parseObject(result, Map.class);
}
public static String getAccessToken(){
String result = WeiXinUtil.connectWeiXinInterface(String.format(Constant.URL.ACCESS_TOKEN_URL, Constant.WEIXIN.APP_ID, Constant.WEIXIN.SECRET), "");
JSONObject json = JSONObject.fromObject(result);
String token = StrUtil.getNotNullStrValue(json.get("access_token"));
return token;
}
總的來說UnionID機制獲取用戶信息有局限性牍汹,比如參數(shù)需openid,且返回數(shù)據(jù)如果未關注則獲取不到用戶信息柬泽;但UnionID方式獲取用戶信息來的更簡單慎菲;需要配合場景權衡;
3锨并,發(fā)送模板消息
3.1獲取openid露该,此步驟同UnionID機制獲取accesstoken
3.2 發(fā)送模板消息
首先在公眾號配置模板id如圖:
部分代碼如下:
public class NotifyTemplate {
private String template_id;
private String touser;
private String url;
private String first;
private String keyword1;
private String keyword2;
private String keyword3;
private String keyword4;
private String keyword5;
private String remark;
private String color;
public NotifyTemplate() {
super();
}
public NotifyTemplate(String template_id, String touser, String url,
String first, String keyword1, String keyword2,
String remark) {
super();
this.template_id = template_id;
this.touser = touser;
this.url = url;
this.first = first;
this.keyword1 = keyword1;
this.keyword2 = keyword2;
this.remark = remark;
this.color="#173177";
}
}
public static Map<String,String> sendTemplateMsg(NotifyTemplate template){
String msg= template.toJsonMsg();
String result = WeiXinUtil.connectWeiXinInterface(String.format(Constant.URL.TEMPLATE_SEND_URL,getAccessToken()), msg);
JSONObject obj= JSONObject.fromObject(result);
Map<String, String> map = JSONObject.toBean(obj, Map.class);
log.info("getSnsOauth2AccessToken==>{}", map);
return map;
}