【问题标题】:GET json with authentication API key使用身份验证 API 密钥获取 json
【发布时间】:2016-04-07 18:04:01
【问题描述】:

我正在制作一个由 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 的私有应用部分,它提供了一个示例 url 格式:

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);

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

【问题讨论】:

  • 看起来不错,我想说.. 尝试像这样发送用户名和密码:"$username:$password" 并像这样发送 url:curl_setopt($ch, CURLOPT_URL, $url) ;
  • 你的意思是"{$username}:{$password}" ?
  • 另外,尝试首先将 curl_exec($ch) 的输出放入一个变量中,然后对该变量进行编码。另一件事可能是您也可能需要发送某种令牌。喜欢这里stackoverflow.com/questions/30426047/…
  • 不,只需像这样添加它 "$username:$password"

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


【解决方案1】:

原来我有一个语法错误。 我忘了用新的 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-04
    • 1970-01-01
    • 1970-01-01
    • 2018-08-17
    • 2021-01-22
    • 2021-02-10
    • 1970-01-01
    • 2021-11-16
    相关资源
    最近更新 更多