Skip to main content
 首页 » 编程设计

php之从 API (oauth2) 获取访问 token

2025年02月15日27bhlsheji

我是 Python 脚本的初学者,但遇到了问题。

我正在尝试将 PHP 代码重写为 Python 以从 API 获取访问 token 以供进一步使用。

##/* Request for access token */ 
 
$base_url = "myurl"; 
$client_id="1234"; 
$client_secret="5678"; 
 
$client_details = "${client_id}:${client_secret}"; 
 
$context = stream_context_create(array( 
    'http' => array( 
    'method' => 'POST', 
    'header' => "Content-Type: application/x-www-form-urlencoded\r\n" . 
                "Authorization : Basic $client_details\r\n", 
    'content' => "grant_type=client_credentials" 
    ) 
)); 
 
$response = file_get_contents($base_url.'/apis/oauth2/Token.php', false, $context); 
$res =  json_decode($response); 
$token = $res->access_token; 

这就是我想用 Python 做的事情。

我的 Python 代码是:

import urllib 
import sys 
import json 
import requests 
 
base_url = 'myurl' 
client_id='1234' 
client_secret='5678' 
 
response = requests.post(base_url+'/apis/oauth2/Token.php', 
                    auth=(client_id, client_secret)) 
 
print(response.json()) 

但这行不通

Python 正在回归:

{'error': 'invalid_request', 'error_description': 'The grant type was not specified in the request'} 

我知道我遗漏了 PHP 代码中上下文变量的所有内容。您知道是否有 Python 方法可以在 PHP 中创建类似 stream_context_create 的上下文,或者您能否给我一些提示,我该怎么做?

请您参考如下方法:

我设法解决了我的问题。 这是代码:

import urllib 
import sys 
import json 
import requests 
 
base_url = 'https://myurl.com' 
client_id='1234' 
client_secret='5678' 
grant_type='client_credentials' 
 
response = requests.post(base_url+'/apis/oauth2/Token.php', 
                        auth=(client_id, client_secret), 
                         data={'grant_type':grant_type,'client_id':client_id,'client_secret':client_secret}) 
print(response.json())