PHP cURL,帮助创建API调用脚本

时间:2016-06-01 13:56:49

标签: php api curl

我想要一些帮助,请创建一个cURL片段来调用API。

非常感谢任何协助。

这是API调用

POST https://api.passes.com/v1/templates/names/Member%20Card/pass

显然他们需要以下发送

------------------------------330184f75e21
Content-Disposition: form-data; name="values"; filename="values.json"
Content-Type: application/json

{
    "firstName": "John",
    "lastName": "Doe",
}
------------------------------330184f75e21
Content-Disposition: form-data; name="icon"; filename="icon.png"
Content-Type: application/octet-stream

imagedata
------------------------------330184f75e21
Content-Disposition: form-data; name="icon@2x"; filename="icon@2x.png"
Content-Type: application/octet-stream

imagedata

我不确定在cURL中放置什么。

我尝试了以下但没有成功。

$url1 = 'https://api.passes.com/v1/templates/names/Test/pass';

$data1 = array("values" => '{"first":"John","last":"Doe"}','application/json',
                "strip" => '@../uploads/icon.png','application/octet-string','icon.png',
                "strip@2x" => '@../uploads/icon.png','application/octet-string','icon.png');

$auth1 = array(  "authorization: Basic xxxxxxxxxxxx=",  "cache-control: no-cache",  "postman-token: xxxxxxxxx");

$ch1 = curl_init($url1);
curl_setopt($ch1, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch1, CURLOPT_POST, 1);
curl_setopt($ch1, CURLOPT_POSTFIELDS, $data1);
curl_setopt($ch1, CURLOPT_HEADER, 0);
curl_setopt($ch1, CURLOPT_HTTPHEADER, $auth1);

$response1 = curl_exec($ch1);

echo $response1;

回复时回复说无效的JSON

如果有人能提供帮助那就太棒了。

谢谢

罗布

1 个答案:

答案 0 :(得分:2)

你不应该写原始的json字符串,但让PHP为你做。

$values = array(
    'first' => 'John',
    'last' => 'Doe'
);

$data1 = array(
    'values' => json_encode($values),
    'strip' => '@../uploads/icon.png',
        'application/octet-string',
        'icon.png',
    'strip@2x' => '@../uploads/icon.png',
        'application/octet-string',
        'icon.png'
);