TwitterService.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. <?php
  2. namespace App\Services\Smm;
  3. use App\Services\Contracts\SmmPlatformInterface;
  4. use Abraham\TwitterOAuth\TwitterOAuth;
  5. use Carbon\Carbon;
  6. use CURLFile;
  7. use Illuminate\Http\Request;
  8. use Illuminate\Support\Facades\Log;
  9. class TwitterService implements SmmPlatformInterface
  10. {
  11. protected $configData;
  12. private $clientId;
  13. private $clientSecret;
  14. private $access_token;
  15. private $media_upload_url = 'https://api.x.com/2/media/upload';
  16. private $tweet_url = 'https://api.x.com/2/tweets';
  17. private $chunk_size = 4 * 1024 * 1024; // 分块上传的大小,不能大于5M,否则会报错
  18. public function __construct($configData)
  19. {
  20. $this->clientId = env('SSM_X_CLIENT_ID');
  21. $this->clientSecret = env('SSM_X_CLIENT_SECRET');
  22. $this->configData = $configData;
  23. }
  24. public function login()
  25. {
  26. $redirectUri = env('DIST_SITE_URL') . '/dist/callback/twitter';
  27. $scopes = ['tweet.read','tweet.write','dm.write', 'users.read', 'offline.access','media.write']; // 需要的权限范围
  28. $oauthState = bin2hex(random_bytes(16));
  29. $authUrl = 'https://twitter.com/i/oauth2/authorize?' . http_build_query([
  30. 'response_type' => 'code',
  31. 'client_id' => $this->clientId,
  32. 'redirect_uri' => $redirectUri,
  33. 'scope' => implode(' ', $scopes),
  34. 'state' => $oauthState,
  35. 'code_challenge' => 'challenge', // 如果使用 PKCE 需要生成
  36. 'code_challenge_method' => 'plain'
  37. ]);
  38. return [
  39. 'status' => true,
  40. 'data' => ['url' => $authUrl]
  41. ];
  42. }
  43. public function loginCallback(Request $request)
  44. {
  45. try {
  46. $tokenUrl = 'https://api.twitter.com/2/oauth2/token';
  47. $redirectUri = env('DIST_SITE_URL') . '/dist/callback/twitter';
  48. $params = [
  49. 'code' => $_GET['code'],
  50. 'grant_type' => 'authorization_code',
  51. 'client_id' => $this->clientId,
  52. 'redirect_uri' => $redirectUri,
  53. 'code_verifier' => 'challenge' // 如果使用 PKCE 需要对应
  54. ];
  55. $ch = curl_init();
  56. curl_setopt($ch, CURLOPT_URL, $tokenUrl);
  57. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  58. curl_setopt($ch, CURLOPT_POST, true);
  59. curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
  60. curl_setopt($ch, CURLOPT_HTTPHEADER, [
  61. 'Authorization: Basic ' . base64_encode($this->clientId . ':' . $this->clientSecret),
  62. 'Content-Type: application/x-www-form-urlencoded'
  63. ]);
  64. $auth = curl_exec($ch);
  65. curl_close($ch);
  66. $auth = json_decode($auth, true);
  67. if (isset($auth['access_token']) == false) {
  68. return ['status' => false, 'data' => '获取token失败'];
  69. }
  70. $this->access_token = $auth['access_token'];
  71. $url = 'https://api.twitter.com/2/users/me?user.fields=id,username,name';
  72. $result = $this->twitterApiRequest($url, 'GET');
  73. // var_dump($result);
  74. // exit;
  75. if ($result['code'] != 200) {
  76. return ['status' => false, 'data' => '获取token失败'];
  77. }
  78. if (isset($auth['access_token'])) {
  79. $userData = $result['response']['data'];
  80. $userId = $userData['id'];
  81. $username = $userData['username'];
  82. $name = $userData['name'];
  83. $refresh_token = $auth['refresh_token'] ?? '';
  84. $expires_in = $auth['expires_in'] ?? 0;
  85. $expiresAt = Carbon::now()->addSeconds($expires_in)->format('Y-m-d H:i:s');
  86. return [
  87. 'status' => true,
  88. 'data' => [
  89. 'accessToken' => $auth['access_token'],
  90. 'backupField1' => json_encode(['refresh_token'=>$refresh_token]),
  91. 'userId' => $userId,
  92. 'userName' => $username,
  93. 'accessToken_expiresAt' => $expiresAt,
  94. ]
  95. ];
  96. } else {
  97. return ['status' => false, 'data' => '获取token失败'];
  98. }
  99. } catch (\Exception $e) {
  100. return ['status' => false, 'data' => $e->getMessage()];
  101. }
  102. }
  103. public function postImage($message, $imagePaths, $accessToken = null)
  104. {
  105. try {
  106. $this->access_token = $accessToken;
  107. $videoPaths = [];
  108. foreach ($imagePaths as $imagePath) {
  109. $videoPaths[] = toStoragePath($imagePath);//用本地路径上传
  110. }
  111. $mediaResult = $this->uploadAndPost($videoPaths, $message);
  112. if (isset($mediaResult['response']['data']['id'])) {
  113. return ['status' => true,
  114. 'data' => [
  115. 'responseIds' => [$mediaResult['response']['data']['id']],
  116. ]
  117. ];
  118. } else {
  119. return ['status' => false, 'data' => '发布失败'];
  120. }
  121. } catch (\Exception $e) {
  122. return ['status' => false, 'data' => $e->getMessage()];
  123. }
  124. }
  125. public function postVideo($message, $videoPath, $accessToken = null)
  126. {
  127. try {
  128. $this->access_token = $accessToken;
  129. $videoPath = toStoragePath($videoPath);//用本地路径上传
  130. $mediaResult = $this->uploadAndPost([$videoPath], $message);
  131. if (isset($mediaResult['response']['data']['id'])) {
  132. return ['status' => true,
  133. 'data' => [
  134. 'responseIds' => [$mediaResult['response']['data']['id']],
  135. ]
  136. ];
  137. } else {
  138. return ['status' => false, 'data' => '上传视频失败'];
  139. }
  140. } catch (\Exception $e) {
  141. return ['status' => false, 'data' => $e->getMessage()];
  142. }
  143. }
  144. // 保持空实现
  145. public function getComments($postId) {}
  146. public function replyToComment($commentId) {}
  147. public function deleteComment($commentId) {}
  148. /**
  149. * 通用Twitter API请求
  150. */
  151. private function twitterApiRequest($url, $method = 'POST', $data = [], $headers = []) {
  152. try {
  153. Log::info('curl 请求:'.$url);
  154. $ch = curl_init();
  155. $headers = array_merge([
  156. 'Authorization: Bearer ' . $this->access_token
  157. ], $headers);
  158. Log::info('curl $headers:'.json_encode($headers));
  159. curl_setopt_array($ch, [
  160. CURLOPT_URL => $url,
  161. CURLOPT_RETURNTRANSFER => true,
  162. CURLOPT_FOLLOWLOCATION => true,
  163. CURLOPT_HTTPHEADER => $headers,
  164. CURLOPT_TIMEOUT => 50,
  165. ]);
  166. if ($method === 'POST') {
  167. curl_setopt($ch, CURLOPT_POST, true);
  168. // 处理JSON数据
  169. curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
  170. }
  171. $response = curl_exec($ch);
  172. $error = curl_error($ch);
  173. curl_close($ch);
  174. Log::info('curl response:'.$response);
  175. if ($error) {
  176. throw new \Exception("cURL Error: ".$error);
  177. }
  178. if ($response === false) {
  179. throw new \Exception("cURL Error: false response");
  180. }
  181. $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  182. return ['code'=>$http_code,'response' => json_decode($response, true)];
  183. } catch (\Exception $e) {
  184. throw new \Exception("catch cURL Error: ".$e->getMessage());
  185. }
  186. }
  187. /**
  188. * 初始化上传
  189. */
  190. public function initUpload($fileSize, $mediaType = 'video/mp4',$media_category = 'tweet_video') {
  191. return $this->twitterApiRequest($this->media_upload_url, 'POST', [
  192. 'command' => 'INIT',
  193. 'media_type' => $mediaType,
  194. 'total_bytes' => $fileSize,
  195. 'media_category' => $media_category
  196. ]);
  197. }
  198. /**
  199. * 分块上传
  200. */
  201. public function appendUpload($media_id, $filePath) {
  202. $handle = fopen($filePath, 'rb');
  203. $segment_index = 0;
  204. while (!feof($handle)) {
  205. $chunk = fread($handle, $this->chunk_size);
  206. $result = $this->twitterApiRequest($this->media_upload_url, 'POST', [
  207. 'command' => 'APPEND',
  208. 'media_id' => $media_id,
  209. 'segment_index' => $segment_index,
  210. 'media' => $chunk
  211. ]);
  212. Log::info('分块上传'.$segment_index.' : '.json_encode($result));
  213. if ($result['code'] !== 204) {
  214. return false;
  215. }
  216. $segment_index++;
  217. sleep(2); // 避免速率限制
  218. }
  219. fclose($handle);
  220. return true;
  221. }
  222. /**
  223. * 完成上传
  224. */
  225. public function finalizeUpload($media_id) {
  226. return $this->twitterApiRequest($this->media_upload_url, 'POST', [
  227. 'command' => 'FINALIZE',
  228. 'media_id' => $media_id
  229. ]);
  230. }
  231. /**
  232. * 检查媒体状态
  233. */
  234. public function checkStatus($media_id) {
  235. $url = $this->media_upload_url . '?' . http_build_query([
  236. 'command' => 'STATUS',
  237. 'media_id' => $media_id
  238. ]);
  239. return $this->twitterApiRequest($url, 'GET');
  240. }
  241. /**
  242. * 等待媒体处理完成
  243. */
  244. public function waitForProcessing($media_id, $interval = 10, $max_attempts = 6) {
  245. $attempts = 0;
  246. do {
  247. $status = $this->checkStatus($media_id);
  248. Log::info('等待媒体处理完成:'.$attempts.' : '.json_encode($status));
  249. if (!isset($status['response']['data'])) {
  250. throw new \Exception("waitForProcessing failed: status data not found");
  251. }
  252. $state = $status['response']['data']['processing_info']['state'] ?? '';
  253. if ($state === 'succeeded') return true;
  254. if ($state === 'failed') return false;
  255. sleep($interval);
  256. $attempts++;
  257. } while ($attempts < $max_attempts);
  258. throw new \Exception("Media processing timeout");
  259. }
  260. /**
  261. * 发布推文
  262. */
  263. public function postTweet($text, $media_ids) {
  264. $data = [
  265. 'text' => $text,
  266. 'media' => ['media_ids' => $media_ids]
  267. ];
  268. $data = json_encode($data);
  269. return $this->twitterApiRequest($this->tweet_url, 'POST',$data , ['Content-Type: application/json']);
  270. }
  271. /**
  272. * 完整上传流程
  273. */
  274. public function uploadAndPost($filePaths, $tweetText) {
  275. try {
  276. $media_ids = [];
  277. foreach ($filePaths as $filePath) {
  278. $file_info = pathinfo($filePath);
  279. $file_extension = $file_info['extension'];
  280. if ($file_extension == 'mp4' && filesize($filePath) > 20 * 1024 * 1024) {
  281. //不能大于20M
  282. return ['status'=>false,'message' => 'File size too large (max 20M)'];
  283. } else if (($file_extension == 'jpg' || $file_extension == 'png') && filesize($filePath) > 5 * 1024 * 1024) {
  284. //不能大于5M
  285. return ['status'=>false,'message' => 'File size too large (max 5M)'];
  286. }
  287. if ($file_extension == 'mp4') {
  288. $media_category = 'tweet_video';
  289. $mediaType = 'video/mp4';
  290. } else if ($file_extension == 'jpg') {
  291. $media_category = 'tweet_image';
  292. $mediaType = 'image/jpeg';
  293. } else {
  294. $media_category = 'tweet_image';
  295. $mediaType = 'image/png';
  296. }
  297. Log::info('Twitter开始发布帖子,文件格式:'.$file_extension);
  298. // 1. 初始化上传
  299. $init = $this->initUpload(filesize($filePath),$mediaType,$media_category);
  300. $media_id = isset($init['response']['data']['id']) ? $init['response']['data']['id'] : null;
  301. $media_ids[] = $media_id;
  302. if (!$media_id) {
  303. return ['status'=>false,'message' => 'Init upload failed'];
  304. }
  305. Log::info('初始化上传成功'.$media_id);
  306. // 2. 分块上传
  307. $append = $this->appendUpload($media_id, $filePath);
  308. if (!$append) {
  309. return ['status'=>false,'message' => 'Append upload failed'];
  310. }
  311. // 3. 完成上传
  312. $finalize = $this->finalizeUpload($media_id);
  313. Log::info('完成上传:'.json_encode($finalize));
  314. if (isset($finalize['response']['data']) == false) {
  315. return ['status'=>false,'message' => 'Finalize upload failed'];
  316. }
  317. // 4. mp4 等待处理完成
  318. if ($file_extension == 'mp4') {
  319. Log::info('等待处理完成');
  320. if (!$this->waitForProcessing($media_id)) {
  321. throw new \Exception('Media processing failed');
  322. }
  323. }
  324. }
  325. // 5. 发布推文
  326. Log::info('发布推文');
  327. $postTweet = $this->postTweet($tweetText, $media_ids);
  328. Log::info('发布推文结果:'.json_encode($postTweet));
  329. return $postTweet;
  330. } catch (\Exception $e) {
  331. return ['status'=>false,'message' => "Upload failed: ".$e->getMessage()];
  332. }
  333. }
  334. }