YoutubeService.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. <?php
  2. namespace App\Services\Smm;
  3. use App\Services\Contracts\SmmPlatformInterface;
  4. use Carbon\Carbon;
  5. use Illuminate\Http\Request;
  6. use Illuminate\Support\Facades\Http;
  7. class YoutubeService implements SmmPlatformInterface
  8. {
  9. protected $clientId;
  10. protected $clientSecret;
  11. // 构造函数,传入配置信息
  12. public $configData = [];
  13. public function __construct($configData) {
  14. $this->configData = $configData;
  15. $this->clientId = env('SSM_INSTAGRAM_APP_ID');
  16. $this->clientSecret = env('SSM_INSTAGRAM_APP_SECRET');
  17. }
  18. /*
  19. * OAuth 2.0 授权登录
  20. * 返回授权地址:https://example.com/fb-callback.php
  21. */
  22. public function login()
  23. {
  24. $loginUrl = 'https://www.instagram.com/oauth/authorize' . '?' . http_build_query([
  25. 'enable_fb_login'=>0,
  26. 'force_authentication'=>1,
  27. 'client_id' => $this->clientId,
  28. 'redirect_uri' => $this->redirectUri,
  29. 'scope' => 'instagram_business_basic,instagram_business_manage_messages,instagram_business_manage_comments,instagram_business_content_publish,instagram_business_manage_insights',
  30. 'response_type' => 'code',
  31. ]);
  32. return ['status'=>true, 'data' => ['url'=>$loginUrl]];
  33. }
  34. /*
  35. * OAuth 2.0 授权回调
  36. * 授权成功后,得到access_token,refresh_token等信息, 保存到数据库中
  37. * 授权成功后,返回回调需要的数据
  38. */
  39. public function loginCallback(Request $request)
  40. {
  41. if (!$request->has('code')) {
  42. return ['status' => false, 'data' => '未收到授权代码'];
  43. }
  44. $code = $request->input('code');
  45. // 1. 交换授权代码以获取短期访问令牌
  46. $tokenResponse = Http::asForm()->post('https://api.instagram.com/oauth/access_token', [
  47. 'client_id' => $this->clientId,
  48. 'client_secret' => $this->clientSecret,
  49. 'grant_type' => 'authorization_code',
  50. 'redirect_uri' => $this->redirectUri,
  51. 'code' => $code,
  52. ]);
  53. $tokenData = $tokenResponse->json();
  54. if (!isset($tokenData['access_token'])) {
  55. return ['status' => false, 'data' => '错误:无法获取短期访问令牌 - ' ];
  56. }
  57. $shortLivedToken = $tokenData['access_token'];
  58. // 2. 使用短期令牌交换长期令牌
  59. $longLivedTokenResponse = Http::get('https://graph.instagram.com/access_token', [
  60. 'grant_type' => 'ig_exchange_token',
  61. 'client_secret' => $this->clientSecret,
  62. 'access_token' => $shortLivedToken,
  63. ]);
  64. $longLivedTokenData = $longLivedTokenResponse->json();
  65. if (!isset($longLivedTokenData['access_token'])) {
  66. return ['status' => false, 'data' => '错误:无法获取长期访问令牌 - ' ];
  67. }
  68. $accessToken = $longLivedTokenData['access_token'];
  69. // 3. 获取用户信息
  70. $userResponse = Http::get('https://graph.instagram.com/me', [
  71. 'fields' => 'id,username',
  72. 'access_token' => $accessToken,
  73. ]);
  74. $userInfo = $userResponse->json();
  75. if (!isset($userInfo['id']) || !isset($userInfo['username'])) {
  76. return ['status' => false, 'data' => '错误:无法获取用户信息 - '];
  77. }
  78. $expiresInSeconds = $longLivedTokenData['expires_in'];
  79. // 当前时间
  80. $now = Carbon::now();
  81. $expiresAt = $now->copy()->addSeconds($expiresInSeconds);
  82. // 返回用户信息和长期访问令牌
  83. return ['status' => true, 'data' => [
  84. 'accessToken' => $accessToken,
  85. 'accessToken_expiresAt'=>$expiresAt,
  86. 'userName'=>$userInfo['username'],'userId'=>$userInfo['id']
  87. ]];
  88. }
  89. /*
  90. * 发布图片,可以发多个图片
  91. * $imagePaths = ['/path/to/image1.jpg','/path/to/image2.jpg'];
  92. */
  93. public function postImage($message, $imagePaths, $accessToken)
  94. {
  95. try {
  96. if (empty($imagePaths)) {
  97. return ['status' => false, 'data' => '错误:未提供图片路径'];
  98. }
  99. $igUserId = $this->configData['accountInfo']['account_id'];
  100. // If single image
  101. if (count($imagePaths) === 1) {
  102. $imagePath = $imagePaths[0];
  103. // Create media container for single image
  104. $postData = [
  105. 'image_url' => $imagePath, // Assuming images are publicly accessible
  106. 'caption' => $message,
  107. 'access_token' => $accessToken,
  108. ];
  109. $containerResponse = Http::asForm()->post("https://graph.instagram.com/v21.0/{$igUserId}/media",$postData);
  110. $containerData = $containerResponse->json();
  111. if (!isset($containerData['id'])) {
  112. return ['status' => false, 'data' => '错误:无法创建媒体容器 - ' . json_encode($containerData)];
  113. }
  114. // Publish the container
  115. $publishResponse = Http::post("https://graph.instagram.com/v21.0/{$igUserId}/media_publish", [
  116. 'creation_id' => $containerData['id'],
  117. 'access_token' => $accessToken,
  118. ]);
  119. $publishData = $publishResponse->json();
  120. if (!isset($publishData['id'])) {
  121. return ['status' => false, 'data' => '错误:无法发布图片 - ' . json_encode($publishData)];
  122. }
  123. $postIds = [$publishData['id']];
  124. $requestContent = [$postData];
  125. $responseContent = [$publishData];
  126. return ['status' => true,
  127. 'data' => [
  128. 'responseIds' => $postIds,
  129. 'requestContent' => $requestContent,
  130. 'responseContent' => $responseContent,
  131. ]];
  132. }
  133. // For multiple images (carousel post)
  134. $children = [];
  135. $requestContent = [];
  136. $responseContent = [];
  137. foreach ($imagePaths as $imagePath) {
  138. $postData = [
  139. 'image_url' => asset($imagePath),
  140. 'is_carousel_item' => true,
  141. 'access_token' => $accessToken,
  142. ];
  143. $requestContent[] = [
  144. 'url'=>"https://graph.instagram.com/v21.0/{$igUserId}/media",
  145. 'postData' => $postData,
  146. ];
  147. $childResponse = Http::asForm()->post("https://graph.instagram.com/v21.0/{$igUserId}/media", $postData);
  148. $childData = $childResponse->json();
  149. $responseContent[] = $childData;
  150. if (!isset($childData['id'])) {
  151. return ['status' => false, 'data' => '错误:无法创建子媒体容器 - ' . json_encode($childData)];
  152. }
  153. $children[] = $childData['id'];
  154. }
  155. // Create carousel container
  156. $postData = [
  157. 'media_type' => 'CAROUSEL',
  158. 'children' => implode(',', $children),
  159. 'caption' => $message,
  160. 'access_token' => $accessToken,
  161. ];
  162. $requestContent[] = [
  163. 'url'=>"https://graph.instagram.com/v21.0/{$igUserId}/media",
  164. 'postData' => $postData,
  165. ];
  166. $carouselResponse = Http::asForm()->post("https://graph.instagram.com/v21.0/{$igUserId}/media",$postData );
  167. $carouselData = $carouselResponse->json();
  168. $responseContent[] = $carouselData;
  169. if (!isset($carouselData['id'])) {
  170. return ['status' => false, 'data' => '错误:无法创建轮播容器 - ' . json_encode($carouselData)];
  171. }
  172. // Publish carousel
  173. $postData = [
  174. 'creation_id' => $carouselData['id'],
  175. 'access_token' => $accessToken,
  176. ];
  177. $requestContent[] = [
  178. 'url'=>"https://graph.instagram.com/v21.0/{$igUserId}/media_publish",
  179. 'postData' => $postData,
  180. ];
  181. $publishResponse = Http::post("https://graph.instagram.com/v21.0/{$igUserId}/media_publish", $postData);
  182. $publishData = $publishResponse->json();
  183. $responseContent[] = $publishData;
  184. if (!isset($publishData['id'])) {
  185. return ['status' => false, 'data' => '错误:无法发布轮播 - ' . json_encode($publishData)];
  186. }
  187. $postIds = [$publishData['id']];
  188. return ['status' => true,
  189. 'data' => [
  190. 'responseIds' => $postIds,
  191. 'requestContent' => $requestContent,
  192. 'responseContent' => $responseContent,
  193. ]];
  194. } catch (\Exception $e) {
  195. //Log::error('Instagram postImage error: ' . $e->getMessage());
  196. return ['status' => false, 'data' => '错误:' . $e->getMessage()];
  197. }
  198. }
  199. /*
  200. * 发布视频,只能发一个视频
  201. */
  202. public function postVideo($message, $videoPath, $accessToken)
  203. {
  204. try {
  205. if (empty($videoPath)) {
  206. return ['status' => false, 'data' => '错误:未提供视频路径'];
  207. }
  208. $igUserId = $this->configData['accountInfo']['account_id'];
  209. $requestContent = [];
  210. $responseContent = [];
  211. // Create media container for video
  212. $postData = [
  213. 'media_type' => 'REELS',
  214. 'video_url' => $videoPath, // Assuming video is publicly accessible
  215. 'caption' => $message,
  216. 'access_token' => $accessToken,
  217. ];
  218. $requestContent[] = ['url'=>"https://graph.instagram.com/v21.0/{$igUserId}/media", 'postData' => $postData];
  219. $containerResponse = Http::asForm()->post("https://graph.instagram.com/v21.0/{$igUserId}/media", $postData);
  220. $containerData = $containerResponse->json();
  221. if (!isset($containerData['id'])) {
  222. return ['status' => false, 'data' => '错误:无法创建视频容器 - ' . json_encode($containerData)];
  223. }
  224. $responseContent[] = $containerData;
  225. // Check container status (video processing may take time)
  226. $status = 'IN_PROGRESS';
  227. $maxAttempts = 10;
  228. $attempt = 0;
  229. while ($status === 'IN_PROGRESS' && $attempt < $maxAttempts) {
  230. sleep(5); // Wait 5 seconds between checks
  231. $postData = [
  232. 'fields' => 'status',
  233. 'access_token' => $accessToken,
  234. ];
  235. $requestContent[] = ['url'=>"https://graph.instagram.com/{$containerData['id']}", 'postData' => $postData];
  236. $statusResponse = Http::get("https://graph.instagram.com/{$containerData['id']}", $postData);
  237. $statusData = $statusResponse->json();
  238. $status = $statusData['status'] ?? 'ERROR';
  239. $attempt++;
  240. if ($status === 'ERROR') {
  241. return ['status' => false, 'data' => '错误:视频处理失败'];
  242. }
  243. $responseContent[] = $statusData;
  244. }
  245. if ($status !== 'FINISHED') {
  246. return ['status' => false, 'data' => '错误:视频处理超时'];
  247. }
  248. // Publish the video
  249. $postData = [
  250. 'creation_id' => $containerData['id'],
  251. 'access_token' => $accessToken,
  252. ];
  253. $requestContent[] = ['url'=>"https://graph.instagram.com/v21.0/{$igUserId}/media_publish", 'postData' => $postData];
  254. $publishResponse = Http::post("https://graph.instagram.com/v21.0/{$igUserId}/media_publish",$postData);
  255. $publishData = $publishResponse->json();
  256. if (!isset($publishData['id'])) {
  257. return ['status' => false, 'data' => '错误:无法发布视频 - ' . json_encode($publishData)];
  258. }
  259. $responseContent[] = $publishData;
  260. $postIds = [$publishData['id']];
  261. return ['status' => true,
  262. 'data' => [
  263. 'responseIds' => $postIds,
  264. 'requestContent' => $requestContent,
  265. 'responseContent' => $responseContent,
  266. ]];
  267. } catch (\Exception $e) {
  268. return ['status' => false, 'data' => '错误:' . $e->getMessage()];
  269. }
  270. }
  271. public function getComments($postId) {
  272. }
  273. public function replyToComment($commentId) {
  274. }
  275. public function deleteComment($commentId) {
  276. }
  277. }