一、获取access_token
public static String getAccess_token(){
String access_token="";
String appid= “”;//获取appid
String secret=“”;//获取secret
String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+secret+"";
access_token = HttpJSON.loadJSON(url);
JSONObject jsonObject = new JSONObject(access_token);
Iterator iterator = jsonObject.keys();
while (iterator.hasNext()) {
String key = (String) iterator.next();
if(key.equals("access_token")){
access_token= jsonObject.getString(key);
}
}
return access_token;
}
二、获取openid
1.获取code
public static String getYtCodeUrl(String uri){
try {
uri = URLEncoder.encode(uri, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String appid= “”;//获取appid
return "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appid+"&redirect_uri="+uri+"&response_type=code&scope=snsapi_userinfo#wechat_redirect";
}
2.获取到openid
/**
* 获取access_token和openid
* @return
*/
public static String[] getAccess_tokenBycodeYiting(String code){
String[] res= new String[2];
String appid= “”;//获取appid
String secret=“”;//获取secret
String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appid+"&secret="+secret+"&code="+code+"&grant_type=authorization_code";
JSONObject jsonObject = new JSONObject(HttpJSON.loadJSON(url));
Iterator iterator = jsonObject.keys();
while (iterator.hasNext()) {
String key = (String) iterator.next();
if(key.equals("access_token")){
res[0]= jsonObject.getString(key);
}
if(key.equals("openid")){
res[1]= jsonObject.getString(key);
}
}
return res;
}
三、推送
public static void generateInfo(Map<String,Object> reqMap) {
String access_token =WeixinClient.getAccess_token();
String title="您的店铺:"+reqMap.get("dpName")+"-新订单提醒";
StringBuilder desc = new StringBuilder("下单时间:"+(String)reqMap.get("tm")+"\n");//消息内容
String url = ConfigerUtil.getPropertys("orderReceipt") +"/mobileH5portal/portal/wxOderDetail.action?logindkttype="+ (Integer)reqMap.get("id");//消息链接地址
StringBuilder sb = new StringBuilder("{\"touser\":\"");
System.out.println((String)reqMap.get("openid"));
sb.append((String)reqMap.get("openid"));//openids
sb.append("\",");
sb.append("\"msgtype\":\"news\",");
sb.append("\"news\":{");
sb.append("\"articles\":[{");
sb.append("\"title\":\""+title+"\",");
sb.append("\"description\":\""+desc.toString()+"\",");
sb.append("\"url\":\""+url+"\"");
sb.append("}]}}");
System.out.println(sb.toString());
sendPost("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="+access_token,sb.toString());
}