文字数[2908文字] この記事は4分38秒で読めます.

x.comのAPI(FREE)にて自分のユーザー情報を取得するには

20240605

Logging

おはようございます.x.comのAPI(FREE)にて自分のユーザー情報を取得するにはってググってもv1.1の情報だらけだったので情報を記載します.v2対応です.一部、有料でないと取得できない部分があり返却もエラーで返ってきますが、雛形コードを記載します.

注意事項
TwitterOAuthというComposerライブラリを使用しています.
APIなどの値はご自身のAPIに合わしてください.

参考にしたサイト
https://developer.x.com/en/docs/twitter-api/users/lookup/api-reference/get-users-me

<?php
date_default_timezone_set('Asia/Tokyo');
require_once "../vendor/autoload.php";

use Abraham\TwitterOAuth\TwitterOAuth;

class xMyProfile
{

    public $connection = null;
    public $response = null;

    public function __construct()
    {
        $this->connection = new TwitterOAuth(APIKEY, APISECRET, ACCESSTOKEN, ACCESSTOKENSECRET);
        $this->connection->setApiVersion("2");
        $this->response = $this->connection->get('users/me', [
            'expansions'=>'pinned_tweet_id',
            'tweet.fields'=>implode(',',[
                'attachments',
                'author_id',
                'context_annotations',
                'conversation_id',
                'created_at',
                'edit_controls',
                'entities',
                'geo',
                'id',
                'in_reply_to_user_id',
                'lang',
                'non_public_metrics',
                'public_metrics',
                'organic_metrics',
                'promoted_metrics',
                'possibly_sensitive',
                'referenced_tweets',
                'reply_settings',
                'source',
                'text',
                'withheld'
            ]),
            'user.fields' => implode(',', [
                'created_at',
                'description',
                'entities',
                'id',
                'location',
                'most_recent_tweet_id',
                'name',
                'pinned_tweet_id',
                'profile_image_url',
                'protected',
                'public_metrics',
                'url',
                'username',
                'verified',
                'verified_type',
                'withheld'
            ])
        ]);
        return $this;
    }

    /**
     * プロフィール情報全てを取得
     */
    public function getMyProfile()
    {
        return $this->response;
    }
    /**
     * プロフィールアイコンURLを取得
     */
    public function getIconUrl()
    {
        return $this->response->data->profile_image_url;
    }
}
var_dump((new xMyProfile)->getMyProfile());
//print (new xMyProfile)->getIconUrl();

この記事はQiitaに掲載していた記事になります.

明日へ続く.

6 Views

著者名  @taoka_toshiaki

Profile
高知県在住の@taoka_toshiakiです、記事を読んで頂きありがとうございます.
数十年前から息を吸うように日々記事を書いてます.たまに休んだりする日もありますがほぼ毎日投稿を心掛けています😅.
SNSも使っています、フォロー、いいね、シェア宜しくお願い致します🙇.
SNS::@taoka_toshiaki

タグ

connection, construct, edit_controls, getIconUrl, getMyProfile, implode, lt, null, organic_metrics, print, promoted_metrics, public, qiita, quot, response, return, use AbrahamTwitterOAuthTwitterOAuth, users, vendor, X.com,