如何在php中使用curl为API服务创建客户?

时间:2014-07-31 12:45:30

标签: php curl

我已成功通过此帖reference link

列出所有客户数据

我正在尝试使用以下php通过API服务创建客户:     

$url = 'https://api.wlvpn.com/v2/customers';
$postData = array("cust_user_id"  => "Jai Lalawat","cust_password" => "12345678","acct_group_id" => 515);
$ch = curl_init();

curl_setopt($ch, CURLOPT_POST, 1);#for post request
curl_setopt($ch, CURLOPT_HEADER, 'Content-Type: application/json');#for header
curl_setopt($ch, CURLOPT_USERPWD, "api-key:my-api-key");#for -u option authentication
curl_setopt($ch, CURLOPT_POST, count($postData));#count post data
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData); #send post request data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSLVERSION, 3);


$output = curl_exec($ch);
$curl_error = curl_error($ch);
curl_close($ch);

print_r($output);
print_r($curl_error);
?>

但我收到以下错误

{"api_status":0,"error":"Invalid account group"}

但是,当我从ubuntu中的命令行运行以下命令时:

curl -X POST -H 'Content-Type: application/json' -u api-key:my-api-key -d '{"cust_user_id":"jaitest","cust_password":"12345678","acct_group_id":"515"}' https://api.wlvpn.com/v2/customers

我得到了预期的回复

任何人都可以帮助我,我在这里失踪了。

1 个答案:

答案 0 :(得分:1)

在CLI示例中,您将JSON数据传递给API。您正在PHP示例中提供表单数据。

您需要将数据作为JSON传递,如下例所示:

<?php

$url = 'https://api.wlvpn.com/v2/customers';
$postData = array("cust_user_id"  => "Jai Lalawat","cust_password" => "12345678","acct_group_id" => 515);

$body = json_encode($postData);

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($body)
));

$result = curl_exec($ch);