免费男女视频_国产系列 视频二区_羞羞视频免费入口网站_久国久产久精永久网页_国产免费观看av_一区二区三区日韩在线观看

微信api接口操作示例

一、服務(wù)器基本信息交互

public class WeiXinServlet extends HttpServlet{ private static final long serialVersionUID = 1L;
 /** * 確認(rèn)請(qǐng)求來(lái)自微信服務(wù)器 */ 
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 微信加密簽名  String signature = request.getParameter("signature"); // 時(shí)間戳  String timestamp = request.getParameter("timestamp"); // 隨機(jī)數(shù)  String nonce = request.getParameter("nonce"); // 隨機(jī)字符串  String echostr = request.getParameter("echostr");  

        PrintWriter out = response.getWriter(); // 通過(guò)檢驗(yàn)signature對(duì)請(qǐng)求進(jìn)行校驗(yàn),若校驗(yàn)成功則原樣返回echostr,表示接入成功,否則接入失敗  if (SignUtil.checkSignature(signature, timestamp, nonce)) {  
            out.print(echostr);
        }  
        out.close();  
        out = null;  
    } 
/** * 處理微信服務(wù)器發(fā)來(lái)的消息  */ 
public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { // 將請(qǐng)求、響應(yīng)的編碼均設(shè)置為UTF-8(防止中文亂碼)  request.setCharacterEncoding("UTF-8");  
            response.setCharacterEncoding("UTF-8"); // 調(diào)用核心業(yè)務(wù)類接收消息、處理消息  String respMessage = CoreService.processRequest(request); // 響應(yīng)消息  PrintWriter out = response.getWriter();  
            out.print(respMessage);  
            out.close();  
    }  
}
二、功能實(shí)現(xiàn)
2.1 公眾平臺(tái)通用接口工具類 public class WeixinUtil { 
private static Logger log = LoggerFactory.getLogger(WeixinUtil.class); 
// 第三方用戶唯一憑證
public final static String appId = "wx71335f894797efd0"; 
// 第三方用戶唯一憑證密鑰 
public final static String appSecret = "d524fcf5147c6c732a2270a64f5869a5";
 // 獲取access_token的接口地址(GET) 
public final static String access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET"; 
// 菜單創(chuàng)建 
public final static String menu_create_url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";
 // 發(fā)送模板消息 
public final static String sendtemplat_url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN"; 
// 獲取code后,請(qǐng)求以下鏈接獲取用戶access_token:
 public final static String userinfotoken_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=APPSECRET&code=CODE&grant_type=authorization_code";
 // 粉絲列表
 public final static String fansi_url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN"; 
// 獲取用戶信息 
public final static String user_url = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN"; 
// 獲取用戶基本信息(包括UnionID機(jī)制) 粉絲列表時(shí)使用
 public final static String fansi_userinfo_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN"; 
// 創(chuàng)建臨時(shí)二維碼ticket 
public final static String temporary_url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=ACCESS_TOKEN"; 
// 創(chuàng)建永久二維碼ticket 
public final static String permanent_url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=ACCESS_TOKEN"; 
// 通過(guò)ticket換取二維碼 提醒:TICKET記得進(jìn)行UrlEncode 
public final static String qrcode_url = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=TICKET"; 
// 獲取用戶增減數(shù)據(jù) 最大時(shí)間跨度7天 
public final static String getusersummary_url = "https://api.weixin.qq.com/datacube/getusersummary?access_token=ACCESS_TOKEN";
 // 獲取累計(jì)用戶數(shù)據(jù) 最大時(shí)間跨度7天 
public final static String getusercumulate_url = "https://api.weixin.qq.com/datacube/getusercumulate?access_token=ACCESS_TOKEN"; 
// 獲取jsapi_ticket 
public final static String jsapi_ticket_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi"; 
// 創(chuàng)建分組 POST數(shù)據(jù)例子:{"group":{"name":"test"}} 
public final static String create_group_url = "https://api.weixin.qq.com/cgi-bin/groups/create?access_token=ACCESS_TOKEN"; 
// 查詢所有分組 
public final static String selete_group_url = "https://api.weixin.qq.com/cgi-bin/groups/get?access_token=ACCESS_TOKEN"; 
// 查詢用戶所在分組 POST數(shù)據(jù)例子:{"openid":"od8XIjsmk6QdVTETa9jLtGWA6KBc"} 
public final static String selectUsers_group_url = "https://api.weixin.qq.com/cgi-bin/groups/getid?access_token=ACCESS_TOKEN"; 
// 修改分組名 POST數(shù)據(jù)例子:{"group":{"id":108,"name":"test2_modify2"}} 
public final static String update_group_url = "https://api.weixin.qq.com/cgi-bin/groups/update?access_token=ACCESS_TOKEN"; 
// 批量移動(dòng)用戶分組 
public final static String batch_group_url = "https://api.weixin.qq.com/cgi-bin/groups/members/batchupdate?access_token=ACCESS_TOKEN"; 
// 獲取微信卡券 api_ticket 
public final static String api_ticket_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=wx_card";
 // 批量查詢卡券列表 
public final static String batchget_url = "https://api.weixin.qq.com/card/batchget?access_token=ACCESS_TOKEN"; 
// 查詢卡券詳情 http請(qǐng)求方式: POST POST數(shù)據(jù) {"card_id":"pFS7Fjg8kV1IdDz01r4SQwMkuCKc"} 
public final static String get_card_url = "https://api.weixin.qq.com/card/get?access_token=ACCESS_TOKEN"; 
// 創(chuàng)建卡券二維碼 ticket post請(qǐng)求 
public final static String create_cardTicket_url = "https://api.weixin.qq.com/card/qrcode/create?access_token=ACCESS_TOKEN"; 
// 核銷卡券Code接口
 public final static String delete_code_url = "https://api.weixin.qq.com/card/code/consume?access_token=ACCESS_TOKEN"; 
// Code解碼接口 
public final static String code_decrypt_url = "https://api.weixin.qq.com/card/code/decrypt?access_token=ACCESS_TOKEN"; 
// 檢測(cè)Code是否正常狀態(tài)
public final static String check_code_url = "https://api.weixin.qq.com/card/code/get?access_token=ACCESS_TOKEN"; 
// 創(chuàng)建卡券貨架接口
public final static String create_cardhj_url = "https://api.weixin.qq.com/card/landingpage/create?access_token=ACCESS_TOKEN"; 
// 獲取用戶已領(lǐng)取卡券接口
public final static String getcardlist_url = "https://api.weixin.qq.com/card/user/getcardlist?access_token=ACCESS_TOKEN"; 
       public static AccessToken getAccessToken(String appid, String appsecret) {
        AccessToken accessToken = null;
        String requestUrl = access_token_url.replace("APPID", appid).replace( "APPSECRET", appsecret);
        JSONObject jsonObject = httpRequest(requestUrl, "GET", null); // 如果請(qǐng)求成功 if (null != jsonObject) { 
 try{
                accessToken = new AccessToken();
                accessToken.setToken(jsonObject.getString("access_token"));
                accessToken.setExpiresIn(jsonObject.getInteger("expires_in"));
            } catch (JSONException e) {
                accessToken = null; // 獲取token失敗 log.error("獲取token失敗 errcode:{} errmsg:{}",
                        jsonObject.getInteger("errcode"),
                        jsonObject.getString("errmsg"));
            }
        } return accessToken;
        } 
 /**獲取網(wǎng)頁(yè)授權(quán)用戶的token */ 
 public static OAuthInfo getUserToken(String code) {
        String requestUrl = userinfotoken_url.replace("APPID", appId)
                .replace("APPSECRET", appSecret).replace("CODE", code);
        JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
        OAuthInfo oa = new OAuthInfo(); if (null != jsonObject) { try {
                oa.setAccessToken(jsonObject.getString("access_token"));
                oa.setExpiresin(jsonObject.getInteger("expires_in").toString());
                oa.setRefreshToken(jsonObject.getString("refresh_token"));
                oa.setOpenid(jsonObject.getString("openid"));
                oa.setScope(jsonObject.getString("scope"));
            } catch (JSONException e) { // 獲取token失敗 log.error("網(wǎng)頁(yè)授權(quán)獲取openId失敗 errcode:{} errmsg:{}",
                        jsonObject.getInteger("errcode"),
                        jsonObject.getString("errmsg"));
            }
        } return oa;
      }
   /**獲取網(wǎng)頁(yè)授權(quán)用戶的詳細(xì)信息 */ 
 public static WxUserinfo getWxUserInfo(OAuthInfo oa) {
        String requestUrl = user_url.replace("ACCESS_TOKEN",
                oa.getAccessToken()).replace("OPENID", oa.getOpenid());
        JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
        WxUserinfo user = new WxUserinfo(); if (jsonObject != null) {
            user.setOpenid(jsonObject.getString("openid"));
            user.setNickname(jsonObject.getString("nickname"));
            user.setSex(jsonObject.getString("sex"));
            user.setProvince(jsonObject.getString("province"));
            user.setCity(jsonObject.getString("city"));
            user.setCountry(jsonObject.getString("country"));
            user.setHeadimgurl(jsonObject.getString("headimgurl"));
            user.setPrivilege(jsonObject.getString("privilege"));
        } return user;
    }
     /**創(chuàng)建菜單*/
    public static int createMenu(Menu menu, String accessToken) { int result = 0; 
 // 拼裝創(chuàng)建菜單的url 
     String url = menu_create_url.replace("ACCESS_TOKEN", accessToken); 
 // 將菜單對(duì)象轉(zhuǎn)換成json字符串 
    String jsonMenu = JSONObject.toJSONString(menu); 
 // 調(diào)用接口創(chuàng)建菜單 
     JSONObject jsonObject = httpRequest(url, "POST", jsonMenu); if (null != jsonObject) { if (0 != jsonObject.getInteger("errcode")) {
                result = jsonObject.getInteger("errcode");
                log.error("創(chuàng)建菜單失敗 errcode:{} errmsg:{}",
                        jsonObject.getInteger("errcode"),
                        jsonObject.getString("errmsg"));
            }
        } return result;
    } 
