issue uploading media files on /media whatsapp cloud api

190 Views Asked by At

I am trying to upload a file through WhatsApp Cloud API so, I am using a simple cURL request to do it.

public function meta_upload_media2($token,$phonesid,$tipo,$archivo,$filename)
    {        

        $ch = curl_init();
        $url = 'https://graph.facebook.com/v18.0/'.$phonesid.'/media';

        $fileFinal=new \CURLFile($archivo,$tipo,$filename);
        
        $data = array(
            'file' => $fileFinal,
            'type' => $tipo,
            'messaging_product' => 'whatsapp'
        );
        $headers = array(); 
        
        $headers[] = 'Authorization: Bearer ' . $token ;

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        
        $result = curl_exec($ch);        

        if($result === false) {
            $result = curl_error($ch) . " - ".curl_errno($ch);
            //return false;
            
        }else{
            $resultDecode = json_decode($result);
            if($resultDecode!=null){
                $result = $resultDecode;
            }
            return($result);
            //return true;
        }
        curl_close($ch);
    }  

I am unable to upload the file, I got the following error:

"error": { "message": "An unknown error has occurred.", "type": "OAuthException", "code": 1, "fbtrace_id": "ActSWlPfhEOVpbiN2QmIf7X" }

FYI: ** I am on CI4 and PHP 8.1 ** $filename is a random filename ** $archivo is a full path file, ex. /home/user/public_html/uploads/random-file-name.pdf

Any help is really appreciate. Thanks!

1

There are 1 best solutions below

1
On

Solved using the following code

$ch = curl_init();
        $url = 'https://graph.facebook.com/v18.0/'.$phonesid.'/media';
        
        $data = array(
            'file' => new \CURLFile($archivo,$type),
            'type' => $type,
            'messaging_product'=>'whatsapp'
        );
        $headers = array(); 
        
        $headers[] = 'Authorization: Bearer ' . $token ;
        $headers[] = 'Content-type: multipart/form-data';

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        
        $result = curl_exec($ch);        

        if($result === false) {
            $result = curl_error($ch) . " - ".curl_errno($ch);
            //return false;
            
        }else{
            $resultDecode = json_decode($result);
            if($resultDecode!=null){
                $result = $resultDecode;
            }
            return($result);
            //return true;
        }
        curl_close($ch);