Apple新闻API。连接和发送JSON数据的PHP代码
问题描述:
我能够连接苹果新闻API的帮助,但我无法发送JSON格式的数据。 我的代码如下。 但是当我尝试附加JSON文件。我收到签名失败消息。Apple新闻API。连接和发送JSON数据的PHP代码
<?php
$channel_id = 'xxxxxxxxxxxxxxxxxx';
$api_key_id = 'xxxxxxxxxxxxxxx';
$api_key_secret = 'xxxxxxxxxxxxxxxx';
// use the correct values above
$data = file_get_contents('article.json');
$Content_type="application/json";
$url = 'https://news-api.apple.com/channels/'.$channel_id;
$date = gmdate('Y-m-d\TH:i:s\Z');
$canonical_request = 'GET'.$url.$date.$Content_type;
$key = base64_decode($api_key_secret);
$hashed = hash_hmac('sha256', $canonical_request,$key,true);
$signature = base64_encode($hashed);
echo $signature;
//curl options
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
$headers = array();
$headers[] = "Authorization: HHMAC; key={$api_key_id}; signature={$signature}; date={$date}";
$headers[] = "Content-Type: application/json";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
//curl_setopt($ch, CURLOPT_POST, true);
//curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
//get result
$server_output = curl_exec ($ch);
curl_close ($ch);
print_r(json_decode($server_output));
?>
答
既然你发送GET
要求,你是不正确的,包括建立规范的请求时,内容类型。
这应该为你工作,那么:
$canonical_request = 'GET'.$url.$date;
仅供参考,请参阅Apple News API Reference: Setting Up MAC/HMAC Authentication:
创建请求的规范版本为以下逐字节级联:
- HTTP方法(例如,GET或POST,在全部大写)
- 请求的完整网址
- 当前日期ISO 8601格式
如果请求是一个POST请求,它包括一个实体,包括以下内容:
- 在Content-Type头的值
- 的实体的完整内容