Guzzle HTTP使用筆記


首先來一段官方文檔對Guzzle的介紹:

Guzzle是一個PHP的HTTP客戶端,用來輕而易舉地發送請求,並集成到我們的WEB服務上。

  • 接口簡單:構建查詢語句、POST請求、分流上傳下載大文件、使用HTTP cookies、上傳JSON數據等等。
  • 發送同步或異步的請求均使用相同的接口。
  • 使用PSR-7接口來請求、響應、分流,允許你使用其他兼容的PSR-7類庫與Guzzle共同開發。
  • 抽象了底層的HTTP傳輸,允許你改變環境以及其他的代碼,如:對cURL與PHP的流或socket並非重度依賴,非阻塞事件循環。
  • 中間件系統允許你創建構成客戶端行為。

 

 

執行Composer命令下載Guzzle:Linux環境、Windows都一樣

composer require guzzlehttp/guzzle

 

下載完成后會生成一個vender文件夾:

我這邊使用的Tp5框架進行開發。

因為Guzzle屬於PHP的第三方擴展,所以使用前先  use引用  接着實例化*******

<?php
namespace app\admin\controller;

use app\admin\controller\BasicAdmin;
use app\admin\service\DataService;
use GuzzleHttp\Client;
use think\Db;

class News extends BasicAdmin
{//企業微信推送消息
    public function send_message()
    {
        //實例化 GuzzleHttp
        $client = new Client();
        //文章id
        $news_id = input('news_id');
        //查詢文章
        $news_data = Db::table('wm_news')->where('id',$news_id)->find();
        //企業微信參數
        $corpid = "*************";
        $secret = "*********";
        //先通過token獲取 access_token
        $access_token = cookie('access_token');
        //如果access_token為空,則去獲取,存儲
//如果推送的消息沒有圖片則給一張企業默認圖片
if (empty($news_data['img_url'])) { $news_data['img_url'] = 'https://tcms.living-power.com/static/images/common/lingpa.jpg'; } if (empty($access_token)) { $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=".$corpid."&corpsecret=".$secret; $response = $client->request('GET',$url); $body = $response->getBody();//獲取相應體 $html = $body->getContents();//獲取目標頁面 //解密json字符串 $res = json_decode($html,true); //存儲access_token $access_token = $res['access_token']; } $agentid = "1000002"; //推送消息 //如果推送的消息沒有圖片則給一張企業默認圖片 if (empty($news_data['img_url'])) { $news_data['img_url'] = 'http://cms.living-power.com/static/images/common/lingpa.jpg'; } $msgUrl = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=".$access_token; $send_msg['touser'] = '@all'; $send_msg['msgtype'] = 'news'; $send_msg['agentid'] = $agentid; $send_msg['news']['articles'][0]['title'] = $news_data['title']; $send_msg['news']['articles'][0]['description'] = strip_tags($news_data['content']); $send_msg['news']['articles'][0]['url'] = 'https://tqymobile.living-power.com/index.php/blog/news/detail?id='.$news_id; $send_msg['news']['articles'][0]['picurl'] = $news_data['img_url']; $send_msg['safe'] = 0; //$send_msg = json_encode($send_msg); $response = $client->request('POST',$msgUrl,['json' => $send_msg]); $body = $response->getBody();//獲取相應體 $html = $body->getContents();//獲取目標頁面 //解密json字符串 $res = json_decode($html,true); // print_r($res);die(); } }

具體參考文檔:https://guzzle-cn.readthedocs.io/zh_CN/latest/

 


免責聲明!

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



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