如何在Laravel 5.5中借助Intervention Image将S3图片上传至Stripe
嘿,我之前处理过类似的场景,咱们来一步步搞定这个问题!
Stripe的文件上传API其实支持多种格式的输入,不一定非要用fopen()拿到的文件流——既然你手里已经有了Intervention的Image实例,咱们可以把它转换成Stripe能识别的格式,有两种简单的方法:
方法一:保存为临时文件再上传
这种方法比较直观,把Image实例存到系统临时目录,再传给Stripe:
// 假设$image是你从S3获取的Intervention\Image\Image实例 // 创建临时文件 $tempFilePath = tempnam(sys_get_temp_dir(), 'stripe_dl'); // 将Image实例保存到临时文件(这里用JPG格式,你可以根据实际调整) $image->save($tempFilePath, 90, 'jpg'); // 调用Stripe API上传文件 $stripeFile = \Stripe\File::create([ 'purpose' => 'identity_document', // 身份验证必须的purpose参数 'file' => fopen($tempFilePath, 'r'), ]); // 上传完成后记得删除临时文件,避免占用空间 unlink($tempFilePath);
方法二:直接传递二进制内容(更高效)
不需要创建临时文件,直接从Image实例提取二进制内容,用数组形式传给Stripe:
// 从Image实例获取编码后的二进制内容(这里用JPG格式,可调整为png等) $imageBinary = $image->encode('jpg', 90)->getEncoded(); // 调用Stripe API,用数组传递文件信息 $stripeFile = \Stripe\File::create([ 'purpose' => 'identity_document', 'file' => [ 'name' => 'drivers_license.jpg', // 给文件起个名字,Stripe会用到 'contents' => $imageBinary, // 二进制内容 'type' => 'image/jpeg', // 对应图片的MIME类型 ], ]);
注意事项
- 确保图片格式是Stripe支持的:目前Stripe接受JPEG、PNG格式的身份验证文件,别用SVG或者其他不兼容格式。
purpose参数要正确:身份验证对应的purpose是identity_document,如果是其他用途要对应调整(比如business_logo等)。- 如果你的图片是PNG格式,记得把
encode()的参数改成'png',type改成'image/png'。
这样处理后,就能顺利把Intervention的Image实例转换成Stripe需要的格式完成身份验证啦!
内容的提问来源于stack exchange,提问作者fronzee
相关产品推荐
相关产品推荐

