TwitterService.php 16 KB

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