-
Notifications
You must be signed in to change notification settings - Fork 2
/
Api.php
117 lines (104 loc) · 2.9 KB
/
Api.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
<?php
namespace Acms\Plugins\Zoho;
use Exception;
use ZCRMRestClient;
use ZohoOAuth;
use Acms\Services\Facades\Config;
use Acms\Services\Facades\Storage;
use Field;
class Api
{
/**
* @var string
*/
private const PERSISTENCE_FILE_NAME = 'zcrm_oauthtokens.txt';
/**
* @var \ZohoOAuthClient
*/
public $client;
/**
* Api constructor.
*/
public function __construct()
{
ZCRMRestClient::initialize();
$this->client = ZohoOAuth::getClientInstance();
}
/**
* 認証
* @param string $grantToken
*/
public function authorize(string $grantToken)
{
if (!$this->tokenPersistenceFileExists()) {
$this->createTokenPersistenceFile();
}
$tokens = $this->client->generateAccessToken($grantToken);
$userEmailId = $tokens->getUserEmailId();
$this->saveUserEmailId($userEmailId);
}
/**
* 認証解除
*/
public function deauthorize()
{
if (!$this->tokenPersistenceFileExists()) {
return;
}
$userEmailId = ZCRMRestClient::getCurrentUserEmailID();
ZohoOAuth::getPersistenceHandlerInstance()->deleteOAuthTokens($userEmailId);
$this->saveUserEmailId('');
}
/**
* アクセストークン取得
* @return string|null
*/
public function getAccessToken(): ?string
{
if (!$this->tokenPersistenceFileExists()) {
return null;
}
$userEmailId = ZCRMRestClient::getCurrentUserEmailID();
try {
$accessToken = $this->client->getAccessToken($userEmailId);
} catch (Exception $e) {
$accessToken = null;
}
return $accessToken;
}
/**
* OAuth認証ユーザーのメールアドレスを保存する
* @param string $userEmailId
*/
protected function saveUserEmailId(string $userEmailId = '')
{
$config = new Field();
$config->set('zoho_user_identifier', $userEmailId);
Config::saveConfig($config, BID);
}
/**
* 認証情報保存用ファイルが存在するかどうか
* @return bool
*/
public function tokenPersistenceFileExists(): bool
{
$persistencePath = ZohoOAuth::getConfigValue("token_persistence_path");
if (empty($persistencePath)) {
return false;
}
$persistenceFilePath = $persistencePath . self::PERSISTENCE_FILE_NAME;
return Storage::exists($persistenceFilePath);
}
/**
* 認証情報保存用ファイルを作成する
*/
public function createTokenPersistenceFile()
{
$persistencePath = ZohoOAuth::getConfigValue("token_persistence_path");
if (empty($persistencePath)) {
return;
}
$persistenceFilePath = $persistencePath . self::PERSISTENCE_FILE_NAME;
Storage::put($persistenceFilePath, '');
}
}