微信公眾號開發-靜默授權實現消息推送(微服務方式)


  一:引用pom

    <dependency>
      <groupId>com.github.binarywang</groupId>
      <artifactId>weixin-java-mp</artifactId>
      <version>${weixin-java-mp.version}</version>
    </dependency>

 

二:獲取code

  注意:redirect_uri 回調地址。請求完成后,微信在回調該地址的時候會帶上code,然后根據code去拿openId。親測不需要編碼!!!

       要在微信客戶端打開接口地址,推薦工具https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1455784140 微信官方web開發工具。

  傳入appId就行了,state是回調的時候帶的參數

  @ApiOperation(value = "獲取code,並回調獲取openId", notes = "獲取code,並回調獲取openId")
  @GetMapping(value = "/routerForOpenId")
  public void redirectToMyPage(HttpServletRequest request, HttpServletResponse response,
      String phone) {
    StringBuffer sb = new StringBuffer();
    StringBuffer encodeUrl = new StringBuffer(300);
    //公眾號中配置的回調域名(網頁授權回調域名)
//    String doname =
//        request.getScheme() + "://" + request.getServerName() + (-1 == request.getLocalPort() ? ""
//            : ":" + request.getLocalPort());
    String doname = "http://xuexing.ngrok.xiaomiqiu.cn";
    String root = "/WeChat";
    String appId = "wxb6fac4047e049312";
    sb.append("https://open.weixin.qq.com/connect/oauth2/authorize?appid=");
    sb.append(appId);
    String url = "";
    try {
      //對重定向url進行編碼,官方文檔要求
      encodeUrl.append(doname).append(root).append("/openId.html");
//      url = URLEncoder.encode(encodeUrl.toString(), "utf-8");
      sb.append("&redirect_uri=").append(encodeUrl.toString());
      //網頁授權的靜默授權snsapi_base
      sb.append("&response_type=code&scope=snsapi_base&state=").append(phone);
      sb.append("#wechat_redirect");
      response.sendRedirect(sb.toString());
    } catch (UnsupportedEncodingException e) {
      log.error("重定向url編碼失敗:>>" + e.getMessage());
      e.printStackTrace();
    } catch (Exception e) {
      log.error("response重定向失敗:>>" + e.getMessage());
      e.printStackTrace();
    }
  }

三:回調地址方法

  調用回調地址之前需要一些准備工作:

  1,回調地址需要做一個內網穿透,推薦工具Ngrok,花生殼。。本人使用的是Ngrok

    1)在Ngrok官網下載好客戶端 http://www.ngrok.cc/download.html  

    

 

    2)在官網注冊賬號並開通隧道 http://www.ngrok.cc  按官網教程開通,有免費隧道,完全可以滿足本地開發使用。

    3)運行Sunny-Ngrok啟動工具.bat   在命令行中輸入 clientId (就是在官網注冊的郵箱)和 隧道Id(看清,是Id 不是名字)

    4)成功后界面,恭喜你內網穿透已經做好,可以在外網環境訪問你的服務接口了。

     

 

  2,配置微信授權域名

    1)微信公眾平台 https://mp.weixin.qq.com/ 

    

    

      

      

     2)在保存的時候,會驗證是否在你域名的根目錄下保存了這個文件。事實上他驗證的本質就是通過 [域名+/txt文件名] 是否能訪問到txt文件中的字符碼,所以我們在微服務中寫一個接口將文件中字符返回出來,保存的時候就能校驗通過了。

      注意:[域名+/txt文件名]和[域名+/openId.html]一定要都可以訪問同,微信才能通過 redirect_uri 回調

       

 

     

    

@ApiOperation(value = "回調獲取openId", notes = "回調獲取openId")
  @GetMapping(value = "/openId.html")
  //發送請求,根據code獲取openId
  public String getOpenId(HttpServletRequest request, HttpServletResponse response, String code,
      String state) {

    String content = "";
    String openId = "";
    String unionId = "";
    //封裝獲取openId的微信API
    StringBuffer url = new StringBuffer();
    url.append("https://api.weixin.qq.com/sns/oauth2/access_token?appid=")
        .append("wxb6fac4047e049312")
        .append("&secret=")
        .append("726b163b73fe82a282903084805b663a")
        .append("&code=")
        .append(code)
        .append("&grant_type=authorization_code");

    ObjectMapper objectMapper = new ObjectMapper();
    try {
      HttpGet httpGet = new HttpGet(url.toString());//這里發送get請求
      HttpClient httpClient = HttpClientBuilder.create().build();
      HttpResponse httpResponse = httpClient.execute(httpGet);
      // 判斷網絡連接狀態碼是否正常(0--200都數正常)
      if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        content = EntityUtils.toString(httpResponse.getEntity(), "utf-8");
      }
      Map map = objectMapper.readValue(content, Map.class);
      openId = String.valueOf(map.get("openid"));
      unionId = String.valueOf(map.get("unionid"));

      log.info("獲取的openID:" + openId);
      /*
       * 將openId保存到session中,當其他業務獲取openId時,
       * 可先從session中獲取openId.
       */
      request.getSession().setAttribute("openId", openId);
    } catch (JsonParseException e) {
      log.error("json解析失敗:", e);
    } catch (JsonMappingException e) {
      log.error("map轉換成json失敗:", e);
    } catch (Exception e) {
      log.error("http獲取openId請求失敗:", e);
    }
    return openId;
  }

 在這里我們就能夠拿到當前微信用戶的openid 並在消息推送的時候進行用戶 判斷,來針對性的推送


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM