PHPでTwitter Oauth2.0を利用したログインの実装で、「Authorize app」クリック後、callback URLに遷移すると下記のようなエラーが出ます。
{"error":"invalid_request","error_description":"Missing required parameter [grant_type]."}int(1)
ソースコードは下記です。どのようにすればうまくいくか、わかる方いたら教えていただけると助かります。
login.php
PHP
1<?php 2 session_start(); 3 4 define('Consumer_Key', '<Consumer Key>'); 5 define('Consumer_Secret', 'Consumer Secret'); 6 define('Callback', 'http://127.0.0.1:3000/callback.php'); 7 define('Client_id', 'Client ID'); 8 9 $base_url = 'https://twitter.com/i/oauth2/authorize'; 10 11 $query = [ 12 'response_type' => 'code', 13 'client_id' => Client_id, 14 'redirect_uri' => Callback, 15 'scope' => 'tweet.read users.read offline.access', 16 'state' => 'state', 17 'code_challenge' => 'codeChallenge', 18 'code_challenge_method' => 'S256' 19 ]; 20 21 $url = $base_url . '?' . http_build_query($query); 22 23 header('Location: ' . $url); 24 25?> 26
callback.php
PHP
1<?php 2 session_start(); 3 4 define('Consumer_Key', 'Consumer Key'); 5 define('Consumer_Secret', 'Consumer Secret'); 6 define('Callback', 'http://127.0.0.1:3000/callback.php'); 7 define('Client_id', 'Client ID'); 8 define('Client_Secret', 'Client Secret'); 9 10 $base_url = 'https://api.twitter.com/2/oauth2/token'; 11 $user_creds = Consumer_Key.':'.Consumer_Secret; 12 $client = Client_id.':'.Client_Secret; 13 $authorization_code = $_GET['code']; 14 15 $header = array( 16 "Authorization: Basic " . $client, 17 "Content-Type: application/x-ww-form-urlencoded", 18 ); 19 20 $data = array( 21 "grant_type" => "client_credentials", 22 "client_id" => Client_id, 23 "client_secret" => Client_Secret, 24 "code" => $authorization_code, 25 "redirect_uri" => Callback, 26 "code_verifier" => "challenge", 27 ); 28 29 $curl = curl_init(); 30 31 curl_setopt($curl, CURLOPT_URL, $base_url); 32 curl_setopt($curl, CURLOPT_HTTPHEADER, $header); 33 curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data)); 34 35 $response = curl_exec($curl); 36 $result = json_decode($response, true); 37 38 curl_close($curl); 39 40 var_dump($result); 41 42?> 43
●参考にしていたURL
https://zenn.dev/kg0r0/articles/8b1cfe654a1cee
https://developer.twitter.com/en/docs/authentication/oauth-2-0/authorization-code

バッドをするには、ログインかつ
こちらの条件を満たす必要があります。