Facebook: post image and description to wall and in page album via php

有些话、适合烂在心里 提交于 2019-11-28 08:50:45

To upload images to a facebook page of which you're an admin you need to do the following:

1.) Create a facebook application (the usual way), make sure you specify the Canvas URL

2.) Navigate to the url below logged in as the admin of the page, and give the permissions (user_photos,manage_pages,offline_access,publish_stream)

https://www.facebook.com/dialog/oauth?
    client_id=<application_id>
    &redirect_uri=<canvas_url>
    &response_type=token
    &scope=user_photos,manage_pages,offline_access,publish_stream

3.) When you give the application the required permissions you'll be redirected to canvas_url#access_token=*access_token*, for example

http://example.com/#access_token=awe12

4.) Then navigate to

https://graph.facebook.com/me/accounts?access_token=<access_token>

(use the access token from #3). This will list the pages you administer; write down the access_token for the page(s) to which you want to upload the image

I'm not 100% sure but I believe that using graph api you can upload images only to albums created via graph api; i.e. you need to first create an album via graph api. Here's sample code using curl:

$uri = sprintf( 
    'https://graph.facebook.com/%1$s/albums?access_token=%2$s',
    $page_id, 
    $access_token
);

$post_fields = array(
    'name' => trim( $album_name )
);

$curl = curl_init( $uri );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1 );  
curl_setopt( $curl, CURLOPT_POST, TRUE );
curl_setopt( $curl, CURLOPT_POSTFIELDS, $post_fields );  

$raw_data = curl_exec( $curl );
curl_close( $curl );

$data = json_decode( $raw_data, $assoc = TRUE );

The $data above will contain the album id, which you'll need to upload a photo:

// prepare the curl post fields
$batch = sprintf(
    '[{"method":"POST", "relative_url":"%1$s/photos", "attached_files":"file1"}]',
    $album_id
);  

$post_fields = array(
    'batch' => $batch,
    'access_token' => $access_token,
    'file1' => '@' . $image_abs_path
);
$uri = 'https://graph.facebook.com';

$curl = curl_init( $uri );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1 );  
curl_setopt( $curl, CURLOPT_POST, TRUE );
curl_setopt( $curl, CURLOPT_POSTFIELDS, $post_fields );  

$raw_data = curl_exec( $curl );
curl_close( $curl );

$data = json_decode( $raw_data, $assoc = TRUE );
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!