laravel使用zoho phpsdk将文件上传到crm系统记录的文件上传(file upload)字段上

这篇博客介绍了如何针对Zoho CRM的SDK进行扩展,以支持文件的上传和管理。作者创建了FilesAPIHandler类,用于处理文件的上传、预览和下载操作,并提供了具体的代码示例。在授权认证时,特别强调了添加特定的scope权限。此外,还展示了如何将上传的文件关联到CRM模块的记录上,以及处理已有文件的更新和删除操作。
摘要由CSDN通过智能技术生成

背景:因为zoho提供的sdk没有此功能,为了满足业务需求,对sdk进行扩展

  1. oauth授权认证时记得在scope中加上“ZohoCRM.Files.READ,ZohoCRM.Files.CREATE”两个作用域
// 授权认证配置
$oauth_params = [
	'scope' => 'ZohoCRM.Files.READ,ZohoCRM.Files.CREATE,ZohoCRM.modules.ALL,ZohoCRM.settings.layouts.READ',
	'client_id' => 'client_id',
	'response_type' => 'code',
	'access_type' => 'offline',
	'redirect_uri' => 'redirect_uri',
];
  1. 新建APIHandler类(FilesAPIHandler)

FilesAPIHandler.php

<?php

namespace App\ZCRMSDK\crm\api\handler;

use Illuminate\Http\Response;
use Illuminate\Http\UploadedFile;
use App\ZCRMSDK\crm\crud\ZCRMFile;
use App\ZCRMSDK\crm\api\APIRequest;
use App\ZCRMSDK\crm\utility\APIConstants;
use App\ZCRMSDK\crm\exception\ZCRMException;
use App\ZCRMSDK\crm\api\response\APIResponse;
use Illuminate\Contracts\Foundation\Application;
use App\ZCRMSDK\crm\api\response\FileAPIResponse;
use Illuminate\Contracts\Routing\ResponseFactory;
use App\ZCRMSDK\oauth\exception\ZohoOAuthException;
use App\ZCRMSDK\crm\setup\restclient\ZCRMRestClient;

class FilesAPIHandler extends APIHandler
{
	/**
     * URL 路径
     *
     * @var null|string
     */
    protected $urlPath = 'files';

    /**
     * 获取实体类
     * 
     * @return FilesAPIHandler
     *
     * @throws ZohoOAuthException
     */
    public static function getInstance(): FilesAPIHandler
    {
        ZCRMRestClient::initialize([
            'client_id' => env('ZOHO_API_CLIENT_ID'),
            'client_secret' => env('ZOHO_API_CLIENT_SECRET'),
            'redirect_uri' => route('zoho.oauth'),
            'accounts_url' => 'https://accounts.zoho.com.cn',
            'apiVersion' => 'v2',
            'apiBaseUrl' => 'www.zohoapis.com.cn',
            'currentUserEmail' => 'xxx@email.com',

            'db_port' => env('DB_PORT'),
            'db_name' => env('DB_DATABASE'),
            'db_username' => env('DB_USERNAME'),
            'db_password' => env('DB_PASSWORD'),
            'host_address' => env('DB_HOST'),
        ]);

        return new FilesAPIHandler();
    }

    /**
     * 上传文件
     * 
     * @param UploadedFile $file
     * @param string|null $filename
     * 
     * @return APIResponse
     * @throws ZCRMException
     * @throws ZohoOAuthException
     */
    public function upload(UploadedFile $file, ?string $filename = null): APIResponse
    {
        $this->requestMethod = APIConstants::REQUEST_METHOD_POST;

        $apiRequest = APIRequest::getInstance($this);
        $responseInstance = $apiRequest->uploadFileByGuzzleHttp($file, $filename);

        $responseJson = $responseInstance->getResponseJSON();
        $detailsJSON = $responseJson['data'][0]['details'] ?? [];

        $responseInstance
        	->setData(ZCRMFile::getInstance($detailsJSON['id'] ?? null, $responseJson['name'] ?? null));

        return $responseInstance;
    }

    /**
     * 获取文件内容
     *
     * @param string $file_id
     *
     * @return FileAPIResponse
     *
     * @throws ZCRMException
     * @throws ZohoOAuthException
     */
    private function getFileResponse(string $file_id): FileAPIResponse
    {
        $this->urlPath = $this->urlPath . '?id=' . $file_id;
        $this->requestMethod = APIConstants::REQUEST_METHOD_GET;

        $apiRequest = APIRequest::getInstance($this);

        return $apiRequest->downloadFile();
    }

    /**
     * 预览文件
     *
     * @param string $file_id
     *
     * @return Application|ResponseFactory|Response
     *
     * @throws ZCRMException
     * @throws ZohoOAuthException
     */
    public function preview(string $file_id)
    {
        $response = $this->getFileResponse($file_id);

        $headers = $response->getResponseHeaders();

        $content_type = $headers['content-type'] ?? $headers['Content-Type'] ?? 'application/octet-stream';
        $content_type = trim($content_type);

        return response($response->getResponse())
            ->header('content-type', $content_type);
    }

    /**
     * 下载文件
     *
     * @param string $file_id
     *
     * @return Application|ResponseFactory|Response
     *
     * @throws ZCRMException
     * @throws ZohoOAuthException
     */
    public function download(string $file_id)
    {
        $response = $this->getFileResponse($file_id);

        return response($response->getResponse())
            ->withHeaders($response->getResponseHeaders());
    }
}

  1. 调用
$file = $request->file('file');
if (is_null($file) || !$file->isValid()) {
	return self::error('请上传文件');
}

$upload = FilesAPIHandler::getInstance()
	->upload($file, '自定义上传文件名称.' . $file->getClientOriginalExtension());

$file_id = $upload->getData()->getId();

$record = ZCRMRecord::getInstance('模块名称', '记录ID');
$record->setFieldValue('字段名称', [$file_id]);

// 注意,上面的方法将会覆盖字段上的所有记录,如果当前字段上有值且想要删除该值对应的文件,可以这样:

$old_record = ZCRMRestClient::getInstance()
	->getModuleInstance('模块名称')
	->getRecord('记录ID')
	->getData(); // 查询旧的记录

$attachments = [$file_id];
if (!empty($old_record->getFieldValue('字段名称'))) {
	foreach ($old_record->getFieldValue('字段名称') as $v) {
		$attachments[] = [
			'_delete' => null, // 指定该字段表示删除
	        'attachment_id' => $v['attachment_Id'], // 旧的附件ID
		];
	}
}

$record->setFieldValue('字段名称', $attachments);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值