zl程序教程

您现在的位置是:首页 >  Javascript

当前栏目

guzzle 使用 json 作为主体请求接口

2023-02-18 16:47:46 时间

在使用第三方插件 Guzzle 请求微信素材管理接口:

接口说明

http请求方式: POST
https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=ACCESS_TOKEN

#参数
{
    "type":TYPE,
    "offset":OFFSET,
    "count":COUNT
}

错误请求代码

$client = new Client();
$response = $client->post("https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=$token", [
          'form_params' => [
              "type"=>"news",
              "offset"=>0,
              "count"=>10
          ]
      ]);

错误原因:请求体格式必须是json 格式 尝试修改代码如下:

$client = new Client();
$response = $client->post("https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=$token", [
          'form_params' =>json_encode([
              "type"=>"news",
              "offset"=>0,
              "count"=>10
          ])
      ]);

仍旧报错。

经查看Guzzle 手册,正确代码如下:

$client = new Client();
$response = $client->post("https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=$token", [
          'json' => [
              "type"=>"news",
              "offset"=>0,
              "count"=>10
          ]
      ]);

可以正常获取到数据。