Simple enterprise WeChat push message development

Enterprise WeChat login address: https://work.weixin.qq.com (preferably an administrator, or register your own enterprise WeChat)
Server api: https://work.weixin.qq.com/api/doc#90001/90143/90371
We find the relevant API driven by the third application message
The application supports push text, picture, video, file, graphic and other types.
Request method: POST (HTTPS) Request address: https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=ACCESS_TOKEN
Parameter Description:
Parameters
   Do you have to
   explain
  access_token
   is
   calling interface voucher
  
each message type specific POST format the following documents.
When the application is set to "always enter the home page in the micro workbench", the application can only receive text messages on the WeChat end, and the length of the text message is limited to 20 bytes, and more than 20 bytes will be truncated. At the same time, other message types will also be converted to text messages, prompting users to go to enterprise WeChat to view.

First we need to get access_token, but what is access_token? You can view the must-read before development, there are three types of access_token,
Distinguish three types of access_token
In the interface provided by third-party application development, three types of access_token are involved. The following table explains the definition and usage scenarios of these three types of tokens. Developers should select corresponding tokens in different scenarios:
Type
   description
   Applicable scenarios The
  service provider's token
   is replaced by corpid (service provider CorpID) and provider_secret (service provider key) for provider_access_token, which represents the service provider's identity
   for service provider-level interface calls, such as login authorization, promotion of QR codes Wait. The documentation refers to obtaining
  the token of the third-party application from the service provider certificate .
   In exchange for suite_id (third-party application ID) and suite_secret (third-party application key) for suite_access_token, it represents the identity of the third-party application and is
   used to obtain the pre-authorization code of the third-party application Authorized corporate information, etc. The documentation refers to Obtaining a third-party application credential to
  authorize the enterprise's token
   . After installing the third-party application, the third-party service provider uses the enterprise's corpid and permanent authorization code to obtain the access_token
   to operate the authorized enterprise-related interfaces, such as address book management, message push, etc. . The documentation refers to Obtaining Enterprise Credentials
   and then the third "Authorized Enterprise Token ". You can see that there is a message push in the usage scenario. Click Get Enterprise Credentials to view.
Obtain corporate credentials
After obtaining the permanent authorization code of the enterprise, the third-party service provider can obtain the access_token of the enterprise through this interface.
Once acquired, these applications can be operated through corporate interfaces such as address books, applications, and messages.

The enterprise access_token obtained here is essentially the same as the token obtained by the enterprise to obtain the access_token, but the way of obtaining it is different. After obtaining, just use the token to call the API interface like ordinary enterprises

The access_token acquisition method required to call the enterprise interface is as follows.
Request method: POST (HTTPS) Request address: https://qyapi.weixin.qq.com/cgi-bin/service/get_corp_token?suite_access_token=SUITE_ACCESS_TOKEN
The enterprise access_token obtained here is essentially the same as the token obtained by the enterprise to obtain the access_token, so I chose the second method.
Get access_token
Request method: GET (HTTPS) Request URL: https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=ID&corpsecret=SECRECT Note: The capitalized word ID and SECRET are marked here, which are variables that need to be replaced , Updated according to the actual acquired value. Other interfaces also use the same label, no description.

If the enterprise installs a third-party application, the service provider can obtain this call credential through "obtain enterprise access_token".

Parameter Description:
The parameter
   must
   indicate that
  corpid
   is the
   enterprise ID and
  corpsecret
   is the
   application's credential key
  authority description:
Each application has an independent secret, so the access_token of each application should be obtained separately
Return results:
{
  "errcode":0,
  "errmsg":"",
  "access_token": "accesstoken000001",
  "expires_in": 7200
}
Parameter
   Description    The credential obtained by
  access_token
, the longest is    the valid time of the
  expires_in
credential of 512 bytes (seconds)
  Error return example:
{
  "errcode":40091,
  "errmsg":"secret is invalid"
}
Special Note:

All interfaces of enterprise WeChat have errcode and errmsg in the return package. Developers need to judge whether the call is successful based on whether errcode is 0 (see global error code for the meaning of errcode).
The errmsg is for reference only and may change in the future, so it cannot be used as a criterion for successful call.
I will not repeat them later.

