[英]POST Call to an API with an XML in PHP
我正在嘗試調用一個 API,該 API 應該返回一個 XML 來為訂單創建一個標簽。
我有這個文件:
Type of request:
GET
URL PROD:
https://api.bpost.be/services/shm/{accountID}/orders/{OrderReference}/labels/{size}
Headers for PDF labels:
Authorization: Basic AccountID:pass-phrase (base64)
Content-Type: application/vnd.bpost.shm-labelRequest-v3+XML
Accept: application/vnd.bpost.shm-label-pdf-v3+XML
當我在 Rest Console 中嘗試參數時它工作正常,但我對 PHP 相當陌生,所以我在實現它時遇到了麻煩。
到目前為止我的代碼:
<?php
header('Content-Type: application/vnd.bpost.shm-labelRequest-v3+XML');
header('Accept: application/vnd.bpost.shm-label-pdf-v3+XML');
header('Authorization: Basic MTE4MDI1OjEyMzQ=');
function createLabel(){
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://api.bpost.be/services/shm/ID/orders/1634/labels/A6');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$resp = curl_exec($curl);
curl_close($curl);
return $resp;
}
createLabel();
?>
有人對此有想法嗎?
編輯:我再次使用 file_get_contents :
$context = stream_context_create(array(
'http' => array(
'header' => ["Authorization: Basic " . base64_encode("$username:$password"),
"Accept: application/vnd.bpost.shm-label-pdf-v3+XML",
"Content-Type: application/vnd.bpost.shm-labelRequest-v3+XML"]
)
));
$res = file_get_contents('https://api.bpost.be/services/shm/118025/orders/1638/labels/A6', false, $context);
$xml = new SimpleXMLElement($res);
var_dump($res);
var_dump($xml);
2 var_dump 的結果:
string(319) "" object(SimpleXMLElement)#1 (0) { }
所以我想我檢索了一些信息,但是如何提取它? 這個 API 調用應該給我一個 PDF ..
您沒有打印任何內容,因此它可能會返回 xml,而您只是看不到結果.. 嘗試 var_dump( createLabel());
帶有標題的行是您自己的請求的 RESPONSE 標題:
header('Content-Type: application/vnd.bpost.shm-labelRequest-v3+XML');
header('Accept: application/vnd.bpost.shm-label-pdf-v3+XML');
header('Authorization: Basic MTE4MDI1OjEyMzQ=');
所以這些標頭會隨着您的請求返回; 您需要將它們添加到 curl 請求中:
curl_setopt($ch,CURLOPT_HTTPHEADER,array('HeaderName: HeaderValue','HeaderName2: HeaderValue2'));
遇到同樣的問題,也許它不再與您相關,但我用以下代碼解決了它。
$username = 'accountid';
$password = 'passphrase';
$context = stream_context_create(array(
'http' => array(
'header' => ["Authorization: Basic " . base64_encode("$username:$password"),
"Content-Type: application/vnd.bpost.shm-labelRequest-v3+XML",
"Accept: application/vnd.bpost.shm-label-pdf-v3+XML"]
)
));
$res = file_get_contents('https://api.bpost.be/services/shm/'.$username.'/orders/'.$order.'/labels/A6', false, $context);
$xml = simplexml_load_string($res);
foreach($xml->label as $item) {
header('Content-type: application/pdf');
header('Content-Disposition: attachment; filename="bpost_'.$order.'.pdf"');
echo base64_decode((string)$item->bytes);
}
重要的是要知道每個標簽只能通過此調用打印一次。 所以第二次結果將是空的。 我建議第一次存儲結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.