You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用PHP发布照片到Instagram,现有Facebook发布代码可参考

Instagram 照片发布PHP代码调整方案

首先确认两个前置条件:

  • 你需要先获取绑定了Facebook主页的Instagram商业账户ID(可通过调用/{page_id}?fields=instagram_business_account接口获取,记为$instagram_business_id)
  • 你使用的页面访问令牌($page_token)需要同时拥有发布Instagram内容的权限

调整后的可运行代码

require_once 'facebook-sdk/autoload.php';

$fb = new Facebook\Facebook([
  'app_id' => 'xxx',
  'app_secret' => 'yyy',
  'default_graph_version' => 'v18.0', // 旧版本v2.9不支持Instagram接口,必须升级到v15.0以上版本
]);

try 
{
   // 第一步:先创建Instagram媒体容器
   $createContainerArgs = [
      'access_token' => $page_token,
      'image_url' => $urlofexistingphoto, // 这里替换为你的公网可访问的图片地址
      'caption' => 'Caption #instagram'
   ];
   $containerResponse = $fb->post("/{$instagram_business_id}/media", $createContainerArgs);
   $containerData = $containerResponse->getGraphNode();
   $containerId = $containerData['id'];

   // 第二步:发布媒体容器到Instagram主页
   $publishArgs = [
      'access_token' => $page_token,
      'creation_id' => $containerId
   ];
   $publishResponse = $fb->post("/{$instagram_business_id}/media_publish", $publishArgs);
   $publishData = $publishResponse->getGraphNode();
   $instagramPostId = $publishData['id'];

   echo "发布成功,Instagram帖子ID:" . $instagramPostId;

} catch (Facebook\Exceptions\FacebookResponseException $e) {
   error_log('Graph返回错误:' . $e->getMessage());
   echo "发布失败:" . $e->getMessage() . "\n";
} catch (Facebook\Exceptions\FacebookSDKException $e) {
   error_log('SDK返回错误:' . $e->getMessage());
   echo "发布失败:" . $e->getMessage() . "\n";
}

核心调整说明

  • 原Facebook发帖是直接调用/{page_id}/photos接口一步完成,Instagram发布需要分两步:先创建媒体容器,再发布容器到主页
  • 接口参数从url改为Instagram要求的image_url,图片必须是公网可直接访问、无防盗链限制的地址
  • 必须升级Graph API的版本,低于v15.0的旧版本已经不支持Instagram发布相关接口
  • 修正了原代码里的语法错误,包括参数名缺引号、SDK实例名拼写错误的问题

内容的提问来源于stack exchange,提问作者Scott Hatton

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 17:45:03