我正在尝试调用一个API,该API应该返回一个XML来为订单创建一个Label。
我有这个文件:
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 ..
答案 0 :(得分:2)
你没有打印任何东西,所以它可能会返回xml而你却看不到结果..试试var_dump(createLabel());
答案 1 :(得分:0)
标题行是您自己请求的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'));
答案 2 :(得分:0)
遇到同样的问题,也许它不再与你有关,但我用下面的代码解决了它。
$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);
}
了解每个标签只能通过此次通话打印一次,这一点非常重要。所以第二次结果是空的。我建议第一次存储结果。