/**獲取粉絲列表信息*/ 
 public static JSONArray getFansList(String accessToken) {
        JSONArray arrs = new JSONArray();
        String url = fansi_url.replace("ACCESS_TOKEN", accessToken);
        JSONObject jsonObject = httpRequest(url, "GET", null); if (null != jsonObject) {
            JSONObject data = (JSONObject) jsonObject.get("data");
            JSONArray openidList = data.getJSONArray("openid"); for (int i = 0; i < openidList.size(); i++) {
                System.out.println(openidList.getString(i));
                JSONObject obj = httpRequest(
                        fansi_userinfo_url.replace("ACCESS_TOKEN", accessToken)
                                .replace("OPENID", openidList.getString(i)), "GET", null); if (obj != null) {
                    arrs.add(obj);
                }
            }
        } return arrs;
    } 
/** 創(chuàng)建二維碼ticket*/ 
 public static JSONObject createTicket(String type, String accessToken,
            String expire_seconds, String scene_id) {
        String requestUrl = "";
        String jsonStr = ""; if (type.equals("1")) {// 臨時(shí) requestUrl = temporary_url.replace("ACCESS_TOKEN", accessToken);
            jsonStr = "{\"expire_seconds\": 604800, \"action_name\": \"QR_SCENE\", \"action_info\": {\"scene\": {\"scene_id\": 123}}}";
        } else {// 永久 requestUrl = permanent_url.replace("ACCESS_TOKEN", accessToken);
            jsonStr = "{\"action_name\": \"QR_LIMIT_SCENE\", \"action_info\": {\"scene\": {\"scene_id\": 123}}}";
        }
        JSONObject jsonObject = httpRequest(requestUrl, "POST", jsonStr); return jsonObject;
    }
 /** 發(fā)起https請(qǐng)求并獲取結(jié)果*/ 
 public static JSONObject httpRequest(String requestUrl,
        String requestMethod, String outputStr) {
        JSONObject jsonObject = null;
        StringBuffer buffer = new StringBuffer(); try { 
 // 創(chuàng)建SSLContext對(duì)象,并使用我們指定的信任管理器初始化 
            TrustManager[] tm = { new MyX509TrustManager() };
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom()); // 從上述SSLContext對(duì)象中得到SSLSocketFactory對(duì)象 SSLSocketFactory ssf = sslContext.getSocketFactory();

            URL url = new URL(requestUrl);
            HttpsURLConnection httpUrlConn = (HttpsURLConnection) url
                    .openConnection();
            httpUrlConn.setSSLSocketFactory(ssf);

            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false); // 設(shè)置請(qǐng)求方式(GET/POST) httpUrlConn.setRequestMethod(requestMethod); if ("GET".equalsIgnoreCase(requestMethod))
                httpUrlConn.connect(); // 當(dāng)有數(shù)據(jù)需要提交時(shí) if (null != outputStr) {
                OutputStream outputStream = httpUrlConn.getOutputStream(); // 注意編碼格式,防止中文亂碼 outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            } // 將返回的輸入流轉(zhuǎn)換成字符串 InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(
                    inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(
                    inputStreamReader);

            String str = null; while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close(); // 釋放資源 inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();
            jsonObject = JSONObject.parseObject(buffer.toString());
        } catch (ConnectException ce) {
            log.error("Weixin server connection timed out.");
        } catch (Exception e) {
            log.error("https request error:{}", e);
        } return jsonObject;
    }
