You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用DocuSign PHP SDK下载信封文档时PDF损坏问题

解决DocuSign下载PDF文档损坏的问题

在Laravel项目中通过原生curl调用DocuSign API下载已签署的信封文档,保存后打开提示文档损坏,相关代码如下:

$ch = curl_init();
$headers = array(
    'Content-Type: application/pdf',
    'Authorization: Bearer '.$_SESSION['docusign_auth_code']
);
curl_setopt($ch, CURLOPT_URL, 'https://demo.docusign.net/restapi/v2/accounts/{account_id}/envelopes/{envelop_id}/documents/1/');
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$file_content = curl_exec($ch);
file_put_contents("my_document.pdf", ($file_content));
return $file_content;

问题原因及修复方案

1. 修正请求头

GET请求无需设置Content-Type(该头用于标识请求体类型,而GET请求无请求体),正确做法是添加Accept: application/pdf,明确告知API返回PDF格式内容:

$headers = array(
    'Accept: application/pdf',
    'Authorization: Bearer '.$_SESSION['docusign_auth_code']
);

2. 强制处理二进制数据

添加CURLOPT_BINARYTRANSFER选项,确保curl返回原始二进制数据,避免自动转码导致PDF内容损坏:

curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);

3. 检查请求错误

执行curl后务必检查是否有错误发生,避免将错误信息(如权限不足、信封ID错误返回的JSON)写入PDF文件:

$file_content = curl_exec($ch);
if (curl_errno($ch)) {
    throw new Exception('Curl请求错误: ' . curl_error($ch));
}
curl_close($ch); // 记得关闭curl资源

4. 优先使用官方SDK

原生curl容易遗漏API细节处理,使用DocuSign官方PHP SDK能更可靠完成文档下载,示例代码:

use DocuSign\eSign\Client\ApiClient;
use DocuSign\eSign\Configuration;

// 初始化配置
$config = new Configuration();
$config->setHost('https://demo.docusign.net/restapi');
$config->addDefaultHeader('Authorization', 'Bearer ' . $_SESSION['docusign_auth_code']);

$apiClient = new ApiClient($config);
$envelopesApi = new \DocuSign\eSign\Api\EnvelopesApi($apiClient);

// 下载指定文档
$fileContent = $envelopesApi->getDocument("{account_id}", "{envelope_id}", "1");

// 保存到Laravel的public目录
file_put_contents(public_path('my_document.pdf'), $fileContent);

内容的提问来源于stack exchange,提问作者rnegi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 20:55:28