【问题标题】:How can I create a customer to a API service using curl in php?如何在 php 中使用 curl 为 API 服务创建客户?
【发布时间】:2014-07-31 12:45:30
【问题描述】:

我已成功通过此帖子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

我收到了预期的回复

任何人都可以帮助我在这里缺少什么。

【问题讨论】:

  • 他们不是同一个账户组。您的 PHP 示例中有 517,命令行示例中有 515
  • 任何客户拥有相同的账户组
  • 两者是不同的帐户组,并且该组存在
  • 从外观上看,你提交 json 数据的命令行和你发送 post 数据的 php
  • 在命令行中它是标题,当你看到所有命令时它是发布请求而不是获取请求

标签: php curl


【解决方案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);

【讨论】:

    猜你喜欢
    • 2015-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多