skip to Main Content

I am trying to upload image to Facebook graph api with Http Client of Laravel. But I am getting the error mentioned before.

    $ad_account_id = env("AD_ACCOUNT_ID");
    $access_token = env("ACCESS_TOKEN");
    $image = $request->file('image');

    $response = Http::asForm()
        ->withHeaders(['Content-Type: multipart/form-data'])
        ->post('https://graph.facebook.com/v14.0/act_' . $ad_account_id . '/adimages',
            [
                'filename' => file_get_contents($image),
                'access_token' => $access_token
            ]
        );

    dd(json_decode($response->body()));

In documentation Facebook gives me curl api example like this

curl 
  -F 'filename=@<IMAGE_PATH>' 
  -F 'access_token=<ACCESS_TOKEN>' 
  https://graph.facebook.com/v<API_VERSION>/act_<AD_ACCOUNT_ID>/adimages

Problem is all about IMAGE_PATH. I have tried to send any kind of path of uploaded image even in base64 format. I am able to upload the same image with same api in Postman. There is not any problem about access_token or ad_account_id.

2

Answers


  1. Chosen as BEST ANSWER

    Solved my problem by using attach method of HTTP client:

    $ad_account_id = env("AD_ACCOUNT_ID");
    $access_token = env("ACCESS_TOKEN");
    $image = $request->file('image');
    
    $response = Http::attach('filename', file_get_contents($image), 'image.jpg')
        ->post('https://graph.facebook.com/v14.0/act_' . $ad_account_id . '/adimages',
            [
                'access_token' => $access_token
            ]
        );
    
    dd(json_decode($response->body()));
    

  2. Will recommend to use PHP SDK for such operations.
    https://github.com/facebook/facebook-php-business-sdk

    
        $account = new FacebookAdsObjectAdAccount('Your ID');
        assert($account instanceof FacebookAdsObjectAdAccount);
        $account->createAdImage(['array of fields'],['array of request Params'],);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search