如何使用PHP curl刷新Hootsuite access_token API服务器到服务器调用

wnvonmuf  于 2022-12-27  发布在  PHP
关注(0)|答案(2)|浏览(149)

我正在使用Postman按照Hootsuite提供的文档获取访问令牌。该过程涉及使用所需参数(client_idresponse_type=coderedirect_uriscope)请求对端点进行授权。身份验证完成后,Hootsuite将发送access_tokenrefresh_token
提供的访问令牌只有60分钟的过期时间。因此,需要经常刷新令牌。根据他们的文档,刷新工作流,应该进行服务器到服务器的请求,其中应该在请求中发送refresh_token以获得新的access_token(其将在常规呼叫中使用,如调度消息)和将再次使用以获得更新令牌的新refresh_token,等等。
我的代码如下所示(代码中的注解解释了步骤):

<?php
$api = 'https://platform.hootsuite.com/oauth2/token';//endpoint
//parameters passed below
$data = array(
    'grant_type' => 'refresh_token',
    'refresh_token' => 'refresh_token_obtained_during_the_authorization',
    'scope' => 'offline'
);
$payload = json_encode($data);//convert parameters to json
//header sent below
$header = array(
    'client_id: my_client_id_xxxxxxx',
    'client_secret: my_client_seceret_xxxxxx',
    'Content-Type: application/json',
    'Content-Length: ' . strlen($payload)
);
$ch = curl_init($api);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");//set to post.
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);//send the parameters.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//expect respond.
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);//send headers.
$result = json_decode(curl_exec($ch));//execute
print_r ($result);//get responce
?>

问题是,虽然我已经仔细遵循了文档。但是,我不断收到错误消息400如下:
stdClass对象([错误] =〉invalid_request [错误描述] =〉请求缺少必需的参数、包含无效的参数值、包含一个参数多次或格式不正确[错误提示] =〉POST主体不能为空。[状态代码] =〉400)
如果您能帮助我找出代码或流程本身的错误,我将不胜感激。

yc0p9oo0

yc0p9oo01#

你应该做的是不要使用client_id,client_secret作为头文件,但是你应该通过curl_setopt来使用基本的auth头文件。
curl_setopt($ch, CURLOPT_USERPWD, "$my_client_id:$my_client_secret");

x6yk4ghg

x6yk4ghg2#

你需要发送授权头为“Basic”,base64编码。下面是我的python工作代码:

def refreshToken(self, client_id, client_secret, refresh_token):
    api_path = '/oauth2/token'
    
    auth_msg = client_id + ':' + client_secret
    auth_msg_bt = auth_msg.encode('ascii')
    auth = base64.b64encode(auth_msg_bt)
    auth = auth.decode('ascii')
    
    headers = { 'Authorization' : 'Basic ' + auth }
    data = { 
        'grant_type' : 'refresh_token',
        'refresh_token' : refresh_token     
    }
    try:
        response = requests.post(self.base_url + api_path, data=data, headers=headers)
        return response.json()
    except Exception as e:
        logging.exception('Error while refreshing token', e)
        return None

相关问题