Laravel集成Google DocAI遇Expect String错误:字符串变量校验失败
问题分析与解决方案
错误核心原因:ProcessRequest::setName方法被传入了ProcessRequest对象而非预期的字符串,触发Google Protobuf的类型校验异常。以下是针对性解决步骤:
1. 拆分链式调用排查问题
将构建ProcessRequest的链式调用拆分为独立语句,避免潜在的方法返回值异常:
// 替换原链式调用代码 $processRequest = new ProcessRequest(); $processRequest->setGcsDocument($gcsDocument); $processRequest->setName('projects/projectid/locations/us/processors/id8');
2. 检查依赖版本兼容性
Google Cloud DocumentAI客户端库与protobuf版本需严格匹配,执行以下命令查看当前版本:
composer show google/protobuf google/cloud-document-ai
确保google/protobuf版本不低于v3.21.0(对应google/cloud-document-ai v1.x系列),版本过低则执行更新:
composer update google/protobuf google/cloud-document-ai
3. 改用数组参数调用API
绕过对象setter方法,直接传递数组参数给processDocument,避免对象赋值的潜在问题:
$operationResponse = $documentAiClient->processDocument([ 'gcs_document' => $gcsDocument, 'name' => 'projects/projectid/locations/us/processors/id8' ]);
4. 替换为官方推荐的Credentials类
使用Google Cloud PHP客户端库官方推荐的Credentials类,避免底层权限类的兼容性问题:
// 替换原use语句 use Google\Cloud\Core\Credentials\ServiceAccountCredentials; // 修正Laravel环境下的密钥文件路径 $keyFilePath = storage_path('app/credentials/sunlsds.json'); $credentials = new ServiceAccountCredentials( 'https://www.googleapis.com/auth/cloud-platform', $keyFilePath );
5. 清除缓存
清除Laravel和Composer的自动加载缓存,确保类加载正确:
php artisan cache:clear php artisan config:clear composer dump-autoload
内容的提问来源于stack exchange,提问作者Andreiasi Marian
相关产品推荐
相关产品推荐

