Posts tagged with php

hello guys im trying to automate a stories video post on facebook but dont know what im doing wrong, my picture stories function works fine but my video one is not working at all!!! i tried to look over here and documentation for a answer but couldnt find a solution! in the first 10 calls i was getting errors from graph and from now on i keep getting erro 500! does anyone knows what i can be doing wrong?

    function postStoriesVideoFacebook($fb, $pageId, $pageAccessToken, $mediaUrls){         $mediaUrls = 'https://sample-videos.com/video123/mp4/720/big_buck_bunny_720p_1mb.mp4';        // Etapa 1: Inicializar a sessão de upload        $response = $fb->post("/{$pageId}/video_stories", [         'upload_phase' => 'start',     ], $pageAccessToken);     $initData = $response->getDecodedBody();     $videoId = $initData['video_id'];     $uploadUrl = $initData['upload_url'];     // Debugging - Verificando as variáveis     var_dump($initData, $videoId, $uploadUrl);     // Etapa 2: Fazer upload do vídeo usando a URL remota     $ch = curl_init();     curl_setopt($ch, CURLOPT_URL, $uploadUrl);     curl_setopt($ch, CURLOPT_POST, true);     curl_setopt($ch, CURLOPT_HTTPHEADER, [         "Authorization: OAuth $pageAccessToken", // Passando o token como OAuth         "file_url: $mediaUrls"     ]);     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);     $uploadResponse = curl_exec($ch);     curl_close($ch);     $uploadData = json_decode($uploadResponse, true);     // Debugging - Verificando a resposta do upload     var_dump($uploadData);     if (isset($uploadData['success']) && $uploadData['success'] === true) {         // Etapa 3: Publicar o vídeo nos Stories         $finishResponse = $fb->post("/{$pageId}/video_stories", [             'upload_phase' => 'finish',             'video_id' => $videoId,         ], $pageAccessToken);         $result = $finishResponse->getDecodedBody();         // Debugging - Verificando a resposta da publicação         var_dump($result);         if (isset($result['success']) && $result['success'] === true) {             return $result['post_id']; // Retorna o ID do post se a publicação for bem-sucedida         } else {             throw new Exception('Erro ao publicar o vídeo nos Stories.');         }     } else {         throw new Exception('Erro ao fazer upload do vídeo.');     } } 

forums , using direct the cURL options, postman etc

Hey guys so im trying to automate the post on intagram in my app using the api graph from facebook, i already got the single post of pictures and videos of reels, stories, and post, got as well a carousel of pictures but im having a lot of problem trying to make works to POST a carousel that contais or just reels (videos) and mixed onde having reels and pictures, most of the time i pass the process of creating the container for the first video or picture (when mixed) but in the second one usully or i get a timeout or a erro from graph that dont specify nothing or it fails to create the 2 container and pass the status finished, if anyone can help me would be much appreciated ! my code below !

 function postOnInstagram($fb, $message, $mediaUrls = [], $isCarrosel = false, $pageAccessToken, $instagramAccountId, $hasVideo = false, $typePost){   $fb->setDefaultAccessToken($pageAccessToken);   try {       switch ($typePost) {           case 'post':               if ($hasVideo) {                   return $isCarrosel                        ? postInstagramMediaCarousel($fb, $instagramAccountId, $message, $mediaUrls)                       : postInstagramSingleVideo($fb, $instagramAccountId, $message, $mediaUrls[0]);               } else {                   return $isCarrosel                        ? postInstagramPhotoCarousel($fb, $instagramAccountId, $message, $mediaUrls)                       : postInstagramSinglePhoto($fb, $instagramAccountId, $message, $mediaUrls[0]);               }           case 'reel':               if (!$hasVideo) {                   throw new Exception("Reels require a video");               }               if ($mediaUrls > 1) {                 return postInstagramMultipleVideos($fb, $instagramAccountId, $message, $mediaUrls);               }               else {                 return postInstagramReel($fb, $instagramAccountId, $message, $mediaUrls[0]);               }           case 'story':               if ($hasVideo) {                   return postInstagramStoryVideo($fb, $instagramAccountId, $message, $mediaUrls[0]);               } elseif (!empty($mediaUrls)) {                   return postInstagramStoryPhoto($fb, $instagramAccountId, $message, $mediaUrls[0]);               } else {                   return postInstagramStoryText($fb, $instagramAccountId, $message);               }           default:               throw new Exception("Invalid post type");       }   } catch (FacebookResponseException $e) {       return 'Graph returned an error: ' . $e->getMessage();   } catch (FacebookSDKException $e) {       return 'Facebook SDK returned an error: ' . $e->getMessage();   } catch (Exception $e) {       return 'General error: ' . $e->getMessage();   } } function postInstagramMediaCarousel($fb, $instagramAccountId, $message, $mediaUrls){     $mediaIds = [];     foreach ($mediaUrls as $mediaUrl) {         sleep(10);         // Detect media type based on URL or other means         $mediaType = (preg_match('/\.(mp4)$/i', $mediaUrl)) ? 'VIDEO' : 'IMAGE';         // Create the media and get the creation ID         $creationId = createMediaInsta($fb, $instagramAccountId, $mediaUrl, $mediaType);         if (!$creationId) {             throw new Exception("Failed to create media: $mediaUrl");         }         // Wait for the media to be ready         if (!waitForMediaToBeReadyInsta($fb, $creationId)) {             throw new Exception("Media is not ready: $creationId");         }         $mediaIds[] = $creationId;     }         // Create carousel with the obtained media IDs     $carouselResponse = $fb->post("/$instagramAccountId/media", [         'caption' => $message,         'media_type' => 'CAROUSEL',         'children' => $mediaIds,     ]);       $carouselCreationId = $carouselResponse->getDecodedBody()['id'];     if (!$carouselCreationId) {         throw new Exception("Failed to create carousel.");     }     // Wait for the carousel to be ready     if (!waitForMediaToBeReadyInsta($fb, $carouselCreationId)) {         throw new Exception("Carousel is not ready: $carouselCreationId");     }     sleep(30);     // Publish the carousel     return publishMedia($fb, $instagramAccountId, $carouselCreationId); } function createMediaInsta($fb, $instagramAccountId, $mediaUrl, $mediaType){     // Configura o payload dependendo do tipo de mídia     $payload = [         'media_type' => $mediaType,         'is_carousel_item' => 'true'     ];     if ($mediaType === 'VIDEO') {         $payload['video_url'] = $mediaUrl;     } else {         $payload['image_url'] = $mediaUrl;     }     $response = $fb->post("/$instagramAccountId/media", $payload);     return $response->getDecodedBody()['id']; } function waitForMediaToBeReadyInsta($fb, $creationId, $timeout = 300, $interval = 10){     $start = time();     do {         sleep($interval);         try {             $response = $fb->get("/$creationId");             $status = $response->getDecodedBody()['status'];         } catch (Exception $e) {             // Log the exception and continue waiting             error_log("Exception: " . $e->getMessage());             return false;         }         if ($status === 'READY') {             return true;         }         if (time() - $start > $timeout) {             error_log("Timeout: Media not ready in time.");             return false;         }     } while (true); } function publishMedia($fb, $instagramAccountId, $creationId){   return $fb->post("/$instagramAccountId/media_publish", [       'creation_id' => $creationId   ])->getDecodedBody(); } 

i tried everything that i could find on docs and net but cant find a solution!

How can I post via API to a Facebook Page without having my "Facebook App" suspended/deleted?

I need to share a URLs per day, via API, from my own script to a Facebook Page I manage.

I followed these instructions to create a "Facebook app" and get the "never-expiring" token.

Once I have the token, I can easily post like this:

<?php class FacebookMessenger{     protected string $pageId = '<my-page-id>';     protected string $token  = '<my-token>';     public function sendUrlToPage(string $url){         $endpoint = "https://graph.facebook.com/v19.0/{$this->pageId}/feed";         $this->lastResponse =             HttpClient::create()->request('POST', $endpoint, [                 "headers" => [                     "Content-Type" => "application/json",                 ],                 "query" => [                     "link"          => $url,                     "access_token"  => $this->token                 ]             ]);         $content = $this->lastResponse->getContent(false);         var_dump($content);         die();     } } (new FacebookMessenger())->sendUrlToPage('https://example.com'); 

This works beautiful for a few days, but then the Facebook App I created gets "restricted":

TLI Sharer App DEV is restricted due to violations

The app TLI Sharer App DEV is in violation of Meta’s Platform Terms or Developer Policies and has been restricted, as described below: Platform Term 7.e.i.2 - Negatively impacting platform, products, data, or users

We determined that your app is negatively impacting the platform, products, data, or users and has violated or may have violated our terms. This violates Platform Term 7.e.i.2.

This is the linked page: https://developers.facebook.com/terms/dfc_platform_terms/#compliancereviewrightsandsuspensionandterminationoftheseterms

I fail to see how running 5/6 API requests like this is a problem, and I have absolutely ZERO ideas on how to proceed.

Wanting to track 'Add to Cart' clicks on a WooCommerce store & Google Ads tell me I need to call gtag_report_conversion when any 'Add to cart' button is clicked on the site.

Some buttons are a link <a href="... etc"> using class="add_to_cart_button" - see example page

While other buttons are a <button> tag using class="single_add_to_cart_button" - see example page

I see from Google's instructions that the structure for a link is:

<a onclick="return gtag_report_conversion('http://example.com/your-link');"href="http://example.com/your-link">Add To Cart</a>

And the structure for a <button> tag is:

<button onclick="return gtag_report_conversion('http://example.com/your-link')">Add To Cart</button>

How can I construct a function hook that will create the above link / button tag structure & would it be an action or filter hook? Also, is it possible to use the classes mentioned earlier to define which buttons on the site should be affected by this particular function. The documentation showing what action & filter hooks are available for WooCommerce is here.

Emojis sent through the Facebook API are not displayed correctly on Facebook.

This functionality used to work, but now, instead of emojis, the symbols “?” are displayed. I tried using UNICODE, HTML code and shortcode.

The problem can be reproduced in the Graph API Explorer.

Link to the Graph API Explorer

For the test I used the following steps.

  1. I took a Facebook profile ID.

GET /v20.0/me?fields=id,name

  1. I created a video broadcast.
POST /v20.0/<USER_ID>/live_videos status="LIVE_NOW" title="Front 😝" description="Front 😝" 
  1. After I started the broadcasting the Facebook post become visible.

  2. After that, I made a request, using the broadcast ID, to receive the stream link.

The streaming link format as follows:

rtmps://live-api-s.facebook.com:443/rtmp/FB-1013749643592269-0-AbzJB6nb_Z183JwA,

To get the streaming link I made the following request:

GET /v20.0/<LIVE_VIDEO_ID>

  1. I started a broadcast in "OBS Studio" with that streaming link.

  2. I ended up checking the post on Facebook.

Facebook SDK for PHP (v5)

I'm using Graph API Explorer v20

Creating a video broadcast.

Getting the streaming url and broadcast title.

Result on Facebook.

Documentation for creating a live broadcast.