Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working PHP code for Apple-news to create article

UPDATE: Below code works for me. Hope it helps someone to figure out their problem.

After having several errors, it helped going back and looking at all possible error codes on Apple News Developer site. Look at specific error numbers in your code and decide what might be wrong with it.

Follow the examples on the Apple News Developer site. Even though they are vague they do contain crucial information!

//set the timezone
date_default_timezone_set('UTC');

//get json to be sent

$raw = file_get_contents('article.json');
$eol = "\r\n";
$data = '';
$bound= '535e329ca936f79a19ac9a251f7d48f7';

$data='--'.$bound.$eol.
"Content-Type: application/json" . $eol.
"Content-Disposition: form-data; name=metadata" . $eol. $eol.
'{
"data": {
    "isCandidateToBeFeatured": "false",
    "isSponsored": false,
    "isPreview": true     
}
}' .$eol.
'--'.$bound.$eol.
"Content-Type: application/json" . $eol.
"Content-Disposition: form-data; filename=article.json; name=article.json".$eol.$eol.
$raw.$eol.
'--'.$bound.'--'.$eol.$eol;

//set variables
$http_method = 'POST';
$date = gmdate('Y-m-d\TH:i:s\Z');
$key = 'xxx';
$url = 'https://news-api.apple.com/channels/xxx/articles';
$secret = 'xxx';

//cannonical request
$canonical_request = $http_method . $url . $date. 'multipart/form-data; boundary=535e329ca936f79a19ac9a251f7d48f7' . $data;

//Signature
$secretKey = base64_decode($secret);
$hash = hash_hmac('sha256', $canonical_request, $secretKey, true);
$signature = base64_encode($hash);

$authHeader = "HHMAC; key=$key; signature=$signature; date=$date;";
$headers = array();

$headers[] = "Authorization: $authHeader";
$headers[] = "Accept: application/json";
$headers[] = "Content-Type: multipart/form-data; boundary=535e329ca936f79a19ac9a251f7d48f7";
$headers[] = "Content-Length: ".strlen($data); 

//curl options
$ch = curl_init();
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);  
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

//get result
$server_output = curl_exec ($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
echo $status;

curl_close ($ch);
print_r(json_decode($server_output));
like image 447
Erhan Avatar asked Oct 17 '22 21:10

Erhan


1 Answers

Your content type header should be Content-Type: application/json but the content type for authorization is just the value `application/json'. Try to use that in the canonical request instead of the full header.

like image 181
ChristianM Avatar answered Nov 09 '22 23:11

ChristianM