public static Map<String, Object> wxMsgMap(Map<String, Object> allMap,
            String key, String value, String color) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("value", value);
        map.put("color", color);
        allMap.put(key, map); return allMap;

    } 
/**發(fā)送模板消息 */ 
public static JSONObject postTemplateMsg(String accessToken, String OpenId,
        String template_id, String detailUrl, Map<String, Object> map) {
        String url = sendtemplat_url.replace("ACCESS_TOKEN", accessToken);
        JSONObject jso = new JSONObject();
        jso.put("touser", OpenId);
        jso.put("template_id", template_id); if (detailUrl != null)
            jso.put("url", detailUrl);
        jso.put("data", map); return httpRequest(url, "POST", jso.toString());
    }
}
主站蜘蛛池模板: 精品国产一区二区三区四区阿崩 | 欧美性生交xxxxx久久久缅北 | 国产精品成人久久久久a级 欧美特黄一级高清免费的香蕉 | 久久国产精品免费视频 | 精品一区二区三区欧美 | av在线影片 | 日韩视频精品一区 | 国产亚洲精品久久久闺蜜 | 午夜久| 国产成人av一区 | 欧美视频一级 | 国产亚洲美女精品久久久2020 | 91精品国产日韩91久久久久久360 | 亚洲精品一区二区三区大胸 | 午夜精品老牛av一区二区三区 | 一本一本久久a久久精品综合小说 | 91精品福利视频 | av在线观| 欧美一区二区三区久久精品视 | 伊人999| 激情小说另类 | 夜夜夜精品视频 | h视频在线免费观看 | 国产一国产精品一级毛片 | 久草在线小说 | 久久久久久99 | 久久千人斩 | 九九热精 | 午夜精品成人一区二区 | 亚洲最大久久 | 一级α片 | 精品黑人一区二区三区国语馆 | 色就操| 午夜视频在线免费播放 | 黄色大片大毛片 | 越南一级黄色片 | 激情av在线 | jizzzxxxxhd| 中文字幕亚洲视频 | 色a综合| 国产免费一区二区三区最新不卡 |