TwitterService.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  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','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' => '',
  91. 'userId' => $userId,
  92. 'userName' => $username,
  93. 'accessToken_expiresAt' => $expiresAt,
  94. 'refreshToken' => $refresh_token,
  95. ]
  96. ];
  97. } else {
  98. return ['status' => false, 'data' => '获取token失败'];
  99. }
  100. } catch (\Exception $e) {
  101. return ['status' => false, 'data' => $e->getMessage()];
  102. }
  103. }
  104. public function postImage($message, $imagePaths, $accessToken = null)
  105. {
  106. try {
  107. $this->access_token = $accessToken;
  108. $videoPaths = [];
  109. foreach ($imagePaths as $imagePath) {
  110. $videoPaths[] = toStoragePath($imagePath);//用本地路径上传
  111. }
  112. $mediaResult = $this->uploadAndPost($videoPaths, $message);
  113. if (isset($mediaResult['response']['data']['id'])) {
  114. return ['status' => true,
  115. 'data' => [
  116. 'responseIds' => [$mediaResult['response']['data']['id']],
  117. ]
  118. ];
  119. } else {
  120. return ['status' => false, 'data' => $mediaResult['message']];
  121. }
  122. } catch (\Exception $e) {
  123. return ['status' => false, 'data' => $e->getMessage()];
  124. }
  125. }
  126. public function postVideo($message, $videoPath, $accessToken = null)
  127. {
  128. try {
  129. $this->access_token = $accessToken;
  130. $videoPath = toStoragePath($videoPath);//用本地路径上传
  131. $mediaResult = $this->uploadAndPost([$videoPath], $message);
  132. if (isset($mediaResult['response']['data']['id'])) {
  133. return ['status' => true,
  134. 'data' => [
  135. 'responseIds' => [$mediaResult['response']['data']['id']],
  136. ]
  137. ];
  138. } else {
  139. return ['status' => false, 'data' => $mediaResult['message']];
  140. }
  141. } catch (\Exception $e) {
  142. return ['status' => false, 'data' => $e->getMessage()];
  143. }
  144. }
  145. // 保持空实现
  146. public function getComments($postId) {}
  147. public function replyToComment($commentId) {}
  148. public function deleteComment($commentId) {}
  149. /**
  150. * 通用Twitter API请求
  151. */
  152. private function twitterApiRequest($url, $method = 'POST', $data = [], $headers = []) {
  153. try {
  154. Log::info('curl 请求:'.$url);
  155. $ch = curl_init();
  156. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 不验证对等证书
  157. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); // 不验证主机名
  158. $headers = array_merge([
  159. 'Authorization: Bearer ' . $this->access_token
  160. ], $headers);
  161. Log::info('curl $headers:'.json_encode($headers));
  162. curl_setopt_array($ch, [
  163. CURLOPT_URL => $url,
  164. CURLOPT_RETURNTRANSFER => true,
  165. CURLOPT_FOLLOWLOCATION => true,
  166. CURLOPT_HTTPHEADER => $headers,
  167. CURLOPT_TIMEOUT => 50,
  168. ]);
  169. if ($method === 'POST') {
  170. curl_setopt($ch, CURLOPT_POST, true);
  171. // 处理JSON数据
  172. curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
  173. }
  174. $response = curl_exec($ch);
  175. $error = curl_error($ch);
  176. curl_close($ch);
  177. Log::info('curl response:'.$response);
  178. if ($error) {
  179. throw new \Exception("cURL Error: ".$error);
  180. }
  181. if ($response === false) {
  182. throw new \Exception("cURL Error: false response");
  183. }
  184. $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  185. return ['code'=>$http_code,'response' => json_decode($response, true)];
  186. } catch (\Exception $e) {
  187. throw new \Exception("catch cURL Error: ".$e->getMessage());
  188. }
  189. }
  190. /**
  191. * 初始化上传
  192. */
  193. public function initUpload($fileSize, $mediaType = 'video/mp4',$media_category = 'tweet_video') {
  194. return $this->twitterApiRequest($this->media_upload_url, 'POST', [
  195. 'command' => 'INIT',
  196. 'media_type' => $mediaType,
  197. 'total_bytes' => $fileSize,
  198. 'media_category' => $media_category
  199. ]);
  200. }
  201. /**
  202. * 分块上传
  203. */
  204. public function appendUpload($media_id, $filePath) {
  205. $handle = fopen($filePath, 'rb');
  206. $segment_index = 0;
  207. while (!feof($handle)) {
  208. $chunk = fread($handle, $this->chunk_size);
  209. $result = $this->twitterApiRequest($this->media_upload_url, 'POST', [
  210. 'command' => 'APPEND',
  211. 'media_id' => $media_id,
  212. 'segment_index' => $segment_index,
  213. 'media' => $chunk
  214. ]);
  215. Log::info('分块上传'.$segment_index.' : '.json_encode($result));
  216. if ($result['code'] !== 204) {
  217. return false;
  218. }
  219. $segment_index++;
  220. sleep(2); // 避免速率限制
  221. }
  222. fclose($handle);
  223. return true;
  224. }
  225. /**
  226. * 完成上传
  227. */
  228. public function finalizeUpload($media_id) {
  229. return $this->twitterApiRequest($this->media_upload_url, 'POST', [
  230. 'command' => 'FINALIZE',
  231. 'media_id' => $media_id
  232. ]);
  233. }
  234. /**
  235. * 检查媒体状态
  236. */
  237. public function checkStatus($media_id) {
  238. $url = $this->media_upload_url . '?' . http_build_query([
  239. 'command' => 'STATUS',
  240. 'media_id' => $media_id
  241. ]);
  242. return $this->twitterApiRequest($url, 'GET');
  243. }
  244. /**
  245. * 等待媒体处理完成
  246. */
  247. public function waitForProcessing($media_id, $interval = 10, $max_attempts = 6) {
  248. $attempts = 0;
  249. do {
  250. $status = $this->checkStatus($media_id);
  251. Log::info('等待媒体处理完成:'.$attempts.' : '.json_encode($status));
  252. if (!isset($status['response']['data'])) {
  253. throw new \Exception("waitForProcessing failed: status data not found");
  254. }
  255. $state = $status['response']['data']['processing_info']['state'] ?? '';
  256. if ($state === 'succeeded') return true;
  257. if ($state === 'failed') return false;
  258. sleep($interval);
  259. $attempts++;
  260. } while ($attempts < $max_attempts);
  261. throw new \Exception("Media processing timeout");
  262. }
  263. /**
  264. * 发布推文
  265. */
  266. public function postTweet($text, $media_ids) {
  267. $data = [
  268. 'text' => $text,
  269. 'media' => ['media_ids' => $media_ids]
  270. ];
  271. $data = json_encode($data);
  272. Log::info('发布推文数据:'.$data);
  273. return $this->twitterApiRequest($this->tweet_url, 'POST',$data , ['Content-Type: application/json']);
  274. }
  275. /**
  276. * 完整上传流程
  277. */
  278. public function uploadAndPost($filePaths, $tweetText) {
  279. try {
  280. $media_ids = [];
  281. foreach ($filePaths as $filePath) {
  282. $file_info = pathinfo($filePath);
  283. $file_extension = $file_info['extension'];
  284. if ($file_extension == 'mp4' && filesize($filePath) > 20 * 1024 * 1024) {
  285. //不能大于20M
  286. return ['status'=>false,'message' => 'File size too large (max 20M)'];
  287. } else if (($file_extension == 'jpg' || $file_extension == 'png') && filesize($filePath) > 3 * 1024 * 1024) {
  288. //不能大于5M
  289. return ['status'=>false,'message' => 'File size too large (max 5M)'];
  290. }
  291. if ($file_extension == 'mp4') {
  292. $media_category = 'tweet_video';
  293. $mediaType = 'video/mp4';
  294. } else if ($file_extension == 'jpg') {
  295. $media_category = 'tweet_image';
  296. $mediaType = 'image/jpeg';
  297. } else {
  298. $media_category = 'tweet_image';
  299. $mediaType = 'image/png';
  300. }
  301. Log::info('Twitter开始发布帖子,文件格式:'.$file_extension);
  302. // 1. 初始化上传
  303. $init = $this->initUpload(filesize($filePath),$mediaType,$media_category);
  304. $media_id = isset($init['response']['data']['id']) ? $init['response']['data']['id'] : null;
  305. $media_ids[] = $media_id;
  306. if (!$media_id) {
  307. return ['status'=>false,'message' => 'Init upload failed'];
  308. }
  309. Log::info('初始化上传成功'.$media_id);
  310. // 2. 分块上传
  311. $append = $this->appendUpload($media_id, $filePath);
  312. if (!$append) {
  313. return ['status'=>false,'message' => 'Append upload failed'];
  314. }
  315. // 3. 完成上传
  316. $finalize = $this->finalizeUpload($media_id);
  317. Log::info('完成上传:'.json_encode($finalize));
  318. if (isset($finalize['response']['data']) == false) {
  319. return ['status'=>false,'message' => 'Finalize upload failed'];
  320. }
  321. // 4. mp4 等待处理完成
  322. if ($file_extension == 'mp4') {
  323. Log::info('等待处理完成');
  324. if (!$this->waitForProcessing($media_id)) {
  325. throw new \Exception('Media processing failed');
  326. }
  327. }
  328. }
  329. // 5. 发布推文
  330. Log::info('发布推文');
  331. $postTweet = $this->postTweet($tweetText, $media_ids);
  332. Log::info('发布推文结果:'.json_encode($postTweet));
  333. return $postTweet;
  334. } catch (\Exception $e) {
  335. Log::info('uploadAndPost error:'.$e->getMessage());
  336. return ['status'=>false,'message' => "Upload failed: ".$e->getMessage()];
  337. }
  338. }
  339. public function refreshAccessToken($refreshToken)
  340. {
  341. try {
  342. $tokenUrl = 'https://api.twitter.com/2/oauth2/token';
  343. $params = [
  344. 'refresh_token' => $refreshToken,
  345. 'grant_type' => 'refresh_token',
  346. 'client_id' => $this->clientId,
  347. ];
  348. $ch = curl_init();
  349. curl_setopt($ch, CURLOPT_URL, $tokenUrl);
  350. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  351. curl_setopt($ch, CURLOPT_POST, true);
  352. curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
  353. curl_setopt($ch, CURLOPT_HTTPHEADER, [
  354. 'Authorization: Basic ' . base64_encode($this->clientId . ':' . $this->clientSecret),
  355. 'Content-Type: application/x-www-form-urlencoded'
  356. ]);
  357. $response = curl_exec($ch);
  358. $error = curl_error($ch);
  359. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  360. curl_close($ch);
  361. if ($error) {
  362. throw new \Exception("cURL Error: " . $error);
  363. }
  364. $authData = json_decode($response, true);
  365. if (!$authData || isset($authData['error'])) {
  366. throw new \Exception("Token refresh failed: " . ($authData['error_description'] ?? 'Unknown error'));
  367. }
  368. if (!isset($authData['access_token'])) {
  369. throw new \Exception("Access token not found in response");
  370. }
  371. $newAccessToken = $authData['access_token'];
  372. $newRefreshToken = $authData['refresh_token'] ?? $refreshToken; // 使用新的refresh_token,若未返回则保留原值
  373. $expiresIn = $authData['expires_in'] ?? 0;
  374. $expiresAt = Carbon::now()->addSeconds($expiresIn)->format('Y-m-d H:i:s');
  375. return [
  376. 'status' => true,
  377. 'data' => [
  378. 'access_token' => $newAccessToken,
  379. 'refresh_token' => $newRefreshToken,
  380. 'expires_at' => $expiresAt,
  381. ],
  382. ];
  383. } catch (\Exception $e) {
  384. Log::error("Twitter刷新Token失败: " . $e->getMessage());
  385. return [
  386. 'status' => false,
  387. 'data' => $e->getMessage(),
  388. ];
  389. }
  390. }
  391. }