TwitterServiceBak.php 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. <?php
  2. namespace App\Services\Smm;
  3. use Abraham\TwitterOAuth\TwitterOAuth;
  4. use App\Services\Contracts\SmmPlatformInterface;
  5. use Carbon\Carbon;
  6. use Illuminate\Http\Request;
  7. use Illuminate\Support\Facades\Log;
  8. class TwitterServiceBak implements SmmPlatformInterface
  9. {
  10. protected $configData;
  11. protected $twitterOAuth;
  12. protected $consumerKey;
  13. protected $consumerSecret;
  14. protected $oauthCallbackUrl;
  15. public function __construct($configData)
  16. {
  17. $this->configData = $configData;
  18. $this->consumerKey = env('SSM_X_CONSUMER_KEY');
  19. $this->consumerSecret = env('SSM_X_CONSUMER_SECRET');
  20. $this->oauthCallbackUrl = env('DIST_SITE_URL') . '/dist/callback/twitter';
  21. if (isset($configData['accountInfo'])) {
  22. //初始化1.1版本的配置信息
  23. $access_token = $configData['accountInfo']['access_token'];
  24. $backup_field1 = json_decode($configData['accountInfo']['backup_field1'],true);
  25. $access_token_secret = $backup_field1['accessTokenSecret'];
  26. if (!empty($access_token) && !empty($access_token_secret)) {
  27. $this->twitterOAuth = new TwitterOAuth(
  28. $this->consumerKey,
  29. $this->consumerSecret,
  30. $access_token,
  31. $access_token_secret
  32. );
  33. }
  34. }
  35. }
  36. public function login()
  37. {
  38. $connection = new TwitterOAuth($this->consumerKey, $this->consumerSecret);
  39. $requestToken = $connection->oauth('oauth/request_token', ['oauth_callback' => $this->oauthCallbackUrl]);
  40. session(['twitter_oauth_token' => $requestToken['oauth_token']]);
  41. session(['twitter_oauth_token_secret' => $requestToken['oauth_token_secret']]);
  42. $url = $connection->url('oauth/authorize', ['oauth_token' => $requestToken['oauth_token']]);
  43. return [
  44. 'status' => true,
  45. 'data' => ['url' => $url]
  46. ];
  47. }
  48. public function loginCallback(Request $request)
  49. {
  50. try {
  51. $oauthToken = $request->get('oauth_token');
  52. $oauthVerifier = $request->get('oauth_verifier');
  53. $requestToken = session('twitter_oauth_token');
  54. $requestTokenSecret = session('twitter_oauth_token_secret');
  55. $connection = new TwitterOAuth(
  56. $this->consumerKey,
  57. $this->consumerSecret,
  58. $requestToken,
  59. $requestTokenSecret
  60. );
  61. $accessToken = $connection->oauth('oauth/access_token', [
  62. 'oauth_verifier' => $oauthVerifier
  63. ]);
  64. $expiresAt = Carbon::now()->addDays(90)->format('Y-m-d H:i:s');
  65. return [
  66. 'status' => true,
  67. 'data' => [
  68. 'accessToken' => $accessToken['oauth_token'],
  69. 'backupField1' => json_encode(['accessTokenSecret'=>$accessToken['oauth_token_secret']]),
  70. 'userId' => $accessToken['user_id'],
  71. 'userName' => $accessToken['screen_name'],
  72. 'accessToken_expiresAt' => $expiresAt,
  73. ]
  74. ];
  75. } catch (\Exception $e) {
  76. return ['status' => false, 'data' => $e->getMessage()];
  77. }
  78. }
  79. public function postImage($message, $imagePaths, $accessToken = null)
  80. {
  81. Log::info('开始发布图片帖子');
  82. try {
  83. $this->twitterOAuth->setApiVersion('1.1'); // 强制使用 v1.1 API
  84. $this->twitterOAuth->setTimeouts(15, 60);
  85. $mediaIds = [];
  86. foreach ($imagePaths as $imagePath) {
  87. $imagePath = toStoragePath($imagePath);
  88. if (!file_exists($imagePath)) {
  89. throw new \Exception("图片不存在: {$imagePath}");
  90. }
  91. //1.1版本上传媒体文件
  92. $uploadedMedia = $this->twitterOAuth->upload('media/upload', [
  93. 'media' => $imagePath
  94. ]);
  95. Log::info('1.1版本上传媒体文件完成');
  96. if (isset($uploadedMedia->error)) {
  97. throw new \Exception('媒体上传失败: ' . json_encode($uploadedMedia));
  98. }
  99. $mediaIds[] = $uploadedMedia->media_id_string;
  100. }
  101. // 2.0版本发布推文
  102. $this->twitterOAuth->setApiVersion('2');
  103. $tweet = $this->twitterOAuth->post('tweets', [
  104. 'text' => $message,
  105. 'media' => !empty($mediaIds) ? ['media_ids' => $mediaIds] : null
  106. ]);
  107. Log::info('2.0版本发布推文完成');
  108. if (isset($tweet->errors)) {
  109. throw new \Exception('推文发布失败: ' . json_encode($tweet->errors));
  110. }
  111. return ['status' => true,
  112. 'data' => [
  113. 'responseIds' => [$tweet->data->id],
  114. ]];
  115. } catch (\Exception $e) {
  116. return ['status' => false, 'data' => $e->getMessage()];
  117. }
  118. }
  119. public function postVideo($message, $videoPath, $accessToken = null)
  120. {
  121. try {
  122. ini_set('memory_limit', '512M');
  123. $this->twitterOAuth->setTimeouts(15, 120);
  124. $this->twitterOAuth->setApiVersion('1.1');
  125. $videoPath = toStoragePath($videoPath);
  126. // Verify file exists and is readable
  127. if (!file_exists($videoPath) || !is_readable($videoPath)) {
  128. throw new Exception("Video file does not exist or is not readable: $videoPath");
  129. }
  130. Log::info('twitter上传视频'.$videoPath);
  131. // Upload video with chunked upload
  132. $uploadedMedia = $this->twitterOAuth->upload('media/upload', [
  133. 'media' => $videoPath,
  134. 'media_category' => 'tweet_video',
  135. ],['chunkedUpload'=>true]);
  136. Log::info('1.1版本,分块上传视频');
  137. $code = $this->twitterOAuth->getLastHttpCode();
  138. if (isset($uploadedMedia->error) || $code != 200) {
  139. throw new \Exception('媒体上传失败: ' . json_encode($uploadedMedia));
  140. }
  141. $mediaId = $uploadedMedia->media_id_string;
  142. $limit = 0;
  143. do {
  144. $status = $this->twitterOAuth->mediaStatus($mediaId);
  145. Log::info('检测视频上传状态'.print_r($status,true));
  146. sleep(5); // 等待 5 秒
  147. $limit++;
  148. } while ($status->processing_info->state !== 'succeeded' && $limit <= 3); // 最多重试 3 次
  149. if ($status->processing_info->state === 'succeeded') {
  150. //print_r($status->processing_info->state);
  151. // 2.0版本发布推文
  152. $this->twitterOAuth->setApiVersion('2');
  153. $tweet = $this->twitterOAuth->post('tweets', [
  154. 'text' => $message,
  155. 'media' => ['media_ids' => [$mediaId]]
  156. ]);
  157. Log::info('2.0版本发布推文');
  158. if (isset($tweet->errors)) {
  159. throw new \Exception('推文发布失败: ' . json_encode($tweet->errors));
  160. }
  161. return ['status' => true,
  162. 'data' => [
  163. 'responseIds' => [$tweet->data->id],
  164. ]
  165. ];
  166. } else {
  167. return ['status' => false, 'data' => '视频上传失败或处理超时。' ];
  168. }
  169. } catch (\Exception $e) {
  170. return ['status' => false, 'data' => '视频上传异常: '.$e->getMessage()];
  171. }
  172. }
  173. // 保持空实现
  174. public function getComments($postId) {}
  175. public function replyToComment($commentId) {}
  176. public function deleteComment($commentId) {}
  177. }