我试图在wordpress订单完成的钩子上自动下载一个文件(在这种情况下,它是一个PDF发票)。
我首先尝试用wp_remote_get来下载,这似乎很简单,但没有成功(没有文件下载)。
function download_pdf_invoice__on_order_completed( $order_id, $order ) {
wp_remote_get( "http://www.africau.edu/images/default/sample.pdf" );
add_action( 'woocommerce_order_status_completed', 'download_pdf_invoice__on_order_completed', 20, 2 );
到目前为止,我已经设法让它工作,只要URL中含有扩展名,就可以用cURL下载任何文件,但我不能让它在我的动态下载URL中工作,也就是这个测试/演示URL。
https://www.moloni.com/downloads/index.php?action=getDownload&h=b75b2d99c08c56480da0c5dff4900b4a&d=189279574&e=teste@moloni.com&i=1&t=n
function action_woocommerce_admin_order_get_invoice_pdf($url){
//The resource that we want to download.
$fileUrl = 'https://www.moloni.com/downloads/index.php?action=getDownload&h=b75b2d99c08c56480da0c5dff4900b4a&d=189279574&e=teste@moloni.com&i=1&t=n';
//The path & filename to save to.
$saveTo = '/myserver/public_html/wp-content/plugins/my-custom-functionality-master/logo.jpg';
//Open file handler.
$fp = fopen($saveTo, 'w+');
//If $fp is FALSE, something went wrong.
if($fp === false){
throw new Exception('Could not open: ' . $saveTo);
//Create a cURL handle.
$ch = curl_init($fileUrl);
//Pass our file handle to cURL.
curl_setopt($ch, CURLOPT_FILE, $fp);
//Timeout if the file doesn't download after 20 seconds.
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
//Execute the request.
curl_exec($ch);
//Get the HTTP status code.
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
//Close the cURL handler.
curl_close($ch);
add_action( 'woocommerce_order_status_completed', 'action_woocommerce_admin_order_get_invoice_pdf', 20, 2 );
然而,如果我把$fileUrl替换成这个PDF样本http://www.africau.edu/images/default/sample.pdf,它就能工作。
我曾考虑过实现某种错误/日志,以便能够看到代码可能造成的错误,但我还没有想出在这种情况下如何将下载与woocommerce订单完成的动作挂钩。