如何在PHP中使用Refresh Token刷新DocuSign的Access Token?
解决DocuSign刷新Access Token时的"invalid_grant/unsupported_grant_type"错误
错误原因分析
- Basic Auth编码逻辑错误:HTTP Basic Auth要求把
{client_id}:{client_secret}拼接后的完整字符串做Base64编码,而非分别编码两个字段再拼接。 - POST数据格式不匹配:用数组作为
CURLOPT_POSTFIELDS参数时,cURL会自动把请求的Content-Type改成multipart/form-data,但DocuSign的OAuth接口只接受application/x-www-form-urlencoded格式的请求体。
修正后的代码
$client_id = env('DOCUSIGN_CLIENT_ID'); $client_secret = env('DOCUSIGN_CLIENT_SECRET'); // 正确生成Basic Auth凭证:拼接后整体Base64编码 $auth_string = base64_encode("{$client_id}:{$client_secret}"); $integrator_and_secret_key = "Basic {$auth_string}"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'https://account-d.docusign.com/oauth/token'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1); // 把POST数据转成URL编码字符串,确保格式符合接口要求 $data = http_build_query([ 'refresh_token' => "My refresh token from previous successful request", 'grant_type' => 'refresh_token', ]); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); $headers = array(); $headers[] = "Authorization: {$integrator_and_secret_key}"; $headers[] = 'Content-Type: application/x-www-form-urlencoded'; $headers[] = 'Cache-Control: no-cache'; curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); $result = curl_exec($ch); if (curl_errno($ch)) { echo 'Error:' . curl_error($ch); } Log::info($result);
关键改动说明
- 修复Basic Auth生成:移除了分别编码client_id和client_secret的错误操作,改为直接拼接后整体编码,符合HTTP标准规范。
- 调整POST数据格式:用
http_build_query()把数组转成URL编码字符串,保证请求体格式和接口要求的application/x-www-form-urlencoded一致。 - 简化请求头设置:直接复用生成好的完整Auth头,避免重复拼接出错。
内容的提问来源于stack exchange,提问作者Odda Kussa
相关产品推荐
相关产品推荐

