PHPでTwitter Oauth2.0を利用したログインの実装で、「Authorize app」クリック後、callback URLに遷移すると下記のようなエラーが出ます。
{"error":"invalid_request","error_description":"Missing required parameter [grant_type]."}int(1)
ソースコードは下記です。どのようにすればうまくいくか、わかる方いたら教えていただけると助かります。
login.php
PHP
<?php session_start(); define('Consumer_Key', '<Consumer Key>'); define('Consumer_Secret', 'Consumer Secret'); define('Callback', 'http://127.0.0.1:3000/callback.php'); define('Client_id', 'Client ID'); $base_url = 'https://twitter.com/i/oauth2/authorize'; $query = [ 'response_type' => 'code', 'client_id' => Client_id, 'redirect_uri' => Callback, 'scope' => 'tweet.read users.read offline.access', 'state' => 'state', 'code_challenge' => 'codeChallenge', 'code_challenge_method' => 'S256' ]; $url = $base_url . '?' . http_build_query($query); header('Location: ' . $url); ?>
callback.php
PHP
<?php session_start(); define('Consumer_Key', 'Consumer Key'); define('Consumer_Secret', 'Consumer Secret'); define('Callback', 'http://127.0.0.1:3000/callback.php'); define('Client_id', 'Client ID'); define('Client_Secret', 'Client Secret'); $base_url = 'https://api.twitter.com/2/oauth2/token'; $user_creds = Consumer_Key.':'.Consumer_Secret; $client = Client_id.':'.Client_Secret; $authorization_code = $_GET['code']; $header = array( "Authorization: Basic " . $client, "Content-Type: application/x-ww-form-urlencoded", ); $data = array( "grant_type" => "client_credentials", "client_id" => Client_id, "client_secret" => Client_Secret, "code" => $authorization_code, "redirect_uri" => Callback, "code_verifier" => "challenge", ); $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $base_url); curl_setopt($curl, CURLOPT_HTTPHEADER, $header); curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data)); $response = curl_exec($curl); $result = json_decode($response, true); curl_close($curl); var_dump($result); ?>
●参考にしていたURL
https://zenn.dev/kg0r0/articles/8b1cfe654a1cee
https://developer.twitter.com/en/docs/authentication/oauth-2-0/authorization-code
まだ回答がついていません
会員登録して回答してみよう