@Rec1cle

Как проверить пользователь сделал ретвит или нет на вордпресс?

Хочу узнать как можно проверить сделал ли пользователь ретвит поста или нет?

В functions.php написал такой код:

function getTwitterBearerToken() {
    $api_key = 'здесь мой айпи';
    $api_secret_key = 'здесь мой айпи';

    $credentials = base64_encode($api_key . ':' . $api_secret_key);

    $url = 'https://api.twitter.com/oauth2/token';

    $headers = [
        'Authorization: Basic ' . $credentials,
        'Content-Type: application/x-www-form-urlencoded;charset=UTF-8'
    ];

    $fields = 'grant_type=client_credentials';

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curlError = curl_error($ch);
    curl_close($ch);

    if ($httpCode !== 200) {
        error_log('Twitter API error: ' . $httpCode . ' ' . $curlError);
        return null;
    }

    $token = json_decode($response);
    return $token->access_token;
}

function checkIfRetweeted($tweetId, $bearerToken) {
    $url = "https://api.twitter.com/1.1/statuses/show.json?id=" . $tweetId;
    
    $headers = [
        'Authorization: Bearer ' . $bearerToken
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curlError = curl_error($ch);
    curl_close($ch);

    if ($httpCode !== 200) {
        error_log('Twitter API error: ' . $httpCode . ' ' . $curlError);
        return null;
    }

    $data = json_decode($response, true);
    if (isset($data['retweeted'])) {
        return $data['retweeted'];
    } else {
        error_log('Invalid API response: ' . $response);
        return null;
    }
}

function create_retweet_button($atts) {
    $a = shortcode_atts(array(
        'tweet_id' => '1803847412793893341', // ID твита, который нужно ретвитнуть
    ), $atts);

    $tweet_id = esc_attr($a['tweet_id']);
    
    return '<button class="retweet-button" data-tweet-id="' . $tweet_id . '">Retweet</button>';
}

add_shortcode('retweet_button', 'create_retweet_button');

Есть еще скрипт, который проверяет сделан ли ретвит или нет:

<script src="https://platform.twitter.com/widgets.js"></script>
<script>
    document.addEventListener('DOMContentLoaded', function () {
        const buttons = document.querySelectorAll('.retweet-button');

        buttons.forEach(button => {
            button.addEventListener('click', function () {
                const tweetId = button.getAttribute('data-tweet-id');
                const url = `https://twitter.com/intent/retweet?tweet_id=${tweetId}`;
                
                // Открываем окно для ретвита
                const width = 550;
                const height = 420;
                const left = (screen.width / 2) - (width / 2);
                const top = (screen.height / 2) - (height / 2);
                const retweetWindow = window.open(url, 'Retweet', `width=${width},height=${height},top=${top},left=${left}`);

                console.log('Retweet window opened.');

                // Функция для отслеживания закрытия окна
                const checkWindowClosed = setInterval(async function() {
                    if (retweetWindow.closed) {
                        clearInterval(checkWindowClosed);
                        console.log('Retweet window closed. Checking retweet status...');

                        // Проверка успешного ретвита через серверный скрипт
                        const isRetweeted = await checkIfRetweeted(tweetId);
                        console.log(`Retweet status for tweet ${tweetId}: ${isRetweeted}`);
                        if (isRetweeted === true) {
                            button.disabled = true;
                            button.innerText = 'Retweeted';
                        } else {
                            console.log('Retweet was not successful or an error occurred.');
                        }
                    }
                }, 1000); // Проверяем каждую секунду
            });
        });

        async function checkIfRetweeted(tweetId) {
            try {
                const response = await fetch(`/check-retweet.php?tweet_id=${tweetId}`);
                const data = await response.json();
                console.log('Server response:', data);
                if (data.error) {
                    console.error('Error from server:', data.message);
                    return false;
                }
                return data.retweeted === true; // Возвращает true если ретвит выполнен
            } catch (error) {
                console.error('Error checking retweet status:', error);
                return false;
            }
        }
    });
</script>

Еще создал файл check-retweet.php в корневом папке сайта для серверного скрипта:

<?php
header('Content-Type: application/json');

$bearerToken = 'Мой беарер токен';
$tweetId = $_GET['tweet_id'];

function checkIfRetweeted($tweetId, $bearerToken) {
    $url = "https://api.twitter.com/1.1/statuses/show.json?id=" . $tweetId;
    
    $headers = [
        'Authorization: Bearer ' . $bearerToken
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curlError = curl_error($ch);
    curl_close($ch);

    if ($httpCode !== 200) {
        return ['error' => true, 'message' => 'Twitter API error: ' . $httpCode, 'response' => $response, 'curlError' => $curlError];
    }

    $data = json_decode($response, true);
    if (isset($data['retweeted'])) {
        return ['retweeted' => $data['retweeted']];
    } else {
        return ['error' => true, 'message' => 'Invalid API response', 'response' => $response];
    }
}

$result = checkIfRetweeted($tweetId, $bearerToken);
echo json_encode($result);
?>

Вроде по логике все должно работать, но когда нажимаю кнопку ретвит и делаю репост, кнопка все равно остается активно, хотя должна деактивироваться.
Сам сайт - https://cz50268-wordpress-f6te0.tw1.ru/
Кнопка в главной странице.

Когда перехожу по ссылке https://cz50268-wordpress-f6te0.tw1.ru/check-retwe... то там ошибка:

{"error":true,"message":"Twitter API error: 403","response":"{\"errors\":[{\"message\":\"You currently have access to a subset of Twitter API v2 endpoints and limited v1.1 endpoints (e.g. media post, oauth) only. If you need access to this endpoint, you may need a different access level. You can learn more here: https:\/\/developer.twitter.com\/en\/portal\/product\",\"code\":453}]}\n","curlError":""}
  • Вопрос задан
  • 85 просмотров
Пригласить эксперта
Ответы на вопрос 1
@historydev
Тебе же пишут, если ты хочешь постучаться на этот end-поинт, тебе нужны повышенные права, 403 = forbidden.
Так что скорее всего твой код в порядке, а вот api ключ - нет.

Выясни как повысить уровень доступа и будет тебе счастье.
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы