1 package goshen.education.weichat; 2 import java.io.BufferedReader; 3 import java.io.DataInputStream; 4 import java.io.DataOutputStream; 5 import java.io.File; 6 import java.io.FileInputStream; 7 import java.io.InputStream; 8 import java.io.InputStreamReader; 9 import java.io.OutputStream; 10 import java.net.HttpURLConnection; 11 import java.net.URL; 12 import java.util.Iterator; 13 import java.util.List; 14 import java.util.Map; 15 import javax.activation.MimetypesFileTypeMap; 16 import javax.servlet.http.HttpServletRequest; 17 import org.slf4j.Logger; 18 import org.slf4j.LoggerFactory; 19 import org.springframework.ui.Model; 20 import org.springframework.web.bind.annotation.RequestMapping; 21 import org.springframework.web.servlet.ModelAndView; 22 import goshen.education.utils.Tools; 23 import goshen.education.web.StudentController; 24 /** 25 * @author cunli 26 * 2016年8月23日 下午8:05:09 27 * 微信 28 */ 29 public class Weichat { 30 private static final Logger log = LoggerFactory.getLogger(Weichat.class); 31 private URL url; 32 private HttpURLConnection httpURLConnection; 33 public static final String APPID ="1234567"; 34 public static final String SECRET ="1234567"; 35 36 // RNJm9LTbpazPD8Swd00eExw8i58nhHXz8vzFtxuYXGQ 消息加密密钥 37 38 39 40 public static void main(String[] args){ 41 Weichat weichat = new Weichat(); 42 43 String accessToken = "eZe_B3a6H_3fRTUQVwHexoOcey82Q_rNRGfjzkH1fZ8mo7MbPlA4R-ncHvMYAbIEmuD4Wdv6tzg778UrKFRKvYBLpkmF75DAYN5vzxCLOb4IHYgAHADCT"; 44 45 // log.info("************获取token************ "+weichat.accessToken()); 46 47 // weichat.menus();//微信菜单 48 49 50 String openid = "o4fZSwYiygaU-WzG5ZjnPAxWbQGg";//自己 51 log.info("-------------获取用户信息------------- "); 52 weichat.whoareyou(openid, accessToken); 53 54 55 56 // log.info("-------------获取关注者列表------------- "+weichat.customers(accessToken)); 57 58 // String mediaId = "I5EAtAGd2ge-aq5OWlsRR0zhWEeNhJwmNKtwNNl_cEBZwfe01tFyVED3-bbCaUFu"; 59 // String openIds = "oI3PGt6VbRrYsvGqAD-8t2qJzS0Y,oI3PGtx_NcIucQpJNw0qO5gT-An4"; 60 // String[] ids = openIds.split(","); 61 // String lastIds = ""; 62 // for (int i = 0; i < ids.length; i++) { 63 // lastIds+=ids[i].trim()+"",""; 64 // } 65 // String lastOpenIds = lastIds.substring(0,lastIds.length()-3); 66 // 67 // System.out.println(lastOpenIds); 68 // 69 // sendImgText(mediaId,lastIds,accessToken); 70 } 71 72 73 74 /** 75 * @param request 76 * @return 获取网页授权 77 */ 78 public String userinfoByPage(HttpServletRequest request) { 79 String code = request.getParameter("code"); 80 String urlStr = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+APPID+"&secret="+SECRET+"&code="+code+"&grant_type=authorization_code"; 81 WeichatReturnCodes weichatReturnCodes =SendURLPost("", urlStr); 82 String openid = weichatReturnCodes.getOpenid(); 83 return openid; 84 85 } 86 87 /** 88 * @param scene_str 把当前用户openid,放到自己的二维码里面 89 * @return 获取二维码 90 */ 91 public String qrcode(String scene_str) { 92 Qrcode qrcode = new Qrcode(); 93 ActionInfo action_info = new ActionInfo(); 94 Scene scene = new Scene(); 95 scene.setScene_str(scene_str); 96 action_info.setScene(scene); 97 qrcode.setAction_info(action_info); 98 99 String qrcodeStr = Tools.toJson(qrcode); 100 System.out.println(qrcodeStr); 101 102 String urlStr = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token="+accessToken(); 103 WeichatReturnCodes token = SendURLPost(qrcodeStr,urlStr); 104 105 String accessTokenIsInvaild = token.getErrcode(); 106 log.info("WeichatController","------------错误信息-------------"+accessTokenIsInvaild); 107 log.info("WeichatController","------------二维码地址-------------"+token.getTicket()); 108 return token.getTicket(); 109 } 110 /** 111 * 上传图片 112 * 113 * @param urlStr 114 * @param textMap 115 * @param fileMap 116 * @return 117 */ 118 @SuppressWarnings("rawtypes") 119 public static String formUpload(String urlStr,Map<String, String> fileMap) { 120 String res = ""; 121 HttpURLConnection conn = null; 122 String BOUNDARY = "---------------------------123821742118716"; //boundary就是request头和上传文件内容的分隔符 123 try { 124 URL url = new URL(urlStr); 125 conn = (HttpURLConnection) url.openConnection(); 126 conn.setConnectTimeout(5000); 127 conn.setReadTimeout(30000); 128 conn.setDoOutput(true); 129 conn.setDoInput(true); 130 conn.setUseCaches(false); 131 conn.setRequestMethod("POST"); 132 conn.setRequestProperty("Connection", "Keep-Alive"); 133 conn.setRequestProperty("User-Agent","Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)"); 134 conn.setRequestProperty("Content-Type","multipart/form-data; boundary=" + BOUNDARY); 135 136 OutputStream out = new DataOutputStream(conn.getOutputStream()); 137 138 // file 139 if (fileMap != null) { 140 Iterator iter = fileMap.entrySet().iterator(); 141 while (iter.hasNext()) { 142 Map.Entry entry = (Map.Entry) iter.next(); 143 String inputName = (String) entry.getKey(); 144 String inputValue = (String) entry.getValue(); 145 if (inputValue == null) { 146 continue; 147 } 148 File file = new File(inputValue); 149 String filename = file.getName(); 150 String contentType = new MimetypesFileTypeMap() 151 .getContentType(file); 152 if (filename.endsWith(".tmp")) { 153 contentType = "image/tmp"; 154 } 155 if (contentType == null || contentType.equals("")) { 156 contentType = "application/octet-stream"; 157 } 158 159 StringBuffer strBuf = new StringBuffer(); 160 strBuf.append(" ").append("--").append(BOUNDARY).append( 161 " "); 162 strBuf.append("Content-Disposition: form-data; name="" 163 + inputName + ""; filename="" + filename 164 + ".png" "); 165 strBuf.append("Content-Type:" + contentType + " "); 166 167 out.write(strBuf.toString().getBytes()); 168 169 DataInputStream in = new DataInputStream( 170 new FileInputStream(file)); 171 int bytes = 0; 172 byte[] bufferOut = new byte[1024]; 173 while ((bytes = in.read(bufferOut)) != -1) { 174 out.write(bufferOut, 0, bytes); 175 } 176 in.close(); 177 } 178 } 179 180 byte[] endData = (" --" + BOUNDARY + "-- ").getBytes(); 181 out.write(endData); 182 out.flush(); 183 out.close(); 184 185 // 读取返回数据 186 StringBuffer strBuf = new StringBuffer(); 187 BufferedReader reader = new BufferedReader(new InputStreamReader( 188 conn.getInputStream())); 189 String line = null; 190 while ((line = reader.readLine()) != null) { 191 strBuf.append(line).append(" "); 192 } 193 res = strBuf.toString(); 194 reader.close(); 195 reader = null; 196 } catch (Exception e) { 197 System.out.println("发送POST请求出错。" + urlStr); 198 e.printStackTrace(); 199 } finally { 200 if (conn != null) { 201 conn.disconnect(); 202 conn = null; 203 } 204 } 205 return res; 206 } 207 208 /** 209 * 群发(文本消息) 210 */ 211 public void sendText(String accessToken){ 212 213 String context = "{"touser": ["oI3PGtx_NcIucQpJNw0qO5gT-An4"], "msgtype": "text", "text": { "content": "哈利路亚 halelujah"}}"; 214 String urlStr="https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token="+accessToken; 215 SendURLPost(context,urlStr); 216 217 System.out.println("***********群发(文本消息)*******已发送******"); 218 } 219 220 221 222 223 224 225 /** 226 * 下载 227 */ 228 public void download(String accessToken){ 229 230 String mediaId="qppSqxO1FlBG2Ll3je-Od-aVdUkW7OZ0gHQ5mXoSbwkHT2HYIW59HhnGWlcl3BS8"; 231 String urlStr="http://file.api.weixin.qq.com/cgi-bin/media/get?access_token="+accessToken+"&media_id="+mediaId; 232 SendURLPost("",urlStr); 233 234 System.out.println("***********下载*************"); 235 } 236 237 238 239 /** 240 * 获取用户信息 241 */ 242 public WeichatReturnCodes whoareyou(String openid,String accessToken){ 243 244 String urlStr ="https://api.weixin.qq.com/cgi-bin/user/info?access_token="+accessToken+"&openid="+openid+"&lang=zh_CN"; 245 String context=""; 246 WeichatReturnCodes weichatReturnCodes = SendURLPost(context,urlStr); 247 System.out.println("***********获取用户信息*************" +weichatReturnCodes.userInfo()); 248 return weichatReturnCodes; 249 250 } 251 /** 252 * 群发(图文消息) 253 */ 254 public HelpPictureText sendImgText(String mediaId,String openIds,String accessToken){ 255 256 StringBuffer stringBuffer=new StringBuffer(); 257 stringBuffer.append("{"touser":[""); 258 stringBuffer.append(openIds); 259 stringBuffer.append(""],"mpnews":{"media_id":""); 260 stringBuffer.append(mediaId); 261 stringBuffer.append(""}, "msgtype":"mpnews"}"); 262 263 String urlStr="https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token="+accessToken; 264 WeichatReturnCodes weichatReturnCodes =SendURLPost(stringBuffer.toString(),urlStr); 265 // String errcode = map.get("errcode").toString(); 266 String errcode = ""; 267 // String errmsg = map.get("errmsg").toString(); 268 // String msgId = map.get("msg_id").toString(); 269 String msgId = ""; 270 271 System.out.println(); 272 273 HelpPictureText helpPictureText=new HelpPictureText(); 274 helpPictureText.setMsgId(msgId); 275 helpPictureText.setErrcode(errcode); 276 277 return helpPictureText; 278 } 279 280 /** 281 * 上传图文信息 282 */ 283 public String uploadImgText(List<WechatMassMpnews> wechatPictureTexts,String accessToken){ 284 285 StringBuffer stringBuffer=new StringBuffer(); 286 287 for (WechatMassMpnews wechatPictureText2 : wechatPictureTexts) { 288 289 stringBuffer.append("{"thumb_media_id":""); 290 stringBuffer.append(wechatPictureText2.getThumbMediaId()); 291 stringBuffer.append("","author":""); 292 stringBuffer.append(wechatPictureText2.getAuthor()); 293 stringBuffer.append("","title":""); 294 stringBuffer.append(wechatPictureText2.getTitle()); 295 stringBuffer.append("","content_source_url":""); 296 stringBuffer.append(wechatPictureText2.getContentSourceUrl()); 297 stringBuffer.append("","content":""); 298 stringBuffer.append(wechatPictureText2.getContent().replaceAll("\\", "\\\\").replaceAll(""", "\\\"")); 299 stringBuffer.append("","digest":""); 300 stringBuffer.append(wechatPictureText2.getDigest()); 301 stringBuffer.append("","show_cover_pic":""); 302 stringBuffer.append(wechatPictureText2.getShowCoverPic()); 303 stringBuffer.append(""}"+","); 304 305 306 } 307 308 String wpt2=stringBuffer.substring(0,stringBuffer.length()-1); 309 String context ="{"articles": ["+wpt2+"]}"; 310 311 String urlStr="https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token="+accessToken; 312 WeichatReturnCodes weichatReturnCodes = SendURLPost(context,urlStr); 313 String mediaId = ""; 314 //String mediaId = map.get("media_id").toString(); 315 return mediaId; 316 } 317 /** 318 * 获取关注者列表 319 */ 320 public String customers(String accessToken){ 321 322 String urlStr ="https://api.weixin.qq.com/cgi-bin/user/get?access_token="+accessToken+"&next_openid="; 323 String context=""; 324 325 WeichatReturnCodes weichatReturnCodes = SendURLPost(context,urlStr); 326 // String data=map.get("data").toString(); 327 UserList data = weichatReturnCodes.getData(); 328 329 log.info("-----------data------ "+data.toString()); 330 331 for (int i = 0; i < data.getOpenid().length; i++) { 332 log.info("-----------array------ "+data.getOpenid()[i]); 333 } 334 335 336 // 337 // JsonUtil jsonUtil=new JsonUtil(); 338 // Map<String, Object> map2= JsonUtil.parseMapFromJsonString(data); 339 // String openid=map2.get("openid").toString(); 340 // String openid1=openid.substring(1); 341 // String openid2=openid1.substring(0,openid1.length()-1); 342 // 343 // String[] ids = openid2.split(","); 344 // 345 // String lastIds = ""; 346 // for (int i = 0; i < ids.length; i++) { 347 // lastIds+=ids[i].trim()+"",""; 348 // } 349 // String lastOpenIds = lastIds.substring(0,lastIds.length()-3); 350 String lastOpenIds = ""; 351 return lastOpenIds; 352 } 353 354 355 356 /** 357 * 微信菜单 358 */ 359 public void menus(String accessToken) { 360 WeichatMenu weichatMenu = new WeichatMenu();//主菜单 361 362 // -------------------------主菜单 1----------------------------------- 363 364 WeiMenu weiMenu = new WeiMenu();//主菜单 1 365 weiMenu.setName("Goshen观"); 366 weiMenu.setType("click"); 367 368 SubMenu subMenu11 = new SubMenu();//子菜单 1.1 369 subMenu11.setName("创新学院介绍"); 370 subMenu11.setType("view"); 371 subMenu11.setUrl("http://mp.weixin.qq.com/s?__biz=MzI0MzQzOTg0MQ==&mid=100000003&idx=1&sn=753f18a0d4db6d50a6661a6ad33aa28d&scene=0#wechat_redirect"); 372 373 SubMenu subMenu12 = new SubMenu();//子菜单 1.2 374 subMenu12.setName("关于高盛教育"); 375 subMenu12.setType("view"); 376 subMenu12.setUrl("http://mp.weixin.qq.com/s?__biz=MzI0MzQzOTg0MQ==&mid=100000029&idx=1&sn=772b3e381e134527b9e119ad9fb2ded9&scene=0#wechat_redirect"); 377 378 SubMenu subMenu13 = new SubMenu();//子菜单 1.3 379 subMenu13.setName("Goshen观点"); 380 subMenu13.setType("view"); 381 subMenu13.setUrl("http://wx.goshencn.com/"); 382 383 SubMenu subMenu14 = new SubMenu();//子菜单 1.4 384 subMenu14.setName("Goshen咨询"); 385 subMenu14.setType("view"); 386 subMenu14.setUrl("http://wx.goshencn.com/"); 387 388 SubMenu[] subMenus1 = {subMenu11,subMenu12,subMenu13,subMenu14}; 389 390 weiMenu.setSub_button(subMenus1);//子菜单 1,2,3,4 391 392 // -------------------------主菜单 1----------------------------------- 393 394 // -------------------------主菜单 2----------------------------------- 395 396 WeiMenu weiMenu2 = new WeiMenu();//主菜单 2 397 weiMenu2.setName("Goshen圈"); 398 399 400 SubMenu subMenu21 = new SubMenu();//子菜单 2.1 401 subMenu21.setName("Goshen公开课"); 402 subMenu21.setType("view"); 403 subMenu21.setUrl("http://wx.goshencn.com/"); 404 405 SubMenu subMenu22 = new SubMenu();//子菜单 2.2 406 subMenu22.setName("Goshen学子圈"); 407 subMenu22.setType("view"); 408 subMenu22.setUrl("http://wx.goshencn.com/"); 409 410 SubMenu subMenu23 = new SubMenu();//子菜单 2.3 411 subMenu23.setName("Goshen家长圈"); 412 subMenu23.setType("view"); 413 subMenu23.setUrl("http://v.qq.com/"); 414 415 SubMenu subMenu24 = new SubMenu();//子菜单 2.4 416 subMenu24.setName("交友 - 学习"); 417 subMenu24.setType("view"); 418 subMenu24.setUrl("http://v.qq.com/"); 419 420 SubMenu[] subMenus = {subMenu21,subMenu22,subMenu23,subMenu24}; 421 422 weiMenu2.setSub_button(subMenus);//子菜单 1,2,3,4 423 424 // -------------------------主菜单 2----------------------------------- 425 426 // -------------------------主菜单 3----------------------------------- 427 WeiMenu weiMenu3 = new WeiMenu();//主菜单 3 428 weiMenu3.setName("Goshen人"); 429 weiMenu3.setType("click"); 430 431 SubMenu subMenu31 = new SubMenu();//子菜单 3.1 432 subMenu31.setName("注册 - 加入"); 433 subMenu31.setType("view"); 434 435 String redirectUrl = "http://wx.goshencn.com/weichatLogin"; 436 String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+APPID+"&redirect_uri="+redirectUrl+"&response_type=code&scope=snsapi_base&state=haliluya#wechat_redirect"; 437 subMenu31.setUrl(url); 438 439 440 441 SubMenu subMenu32 = new SubMenu();//子菜单 3.2 442 subMenu32.setName("我的账户"); 443 subMenu32.setType("view"); 444 subMenu32.setUrl("http://wx.goshencn.com/"); 445 446 SubMenu subMenu33 = new SubMenu();//子菜单 3.3 447 subMenu33.setName("我的二维码"); 448 subMenu33.setType("view"); 449 subMenu33.setUrl("http://wx.goshencn.com/myQrcode"); 450 451 SubMenu subMenu34 = new SubMenu();//子菜单 3.4 452 subMenu34.setName("联系我们"); 453 subMenu34.setType("view"); 454 subMenu34.setUrl("http://mp.weixin.qq.com/s?__biz=MzI0MzQzOTg0MQ==&mid=100000029&idx=5&sn=78888945558437e44d3d1abf07b361f1&scene=0#wechat_redirect"); 455 456 SubMenu[] subMenus3 = {subMenu31,subMenu32,subMenu33,subMenu34}; 457 458 weiMenu3.setSub_button(subMenus3);//子菜单 1,2,3,4 459 460 // -------------------------主菜单 3----------------------------------- 461 462 WeiMenu[] weiMenus = {weiMenu,weiMenu2,weiMenu3}; 463 weichatMenu.setButton(weiMenus);//主菜单 1,2,3 464 465 466 String context = Tools.urlToJson(weichatMenu); 467 // String context = Tools.toJson(weichatMenu); 468 469 System.out.println("------------ "+context); 470 471 // accessToken = accessToken();//获取accessToken 472 473 String urlStr=" https://api.weixin.qq.com/cgi-bin/menu/create?access_token="+accessToken; 474 475 WeichatReturnCodes token = SendURLPost(context,urlStr); 476 477 String accessTokenIsInvaild = token.getErrcode(); 478 if ("42001".equals(accessTokenIsInvaild)) {//如果accessToken无效,重新获取 479 accessToken = accessToken(); 480 } 481 482 System.out.println("-----------微信菜单--------getErrcode---------- "+accessTokenIsInvaild); 483 System.out.println("-----------微信菜单--------getErrmsg---------- "+token.getErrmsg()); 484 } 485 486 487 488 /** 489 * 获取accessToken 490 */ 491 public String accessToken(){ 492 493 494 String urlStr="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+APPID+"&secret="+SECRET; 495 WeichatReturnCodes token = SendURLPost(APPID,urlStr); 496 497 System.out.println("--------获取token时的错误码-----7200 正常------getExpires_in------ "+token.getExpires_in()); 498 499 return token.getAccess_token(); 500 } 501 502 /** 503 * @param articleId 504 * 发送信息 505 */ 506 public WeichatReturnCodes SendURLPost(String context,String urlStr) { 507 StringBuilder sb = null; 508 // String content = ""; 509 try { 510 url = new URL(urlStr); 511 httpURLConnection = (HttpURLConnection) url.openConnection(); // 获取连接 512 httpURLConnection.setRequestMethod("POST"); // 设置请求方法为POST, 也可以为GET 513 httpURLConnection.setDoOutput(true); 514 OutputStream os = httpURLConnection.getOutputStream(); 515 os.write(context.toString().getBytes("UTF-8")); 516 os.flush(); 517 os.close(); 518 InputStream is = httpURLConnection.getInputStream( 519 ); 520 BufferedReader br = new BufferedReader(new InputStreamReader(is,"utf-8")); 521 sb = new StringBuilder(); 522 int b; 523 while ((b=br.read()) != -1) { 524 sb.append((char)b); 525 } 526 // content = new String(sb.toString().getBytes("ISO8859-1"), "utf-8"); 527 // System.out.println(sb.toString()); 528 // sb.toString() = {"access_token":"SpnkZdGB7Qy-cc8g1zmPiMj0eviJY72ZLimLLejeH8RGEhE8P8LQO5wayp0ehbL1VwrFtLi-Ex4u6YZPuRorsJ5pwpALY75oVrXqsd_NjedB5AHR-T8niG7uCRwTgWJ3JDRhABAWQE","expires_in":7200} 529 br.close(); 530 } catch (Exception e) { 531 e.printStackTrace(); 532 } 533 return Tools.fromJson(sb.toString(), WeichatReturnCodes.class); 534 } 535 536 537 }