使用身份验证API密钥获取json

时间:2016-04-07 18:04:02

标签: json curl php-5.3 http-authentication api-key

我正在制作一个由cronjob运行的脚本。

它已经开始获取一些json订单并处理它们。

我的剧本目前看起来像这样:

$json_string = '/admin/orders/7109.json';
$real_url = "https://my-store.myshopify.com{$json_string}";
$user = 'my-user';
$pass = 'my-pass';

$ch = curl_init($real_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, $user . ':' . $pass);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));

$result = json_decode(curl_exec($ch),true);
curl_close($ch);

file_put_contents(__DIR__ . '/../debug/tracker_test.txt', print_r($result,true));

即使我的凭据是正确的,我也会将其写入代码文件。

Array
(
    [errors] => [API] Invalid API key or access token (unrecognized login or wrong password)
)

我错过了什么吗?

编辑:在Shopify的私人应用部分中,它提供了一个示例网址格式:

https://apikey:password@hostname/admin/resource.json

所以现在脚本看起来像这样:

$json_url = 'https://my-api-key:my-api-pass@my-store.myshopify.com/admin/orders.json';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $real_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));

$result = json_decode(curl_exec($ch), true);
curl_close($ch);

但我仍然遇到同样的错误。

1 个答案:

答案 0 :(得分:0)

原来我遇到了语法错误。 我忘了用新的url变量更新CURLOPT_URL

最终看起来像这样:

$json_url = 'https://my-api-key:my-api-pass@my-store.myshopify.com/admin/orders.json';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $json_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));

$result = json_decode(curl_exec($ch), true);
curl_close($ch);