The enterprise id and application credential key can be found in the terminology introduction, but administrator rights are required
After we get the access_token, we can already push the message. The official API gives a lot of message types. I just developed the text card message simply.
Because the official API for sending messages is very detailed, and the above is included, I just record my thoughts. Therefore, the code directly below.
@Servicepublic class QywxSendMessageServiceImpl implements QywxSendMessageService {private final String agentid = "1000003"; // This is the id of the enterprise application private final String secret = "qiyeyingyongmiyao"; // This is the secret key of the enterprise application, manually update @Override public String sendMessage (Params param) {String qywxId = param.getString ("qywxId"); // Get parameters, id of enterprise WeChat String token = getAccessToken (qywxId, secret); // Get token String userId = param.getString ("userId "); // The userid that was pushed to a specific person String departmentId =" "; String content = param.getString (" context "); // String msgtype =" mytext "; // String agentid =" 1000002 "; // WxConstants.AGENTID is the application's agenid // String content = "Test message push: Your courier has arrived, please bring your work card to the mail center to pick it up. \ NYou can check <a href = \" http: // work. Before departure. weixin.qq.com \ "> Video Center Video Live </a>, smart to avoid queuing.";Map <String, Object> params = new LinkedHashMap <String, Object> (); params.put ("touser", userId); // params.put ("toparty", departmentId); params.put ("agentid", agentid); JSONObject mytext = new JSONObject (); mytext.put ("title", "Reception Notice"); mytext.put ("description", "<div class = \" gray \ "> May 10, 2009 Sunday </ div> <div class = \ "normal \"> Congratulations on winning a Maserati one, winning code: xxxx </ div> <div class = \ "highlight \"> Please be before May 9, 2009 Contact an administrative colleague to collect </ div> "); mytext.put (" url "," url "); mytext.put (" btntxt "," more "); // params.put (" msgtype "," text "); params.put (" msgtype "," textcard "); params.put ("textcard",mytext);        String result="发送失败";        try {            String aa=HttpUtils.httpPostMethod("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + token,  params);            JSONObject parseObject = JSON.parseObject(aa);            String string = parseObject.getString("errcode");            if("0".equals(string)){             result="发送成功";            }else{             result=aa;            }            System.out.println("1.推送消息请求微信接口=="+aa);        } catch (Exception e) {            e.printStackTrace();        }  return result; }  private String getAccessToken(String qywxId, String secret2) {  String url="https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid="+qywxId+"&corpsecret="+secret2+"";  String token=null;  try {   token = HttpUtils.httpGetMethod(url);     } catch (Exception e) {   e.printStackTrace();  }  return token; } }
 
public class HttpUtils {  public static String httpPostMethod(String url,   Map<String, Object> params) {  String returnValue = "接口调用失败";        CloseableHttpClient httpClient = HttpClients.createDefault();        HttpPost post = new HttpPost(url);        post.setHeader("Content-Type","Content-Type");        post.setEntity(new StringEntity(JSON.toJSONString(params), "utf-8"));        CloseableHttpResponse response = null;        try{         response = httpClient.execute(post);         if(response != null && response.getStatusLine().getStatusCode() == 200){          HttpEntity entity = response.getEntity();          returnValue = EntityUtils.toString(entity);                   }        }        catch(Exception e)        {            e.printStackTrace();} finally {try {httpClient.close ();} catch (Exception e) {// e.printStackTrace ();}} // The fifth step: handle return value return returnValue;} public static String httpGetMethod (String url) throws Exception, Exception {CloseableHttpClient httpClient = HttpClients.createDefault (); HttpGet get = new HttpGet (url); CloseableHttpResponse response = null; response = httpClient.execute (get); HttpEntity entity = response.getEntity (); String returnValue = EntityUtils. toString (entity); JSONObject jsonObject = JSON.parseObject (returnValue); String token = jsonObject.getString ("access_token"); // It is recommended to cache the token here to avoid always calling the interface return token;}}} catch (Exception e) {// e.printStackTrace ();}} // The fifth step: handle the return value return returnValue;} public static String httpGetMethod (String url) throws Exception, Exception {CloseableHttpClient httpClient = HttpClients.createDefault ( ); HttpGet get = new HttpGet (url); CloseableHttpResponse response = null; response = httpClient.execute (get); HttpEntity entity = response.getEntity (); String returnValue = EntityUtils.toString (entity); JSONObject jsonObject = JSON.parseObject (returnValue); String token = jsonObject.getString ("access_token"); // It is recommended that the token needs to be cached here to avoid always calling the interface return token;}}} catch (Exception e) {// e.printStackTrace ();}} // The fifth step: handle the return value return returnValue;} public static String httpGetMethod (String url) throws Exception, Exception {CloseableHttpClient httpClient = HttpClients.createDefault ( ); HttpGet get = new HttpGet (url); CloseableHttpResponse response = null; response = httpClient.execute (get); HttpEntity entity = response.getEntity (); String returnValue = EntityUtils.toString (entity); JSONObject jsonObject = JSON.parseObject (returnValue); String token = jsonObject.getString ("access_token"); // It is recommended that the token needs to be cached here to avoid always calling the interface return token;}} }  public static String httpGetMethod(String url) throws Exception, Exception {     CloseableHttpClient httpClient = HttpClients.createDefault();       HttpGet get = new HttpGet(url);       CloseableHttpResponse response = null;       response = httpClient.execute(get);      HttpEntity entity = response.getEntity();   String returnValue = EntityUtils.toString(entity);   JSONObject jsonObject = JSON.parseObject(returnValue);   String token = jsonObject.getString("access_token");   //建议此处需要将token缓存起来,避免总是调用接口  return token;     } } }  public static String httpGetMethod(String url) throws Exception, Exception {     CloseableHttpClient httpClient = HttpClients.createDefault();       HttpGet get = new HttpGet(url);       CloseableHttpResponse response = null;       response = httpClient.execute(get);      HttpEntity entity = response.getEntity();   String returnValue = EntityUtils.toString(entity);   JSONObject jsonObject = JSON.parseObject(returnValue);   String token = jsonObject.getString("access_token");   //建议此处需要将token缓存起来,避免总是调用接口  return token;     } }String returnValue = EntityUtils.toString (entity); JSONObject jsonObject = JSON.parseObject (returnValue); String token = jsonObject.getString ("access_token"); // It is recommended to cache the token here to avoid always calling the interface return token ;}}String returnValue = EntityUtils.toString (entity); JSONObject jsonObject = JSON.parseObject (returnValue); String token = jsonObject.getString ("access_token"); // It is recommended to cache the token here to avoid always calling the interface return token ;}}
————————————————
Copyright Statement: This article is an original article of CSDN blogger "Gaga & Baby", following the CC 4.0 BY-SA copyright agreement, please attach the original source link for reprint And this statement.
Original link: https://blog.csdn.net/aStartStudy/article/details/90215415

Guess you like

Origin www.cnblogs.com/ran-d/p/12698488.html