2017-08-18 105 views
1

我正在將wordpress網站與外部API集成。我有一個表單發佈到我的服務器,我在我的服務器上調用了一個對外部API進行wp_remote_get調用的函數。將pdf從wp_remote_get發送到瀏覽器

外部API返回一個PDF,與像頭:

 [date] => Fri, 18 Aug 2017 15:59:19 GMT 
     [x-powered-by] => Servlet/3.0 
     [cache-control] => no-cache 
     [content-type] => application/pdf;charset=utf-8 
     [content-language] => en-US 

和響應身體是PDF討厭的字符串格式,這似乎是一個良好的開端。

如何將此PDF傳遞給用戶的瀏覽器? 即

$response = wp_remote_get($url, array (//stuff the request needs)); 
if (is_wp_error ($response)) { 
    $error_message = $response->get_error_message(); 
    echo "Something went wrong: $error_message"; 
} else { 
    //What here? 
} 

我得先打我的服務器,不能直接發帖的形式向外部API。

回答

0

我管理了此項通過使用javascript來重定向我的表單提交到我的網站上的一個新窗口,作爲URL參數傳遞表單信息。 即 在我的HTML:

<form onsubmit="return qrsDownload()"> 

然後在javascript:

function qrsDownload() { 
    // a bunch of jquery and processing to build the URL.. 
    window.open(url, 'My Title', 'width=800, height=600'); 
} 

我打開了我創建了一個一次性使用的頁面模板,我省略了標準WP模板的頁面(所以沒有頁眉,頁腳沒有,沒有WordPress的循環),並在該頁面的PHP文件:

<?php 
if (isset($_GET['someParam'])) { 
    // started off with logic to verify that I had the params needed 
    // because anybody could just jump directly to this page now 
} 
$url = "whateverurl.com/myendpoint"; 
// additional logic to set up the API call 
$server_response = wp_remote_get($url, $args); 
if (is_wp_error($server_response)) { 
    // do something to handle error 
} else { 
    // PASS OUR PDF to the user 
    $response_body = wp_remote_retrieve_body($server_response); 
    header("Content-type: application/pdf"); 
    header("Content-disposition: attachment;filename=downloaded.pdf"); 
    echo $response_body; 
} 
} else { 
    get_header(); 
    $html = "<div class='content-container'><p>A pretty error message here.</p></div>"; 
    echo $html; 
    get_footer(); 
} 

?> 

這種方法基本上是通過從API斯特拉結果ight退出用戶,但您需要標題來指定它是PDF,並且在寫出任何輸出之前必須設置標題。確保這一點的一種更簡單的方法是在新窗口中完成,而不是嚴格按照表格回發。