企業微信介面對接之PHP開發實戰經驗分享
企業微信是一款專為企業打造的,幫助企業高效溝通與協同工作的工具。在實際專案開發過程中,我們常常需要將企業微信介面與自己的Web應用程式對接,以實現企業內部資訊的及時傳遞、協同辦公等功能。本文將分享一些在PHP開發中對接企業微信介面的實戰經驗,並附帶對應的程式碼範例,希望對大家有幫助。
一、取得access_token
在使用企業微信介面之前,我們首先需要取得access_token。 access_token是企業微信介面呼叫的憑證,每兩小時需要重新取得一次。
1 2 3 4 5 6 7 8 9 10 11 | <?php
$corpid = 'your_corpid' ;
$corpsecret = 'your_corpsecret' ;
$url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={$corpid}&corpsecret={$corpsecret}" ;
$response = file_get_contents ( $url );
$result = json_decode( $response , true);
$access_token = $result [ 'access_token' ];
?>
|
登入後複製
以上程式碼中,$corpid
是你的企業ID,$corpsecret
是你套用的憑證金鑰。透過呼叫https://qyapi.weixin.qq.com/cgi-bin/gettoken
接口,傳入企業ID和應用程式的憑證金鑰,即可取得access_token。
二、傳送訊息
接下來我們透過企業微信介面發送訊息。企業微信提供了多種訊息類型,如文字訊息、圖文訊息、Markdown訊息等。
1. 傳送文字訊息
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | <?php
$userid = 'userid' ;
$agentid = 'agentid' ;
$content = '这是一条文本消息' ;
$url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={$access_token}" ;
$data = [
'touser' => $userid ,
'msgtype' => 'text' ,
'agentid' => $agentid ,
'text' => [
'content' => $content
]
];
$options = [ 'http' => [
'method' => 'POST' ,
'header' => 'Content-type: application/json' ,
'content' => json_encode( $data ),
]];
$context = stream_context_create( $options );
$response = file_get_contents ( $url , false, $context );
$result = json_decode( $response , true);
?>
|
登入後複製
以上程式碼實作了傳送一則文字訊息的功能。我們需要指定要傳送訊息的使用者ID、應用程式的AgentID和訊息內容。將資料組裝成JSON格式,並透過file_get_contents
函數傳送POST請求,即可實現資訊的傳送。
2. 傳送圖文訊息
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | <?php
$userid = 'userid' ;
$agentid = 'agentid' ;
$title = '图文消息标题' ;
$description = '图文消息描述' ;
$url = 'https://www.example.com' ; // 点击消息后跳转的URL
$picurl = 'https://www.example.com/image.jpg' ; // 图片的URL
$url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={$access_token}" ;
$data = [
'touser' => $userid ,
'msgtype' => 'news' ,
'agentid' => $agentid ,
'news' => [
'articles' => [[
'title' => $title ,
'description' => $description ,
'url' => $url ,
'picurl' => $picurl
]]
]
];
$options = [ 'http' => [
'method' => 'POST' ,
'header' => 'Content-type: application/json' ,
'content' => json_encode( $data ),
]];
$context = stream_context_create( $options );
$response = file_get_contents ( $url , false, $context );
$result = json_decode( $response , true);
?>
|
登入後複製
以上程式碼實作了傳送一則圖文訊息的功能。我們需要指定要傳送訊息的使用者ID、套用的AgentID以及訊息的標題、描述、點擊跳轉的URL和圖片URL。同樣地,將資料組裝成JSON格式,並透過file_get_contents
函數發送POST請求發送訊息。
結語
透過以上的實例程式碼,我們可以輕鬆地在PHP開發中實作企業微信介面的對接。當然,除了發送訊息外,企業微信還提供了許多其他強大的介面功能,例如獲取部門成員清單、上傳媒體檔案、建立會話等等。在實際開發中,可以依照自己的需求進行相關介面的呼叫。
希望以上的實戰經驗可以幫助到大家,如果有任何問題或疑惑,歡迎留言交流。謝謝!
以上是企業微信介面對接之PHP開發實戰經驗分享的詳細內容。更多資訊請關注PHP中文網其他相關文章!