TwitterService.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  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. $tweetText = $this->truncateText($tweetText, 138);// 截断推文
  281. $media_ids = [];
  282. foreach ($filePaths as $filePath) {
  283. $file_info = pathinfo($filePath);
  284. $file_extension = $file_info['extension'];
  285. if ($file_extension == 'mp4' && filesize($filePath) > 20 * 1024 * 1024) {
  286. //不能大于20M
  287. return ['status'=>false,'message' => 'File size too large (max 20M)'];
  288. } else if (($file_extension == 'jpg' || $file_extension == 'png') && filesize($filePath) > 3 * 1024 * 1024) {
  289. //不能大于5M
  290. return ['status'=>false,'message' => 'File size too large (max 5M)'];
  291. }
  292. if ($file_extension == 'mp4') {
  293. $media_category = 'tweet_video';
  294. $mediaType = 'video/mp4';
  295. } else if ($file_extension == 'jpg') {
  296. $media_category = 'tweet_image';
  297. $mediaType = 'image/jpeg';
  298. } else {
  299. $media_category = 'tweet_image';
  300. $mediaType = 'image/png';
  301. }
  302. Log::info('Twitter开始发布帖子,文件格式:'.$file_extension);
  303. // 1. 初始化上传
  304. $init = $this->initUpload(filesize($filePath),$mediaType,$media_category);
  305. $media_id = isset($init['response']['data']['id']) ? $init['response']['data']['id'] : null;
  306. $media_ids[] = $media_id;
  307. if (!$media_id) {
  308. return ['status'=>false,'message' => 'Init upload failed'];
  309. }
  310. Log::info('初始化上传成功'.$media_id);
  311. // 2. 分块上传
  312. $append = $this->appendUpload($media_id, $filePath);
  313. if (!$append) {
  314. return ['status'=>false,'message' => 'Append upload failed'];
  315. }
  316. // 3. 完成上传
  317. $finalize = $this->finalizeUpload($media_id);
  318. Log::info('完成上传:'.json_encode($finalize));
  319. if (isset($finalize['response']['data']) == false) {
  320. return ['status'=>false,'message' => 'Finalize upload failed'];
  321. }
  322. // 4. mp4 等待处理完成
  323. if ($file_extension == 'mp4') {
  324. Log::info('等待处理完成');
  325. if (!$this->waitForProcessing($media_id)) {
  326. throw new \Exception('Media processing failed');
  327. }
  328. }
  329. }
  330. // 5. 发布推文
  331. Log::info('发布推文');
  332. $postTweet = $this->postTweet($tweetText, $media_ids);
  333. Log::info('发布推文结果:'.json_encode($postTweet));
  334. return $postTweet;
  335. } catch (\Exception $e) {
  336. Log::info('uploadAndPost error:'.$e->getMessage());
  337. return ['status'=>false,'message' => "Upload failed: ".$e->getMessage()];
  338. }
  339. }
  340. public function refreshAccessToken($refreshToken)
  341. {
  342. try {
  343. $tokenUrl = 'https://api.twitter.com/2/oauth2/token';
  344. $params = [
  345. 'refresh_token' => $refreshToken,
  346. 'grant_type' => 'refresh_token',
  347. 'client_id' => $this->clientId,
  348. ];
  349. $ch = curl_init();
  350. curl_setopt($ch, CURLOPT_URL, $tokenUrl);
  351. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  352. curl_setopt($ch, CURLOPT_POST, true);
  353. curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
  354. curl_setopt($ch, CURLOPT_HTTPHEADER, [
  355. 'Authorization: Basic ' . base64_encode($this->clientId . ':' . $this->clientSecret),
  356. 'Content-Type: application/x-www-form-urlencoded'
  357. ]);
  358. $response = curl_exec($ch);
  359. $error = curl_error($ch);
  360. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  361. curl_close($ch);
  362. if ($error) {
  363. throw new \Exception("cURL Error: " . $error);
  364. }
  365. $authData = json_decode($response, true);
  366. if (!$authData || isset($authData['error'])) {
  367. throw new \Exception("Token refresh failed: " . ($authData['error_description'] ?? 'Unknown error'));
  368. }
  369. if (!isset($authData['access_token'])) {
  370. throw new \Exception("Access token not found in response");
  371. }
  372. $newAccessToken = $authData['access_token'];
  373. $newRefreshToken = $authData['refresh_token'] ?? $refreshToken; // 使用新的refresh_token,若未返回则保留原值
  374. $expiresIn = $authData['expires_in'] ?? 0;
  375. $expiresAt = Carbon::now()->addSeconds($expiresIn)->format('Y-m-d H:i:s');
  376. return [
  377. 'status' => true,
  378. 'data' => [
  379. 'access_token' => $newAccessToken,
  380. 'refresh_token' => $newRefreshToken,
  381. 'expires_at' => $expiresAt,
  382. ],
  383. ];
  384. } catch (\Exception $e) {
  385. Log::error("Twitter刷新Token失败: " . $e->getMessage());
  386. return [
  387. 'status' => false,
  388. 'data' => $e->getMessage(),
  389. ];
  390. }
  391. }
  392. /**
  393. * 安全截断多字节文本(支持中文、日文等)
  394. * @param string $text 原始文本
  395. * @param int $maxLength 最大长度(默认280)
  396. * @param string $ellipsis 截断后缀(默认...)
  397. * @return string 处理后的文本
  398. */
  399. function truncateText(string $text, int $maxLength = 140, string $ellipsis = ''): string {
  400. // 检测文本长度
  401. $textLength = mb_strlen($text, 'UTF-8');
  402. if ($textLength <= $maxLength) {
  403. return $text;
  404. }
  405. // 计算后缀长度
  406. $ellipsisLength = mb_strlen($ellipsis, 'UTF-8');
  407. // 确保后缀不会导致总长度超过限制
  408. $truncateLength = $maxLength - $ellipsisLength;
  409. // 安全截取并添加后缀
  410. return mb_substr($text, 0, $truncateLength, 'UTF-8') . $ellipsis;
  411. }
  412. }