无法使用curl和PHP在WhatsApp云API中将响应保存为图像

ui7jx7zq  于 2023-08-02  发布在  PHP
关注(0)|答案(1)|浏览(134)

我面临着从 curl 图像保存图像。现在用在curl cli和Postman中,在这两种情况下都可以工作,但在PHP的情况下不工作。
使用curl和Postman:
curl

curl  \
 'https://lookaside.fbsbx.com/whatsapp_business/attachments/?mid=874575937325370&ext=1672595325&hash=ATtpPT6xh31fKJgKmv5gALTnHvlLR8GOZEKR5Ly4WHo-UA' \
 -H 'Authorization: Bearer ACCESS_TOKEN' > image.jpg

字符串
当前PHP代码:

$rptaUrlMedia = "https://lookaside.fbsbx.com/whatsapp_business/attachments/?mid=874575937325370&ext=1672591353&hash=ATu_gBkH9rfUoUwp6-js54WQj3ycCcUHm5Mys4W5slUQxQ";

$ch = curl_init($rptaUrlMedia);

$token = "xxx";

$output_filename = 'demo.png';
$fp = fopen($output_filename, 'wb');
    
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 400);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_CUSTOMREQUEST , "GET");
curl_setopt($ch,CURLOPT_ENCODING , "");
curl_setopt($ch,CURLOPT_FILE , $fp);

$headers = [];
$headers[]  = "Authorization: Bearer " . $token;
$headers[]  = "Accept-Language:en-US,en;q=0.5";
$headers[]  = "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) 
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$raw = curl_exec($ch);
    
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);


请让我知道我在curl cli和PHP脚本中缺少什么,这样我就可以将我的响应保存为jpg格式。
我的主要目的是从URL中获取图像并下载,就像 Postman 在保存为响应时所做的那样。
我已经去另一个Stack Overflow的答案,但没有找到解决方案。
Error WhatAspp cloud API save image using cURL and PHP

p5cysglq

p5cysglq1#

  • 在我的情况下,我不得不使用Guzzlehttp库:
function downloadMedia($mediaUrl , $extension)
{
    $client = new Client();

    try {
        $response = $client->get($mediaUrl, [
            'headers' => [
                'Authorization' => "Bearer {$this->accessToken}"
            ]
        ]);

        if ($response->getStatusCode() === 200) {
            $filename = uniqid('till_slip_') . '_' . time() . '.'.$extension; // Modify the filename
            $filePath = '../till_slips/' . $filename;
            file_put_contents($filePath, $response->getBody());
            $fname =  'uploads/till_slips/' . $filename;
            return $fname;
        } else {
            return null;
        }
    } catch (RequestException $e) {
        return null;
    }
}

字符串

相关问题