OAuth2Client::advertiserGet()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 34
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 16
c 0
b 0
f 0
dl 0
loc 34
rs 9.7333
cc 2
nc 2
nop 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Promopult\TikTokMarketingApi;
6
7
use Promopult\TikTokMarketingApi\Exception\MalformedResponse;
8
use Psr\Http\Client\ClientExceptionInterface;
9
use Psr\Http\Client\ClientInterface;
10
11
/**
12
 * @psalm-suppress UnusedClass
13
 */
14
final class OAuth2Client
15
{
16
    use RequestSenderTrait;
17
18
    private ClientInterface $httpClient;
19
20
    /**
21
     * OAuth2Client constructor.
22
     *
23
     * @param ClientInterface $httpClient
24
     */
25
    public function __construct(
26
        ClientInterface $httpClient
27
    ) {
28
        $this->httpClient = $httpClient;
29
    }
30
31
    /**
32
     * Getting a list of advertiser accounts.
33
     *
34
     * @param string $accessToken   Authorized Access Token
35
     * @param string $appId         The App id applied by the developer
36
     * @param string $secret        The private key of the developer's application
37
     * @param string $apiBaseUrl
38
     *
39
     * @return array
40
     *
41
     * @throws ClientExceptionInterface
42
     *
43
     * @see https://ads.tiktok.com/marketing_api/docs?id=100579
44
     */
45
    public function advertiserGet(
46
        string $accessToken,
47
        string $appId,
48
        string $secret,
49
        string $apiBaseUrl = CredentialsInterface::API_BASE_URL
50
    ): array {
51
        $query = http_build_query([
52
            'access_token' => $accessToken,
53
            'app_id' => $appId,
54
            'secret' => $secret
55
        ]);
56
57
        $request = new \GuzzleHttp\Psr7\Request(
58
            'GET',
59
            $apiBaseUrl . '/open_api/v1.3/oauth2/advertiser/get/?' . $query,
60
            [
61
                'Accept' => 'application/json'
62
            ]
63
        );
64
65
        $response = $this->sendRequest($request);
66
67
        /** @var array $parsedBody */
68
        $parsedBody = json_decode(
69
            $response->getBody()->__toString(),
70
            true,
71
            JSON_THROW_ON_ERROR
72
        );
73
74
        if (empty($parsedBody)) {
75
            throw new MalformedResponse($request, $response);
76
        }
77
78
        return $parsedBody;
79
    }
80
81
    /**
82
     * Get Long-term Access Token
83
     *
84
     * @param string $appId
85
     * @param string $authCode
86
     * @param string $secret
87
     * @param string $apiBaseUrl
88
     *
89
     * @return array
90
     *
91
     * @throws ClientExceptionInterface
92
     */
93
    public function getAccessToken(
94
        string $appId,
95
        string $authCode,
96
        string $secret,
97
        string $apiBaseUrl = CredentialsInterface::API_BASE_URL
98
    ): array {
99
        $request = new \GuzzleHttp\Psr7\Request(
100
            'POST',
101
            $apiBaseUrl . '/open_api/v1.3/oauth2/access_token/',
102
            [
103
                'Content-Type' => 'application/json'
104
            ],
105
            json_encode([
106
                'app_id' => $appId,
107
                'auth_code' => $authCode,
108
                'secret' => $secret
109
            ], JSON_THROW_ON_ERROR)
110
        );
111
112
        $response = $this->sendRequest($request);
113
114
        /** @var array $accessToken */
115
        $accessToken = json_decode($response->getBody()->__toString(), true, JSON_THROW_ON_ERROR);
116
117
        if (empty($accessToken)) {
118
            throw new MalformedResponse($request, $response);
119
        }
120
121
        return $accessToken;
122
    }
123
124
    /**
125
     * Creates Authorization URL
126
     *
127
     * @param string $appId         The application ID.
128
     * @param string $redirectUri   The callback address, which is set and defined by you.
129
     * @param int[] $scope          The scope of permissions. See https://ads.tiktok.com/marketing_api/docs?id=100648
130
     * @param string $state         A user-defined parameter which can be used to transfer user-defined information,
131
     *                              and is returned with the authorization code. Common usage includes, using the
132
     *                              advertiser account to distinguish the advertiser corresponding to the authorization
133
     *                              code during callback. Other usages can be set as you wish.
134
     * @param string $apiBaseUrl    API base URL, ex. https://ads.tiktok.com
135
     *
136
     * @return string
137
     *
138
     * @see https://ads.tiktok.com/marketing_api/docs?id=100648
139
     */
140
    public static function createAuthorizationUrl(
141
        string $appId,
142
        string $redirectUri,
143
        string $state,
144
        ?array $scope = null,
145
        string $apiBaseUrl = CredentialsInterface::API_BASE_URL
146
    ): string {
147
        $queryParams = [
148
            'app_id' => $appId,
149
            'state' => $state,
150
            'redirect_uri' => $redirectUri,
151
        ];
152
153
        if (
154
            $scope !== null
155
            && count($scope) > 0
156
        ) {
157
            $queryParams['scope'] = '[' . implode(',', $scope) . ']';
158
        }
159
160
        return $apiBaseUrl . '/marketing_api/auth?' . http_build_query($queryParams);
161
    }
162
}
163