天天看點

一、微信公衆号和小程式開發(擷取TOKEN AND 推送)WechatAPI_BackEnd_TOKEN_OPENID#二、擷取Token(用于對公衆号和小程式進行操作)

WechatAPI_BackEnd_TOKEN_OPENID

一、前期準備

  1. 有一台公網IP的伺服器
  2. 注冊域名并進行備案(保證合法開啟80端口)
  3. 在微信公衆号平台 AND 小程式平台 填寫伺服器相關配置和回調位址
  4. 拉取Demo、數字簽名等等
  5. 進行微信認證
  6. 可以直接用80端口運作、也可以在有域名的情況下進行綁定其他端口。

#二、擷取Token(用于對公衆号和小程式進行操作)

“原理:你去異步通路他、帶上相應參數、成功的話就能下載下傳一個檔案、這個檔案裡面就有相應的token”

1.公衆号

1. 調用service方法(從網絡Url中下載下傳檔案):

https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=唯一辨別&secret=唯一密碼

2. 讀取檔案中的Token

public String UpdateToken(HttpServletRequest request) throws IOException {
         String tokenURL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx2b1927149d977111&secret=bf18aa42e02f697211a496882c7c1111";
         File TokenFile = new File(this.getClass().getResource("").getFile() + "/token.txt");
         HTTPUtils.downLoadFromUrl(tokenURL, "token.txt", TokenFile.getParent());
 
         System.out.println(TokenFile.getAbsolutePath());
 
         List<String> stringList = IOUtils.readLines(new FileInputStream(TokenFile));
 
         String token = stringList.get(0);
 
 
         String[] tokenParse = token.substring(1, token.length()).replaceAll("\"", "").split(",");
         String[] result = tokenParse[0].split(":");
 
 
         if (result[0].equals("access_token")) {
             System.out.println("擷取token成功");
             System.out.println(result[1]);
             request.getServletContext().setAttribute("WeachatToken", result[1]);
             return result[1];
         } else {
             System.out.println("擷取token失敗");
             return "擷取token失敗";
         }
     }
           

2.小程式

三、擷取Openid(對公衆号和小程式的使用者進行操作)

“其實原理就是、你去重定向他、帶上他想要的東西。然後他會吸收掉參數、然後來通路你的接口”

1.進行消息推送(公衆号)

1.拿到code:

進行重定向https://open.weixin.qq.com/connect/oauth2/authorize?appid=唯一辨別&redirect_uri=" + 回調位址(給需要openid的方法) + "&response_type=code&scope=snsapi_userinfo&state=13392876810#wechat_redirect=asd

2.拿到Openid:

寫一個API接口接收code,通路https://api.weixin.qq.com/sns/oauth2/access_token?appid=唯一辨別&secret=唯一密碼&code=" + 第一步會帶來的參數 + "&grant_type=authorization_code

2.進行消息推送(小程式)

END:codding項目位址

https://git.dev.tencent.com/a83841070/WechatAPI_BackEnd_TOKEN_OPENID.git
[email protected]:a83841070/WechatAPI_BackEnd_TOKEN_OPENID.git