【问题标题】:Converting Request from CURL to PHP's Guzzle to access WHMCS API将请求从 CURL 转换为 PHP 的 Guzzle 以访问 WHMCS API
【发布时间】:2016-04-11 14:24:13
【问题描述】:

我正在尝试学习最新版本的 Guzzle (6.2) 并将我的 cURL 请求转换为 WHMCS API。

使用来自http://docs.whmcs.com/API:JSON_Sample_Code的示例代码

// The fully qualified URL to your WHMCS installation root directory
$whmcsUrl = "https://www.yourdomain.com/billing/";

// Admin username and password
$username = "Admin";
$password = "password123";

// Set post values
$postfields = array(
    'username' => $username,
    'password' => md5($password),
    'action' => 'GetClients',
    'responsetype' => 'json',
);

// Call the API
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $whmcsUrl . 'includes/api.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postfields));
$response = curl_exec($ch);
if (curl_error($ch)) {
    die('Unable to connect: ' . curl_errno($ch) . ' - ' . curl_error($ch));
}
curl_close($ch);

// Attempt to decode response as json
$jsonData = json_decode($response, true);

// Dump array structure for inspection
var_dump($jsonData);

我还没有弄清楚如何使用 Guzzle 实现相同的功能。

这是我尝试过的:

use GuzzleHttp\Client;

// The fully qualified URL to your WHMCS installation root directory
$whmcsUrl = "https://www.yourdomain.com/billing/";

// Admin username and password
$username = "Admin";
$password = "password123";

$client = new Client([
    'base_uri' => $whmcsUrl,
    'timeout'  => 30,
    'auth' => [$username, md5($password)],
    'action' => 'GetClients',
    'responsetype'  =>  'json'
]);

$response = $client->request('POST', 'includes/api.php');
echo $response->getStatusCode();
print_r($response,true);

对于以前使用过 Guzzle 的人来说,这很可能是一个非常明显的答案。

我哪里错了?

【问题讨论】:

    标签: php api curl guzzle psr-7


    【解决方案1】:

    我认为您需要使用 'form_params' 发送 urlencoded POST 数据:

    $username = "Admin";
    $password = "password123";
    
    // Set post values
    $postfields = array(
        'username' => $username,
        'password' => md5($password),
        'action' => 'GetClients',
        'responsetype' => 'json',
    );
    
    $client = new Client([
        'base_uri' => 'https://www.yourdomain.com',
        'timeout'  => 30,
    ]);
    
    $response = $client->request('POST', '/billing/includes/api.php', [
        'form_params' => $postfields
    ]);
    

    【讨论】:

    • 做到了!非常感谢!
    猜你喜欢
    • 2015-11-02
    • 2017-01-13
    • 2014-09-17
    • 2019-12-17
    • 2017-04-04
    • 2015-02-13
    • 1970-01-01
    • 2017-05-25
    • 2017-08-03
    相关资源
    最近更新 更多