Completed
Push — master ( 087020...368970 )
by
unknown
03:33
created

XsollaClient   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 103
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 63.41%

Importance

Changes 0
Metric Value
wmc 15
lcom 1
cbo 6
dl 0
loc 103
ccs 26
cts 41
cp 0.6341
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A jsonEncode() 0 6 2
A factory() 0 20 1
B __call() 0 30 10
A createCommonPaymentUIToken() 0 7 1
A createPaymentUITokenFromRequest() 0 6 1
1
<?php
2
3
namespace Xsolla\SDK\API;
4
5
use GuzzleHttp\Client;
6
use GuzzleHttp\Collection;
7
use GuzzleHttp\Exception\BadResponseException;
8
use GuzzleHttp\Exception\ClientException;
9
use Xsolla\SDK\API\PaymentUI\TokenRequest;
10
use Xsolla\SDK\Exception\API\XsollaAPIException;
11
use Xsolla\SDK\Version;
12
13
/**
14
 * @method array CreatePaymentUIToken(array $args = []) Create payment UI token. http://developers.xsolla.com/api.html#payment-ui
15
 *
16
 * @method array CreateSubscriptionPlan(array $args = [])       Create a recurrent plan. http://developers.xsolla.com/api.html#create-a-plan
17
 * @method array UpdateSubscriptionPlan(array $args = [])       Update a recurrent plan. http://developers.xsolla.com/api.html#update-a-plan
18
 * @method void  DeleteSubscriptionPlan(array $args = [])       Delete a recurrent plan. http://developers.xsolla.com/api.html#delete-a-plan
19
 * @method void  DisableSubscriptionPlan(array $args = [])      Disable a recurrent plan. http://developers.xsolla.com/api.html#disable-a-plan
20
 * @method void  EnableSubscriptionPlan(array $args = [])       Enable a recurrent plan. http://developers.xsolla.com/api.html#enable-a-plan
21
 * @method array ListSubscriptionPlans(array $args = [])        List all recurrent plans. http://developers.xsolla.com/api.html#list-all-plans
22
 * @method array CreateSubscriptionProduct(array $args = [])    Create a product. http://developers.xsolla.com/api.html#create-a-product
23
 * @method array UpdateSubscriptionProduct(array $args = [])    Update a product. http://developers.xsolla.com/api.html#update-a-product
24
 * @method void  DeleteSubscriptionProduct(array $args = [])    Delete a product. http://developers.xsolla.com/api.html#delete-a-product
25
 * @method array ListSubscriptionProducts(array $args = [])     List all recurrent products. http://developers.xsolla.com/api.html#list-all-products
26
 * @method array UpdateSubscription(array $args = [])           Updates a subscription by either changing its status ‘active’, ‘canceled’, or ‘non_renewing’ or postponing the next billing date. http://developers.xsolla.com/api.html#update-subscription
27
 * @method array ListSubscriptions(array $args = [])            List all recurrent subscriptions. http://developers.xsolla.com/api.html#list-all-subscriptions
28
 * @method array ListSubscriptionPayments(array $args = [])     List all recurrent payments. http://developers.xsolla.com/api.html#list-all-payments
29
 * @method array ListUserSubscriptionPayments(array $args = []) List all recurrent payments by user. http://developers.xsolla.com/api.html#list-all-payments-by-user
30
 * @method array ListSubscriptionCurrencies(array $args = [])   List all recurrent currencies. http://developers.xsolla.com/api.html#list-all-currencies
31
 *
32
 * @method array ListUserAttributes(array $args = [])  Get list of user attributes. http://developers.xsolla.com/api.html#list-all-user-attributes
33
 * @method array GetUserAttribute(array $args = [])    Show a user attribute. http://developers.xsolla.com/api.html#get-user-attribute
34
 * @method array CreateUserAttribute(array $args = []) Create user attribute. http://developers.xsolla.com/api.html#create-user-attribute
35
 * @method void  UpdateUserAttribute(array $args = []) Update user attribute. http://developers.xsolla.com/api.html#update-user-attribute
36
 * @method void  DeleteUserAttribute(array $args = []) Delete a user attribute. http://developers.xsolla.com/api.html#delete-user-attribute
37
 *
38
 * @method array CreateVirtualItem(array $args = [])             Create a virtual item. http://developers.xsolla.com/api.html#create-an-item
39
 * @method array GetVirtualItem(array $args = [])                Get a virtual item. http://developers.xsolla.com/api.html#get-an-item
40
 * @method void  UpdateVirtualItem(array $args = [])             Update a virtual item. http://developers.xsolla.com/api.html#update-an-item
41
 * @method void  DeleteVirtualItem(array $args = [])             Delete a virtual item. http://developers.xsolla.com/api.html#delete-an-item
42
 * @method array ListVirtualItems(array $args = [])              List a virtual items. http://developers.xsolla.com/api.html#list-all-items
43
 * @method array CreateVirtualItemsGroup(array $args = [])       Create a virtual items group. http://developers.xsolla.com/api.html#create-a-group
44
 * @method array GetVirtualItemsGroup(array $args = [])          Get a virtual items group. http://developers.xsolla.com/api.html#get-a-group
45
 * @method void  UpdateVirtualItemsGroup(array $args = [])       Update a virtual items group. http://developers.xsolla.com/api.html#update-a-group
46
 * @method void  DeleteVirtualItemsGroup(array $args = [])       Delete a virtual items group. http://developers.xsolla.com/api.html#delete-a-group
47
 * @method array ListVirtualItemsGroups(array $args = [])        List all virtual items groups. http://developers.xsolla.com/api.html#list-all-groups
48
 * @method void  UpdateVirtualItemOrderInGroup(array $args = []) Update items order in group. http://developers.xsolla.com/api.html#change-an-items-order
49
 *
50
 * @method array GetProjectVirtualCurrencySettings(array $args = [])    Get project virtual currency settings. http://developers.xsolla.com/api.html#list-the-currency-package
51
 * @method void  UpdateProjectVirtualCurrencySettings(array $args = []) Update project virtual currency settings. http://developers.xsolla.com/api.html#update-the-currency-package
52
 *
53
 * @method void  CreateWalletUser(array $args = [])                Create a new user. http://developers.xsolla.com/api.html#create-a-new-user
54
 * @method array GetWalletUser(array $args = [])                   Retrieve a user data. http://developers.xsolla.com/api.html#get-a-user
55
 * @method void  UpdateWalletUser(array $args = [])                Update user's information. http://developers.xsolla.com/api.html#update-an-user
56
 * @method array ListWalletUsers(array $args = [])                 List all users. http://developers.xsolla.com/api.html#list-all-users
57
 * @method array ListWalletUserOperations(array $args = [])        List all operations. http://developers.xsolla.com/api.html#list-all-operations
58
 * @method array RechargeWalletUserBalance(array $args = [])       Change a balance. http://developers.xsolla.com/api.html#change-a-balance
59
 * @method array ListWalletUserVirtualItems(array $args = [])      Get user's virtual items. http://developers.xsolla.com/api.html#list-all-virtual-items
60
 * @method void  AddVirtualItemToWalletUser(array $args = [])      Add the virtual items to the user's account. http://developers.xsolla.com/api.html#add-items-to-the-user
61
 * @method void  DeleteVirtualItemFromWalletUser(array $args = []) Delete the virtual items from the user's account. http://developers.xsolla.com/api.html#delete-items-from-the-user
62
 *
63
 * @method void  CreateCoupon(array $args = []) Create coupon for a campaign by given code
64
 * @method array GetCoupon(array $args = [])    Get information about coupon by code. http://developers.xsolla.com/api.html#get-a-coupon
65
 * @method array RedeemCoupon(array $args = []) Redeem coupon by code. http://developers.xsolla.com/api.html#redeem-a-coupon
66
 *
67
 * @method array CreatePromotion(array $args = [])            Create a new promotion. http://developers.xsolla.com/api.html#create-a-new-promotion
68
 * @method array GetPromotion(array $args = [])               Get a promotion. http://developers.xsolla.com/api.html#get-the-promotion
69
 * @method void  UpdatePromotion(array $args = [])            Update a promotion. If the promotion is read-only (read_only = true), you are not allowed to change "project_id" parameter. http://developers.xsolla.com/api.html#update-the-promotion
70
 * @method array ReviewPromotion(array $args = [])            Check the promotion, if it is ready for activation. This method returns the list of errors (if they exist). http://developers.xsolla.com/api.html#review-the-promotion
71
 * @method void  TogglePromotion(array $args = [])            Toggle the promotion. Change the status of promotion from enabled to disabled and vice versa. http://developers.xsolla.com/api.html#toggle-the-promotion
72
 * @method void  DeletePromotion(array $args = [])            Delete a promotion. Only disabled promotion is allowed to delete (enabled = false). http://developers.xsolla.com/api.html#delete-the-promotion
73
 * @method array ListPromotions(array $args = [])             List all promotions. http://developers.xsolla.com/api.html#list-all-promotions
74
 * @method array GetPromotionSubject(array $args = [])        Get the subject of the promotion. http://developers.xsolla.com/api.html#get-the-subject
75
 * @method void  SetPromotionSubject(array $args = [])        Set the subject of the promotion. If the promotion is read-only (read_only = true), you are not allowed to update the subject. The subject can take the following values: "purchase", or "items", or "packages". http://developers.xsolla.com/api.html#set-the-subject
76
 * @method array GetPromotionPaymentSystems(array $args = []) Get the payment systems of the promotion. If the payment systems list is empty, the promotion will be valid for all payment systems. http://developers.xsolla.com/api.html#get-the-payment-systems
77
 * @method void  SetPromotionPaymentSystems(array $args = []) Set the payment systems of the promotion. If the payment systems list is empty, the promotion will be applied for all payment systems. If the promotion is read-only (read_only = true), you are not allowed to call this command. http://developers.xsolla.com/api.html#set-the-payment-systems
78
 * @method array GetPromotionPeriods(array $args = [])        Get the periods of the promotion. http://developers.xsolla.com/api.html#get-the-periods
79
 * @method void  SetPromotionPeriods(array $args = [])        Set the periods of the promotion. If the promotion is read-only (read_only = true), you are not allowed to edit existing periods, add new periods only. http://developers.xsolla.com/api.html#set-the-periods
80
 * @method array GetPromotionRewards(array $args = [])        Get the rewards of the promotion. http://developers.xsolla.com/api.html#get-the-rewards
81
 * @method void  SetPromotionRewards(array $args = [])        Set the rewards to the promotion. If the promotion is read-only (read_only = true), you are not allowed to update the rewards. http://developers.xsolla.com/api.html#set-the-rewards
82
 * @method array ListCouponPromotions(array $args = [])       Get coupon promotions
83
 * @method array CreateCouponPromotion(array $args = [])      Create coupon promotion
84
 * @method void  UpdatePromotionCampaigns(array $args = [])   Update the promotion campaigns
85
 *
86
 * @method array ListEvents(array $args = []) List all events from Xsolla Event System. http://developers.xsolla.com/api.html#list-all-events
87
 *
88
 * @method array SearchPaymentsRegistry(array $args = []) Get a transaction list based on specific search parameters. JSON, CSV or XML will be returned in response from the API. http://developers.xsolla.com/api.html#search-all-transactions
89
 * @method array ListPaymentsRegistry(array $args = [])   Get information about all transactions for specified data range/transfer/report in different data formats. JSON, CSV or XML will be returned in response from the API. http://developers.xsolla.com/api.html#list-all-transactions
90
 * @method array ListTransfersRegistry(array $args = [])  List all transfers. http://developers.xsolla.com/api.html#list-all-transfers
91
 * @method array ListReportsRegistry(array $args = [])    Get a list of finance reports for specified data range. http://developers.xsolla.com/api.html#list-all-reports
92
 * @method void  CreateRefundRequest(array $args = [])    Send a refund request. Money will be returned to user. http://developers.xsolla.com/api.html#send-a-refund-request
93
 *
94
 * @method array ListSupportTickets(array $args = [])        List all tickets. http://developers.xsolla.com/api.html#list-all-tickets
95
 * @method array ListSupportTicketComments(array $args = []) List all comments. http://developers.xsolla.com/api.html#list-all-comments
96
 *
97
 * @method array CreateGameDeliveryEntity(array $args = [])     Create game delivery entity http://developers.xsolla.com/api.html#create-game-delivery-entity
98
 * @method array GetGameDeliveryEntity(array $args = [])        Get a game delivery entity http://developers.xsolla.com/api.html#get-a-game-delivery-entity
99
 * @method void  UpdateGameDeliveryEntity(array $args = [])     Update a game delivery entity http://developers.xsolla.com/api.html#update-a-game-delivery-entity
100
 * @method array ListGameDeliveryEntities(array $args = [])     List all game delivery entities http://developers.xsolla.com/api.html#list-all-game-delivery-entities
101
 * @method array ListGameDeliveryDrmPlatforms(array $args = []) List available DRM platforms http://developers.xsolla.com/api.html#list-available-drm-platforms
102
 *
103
 * @method array GetStorefrontVirtualCurrency(array $args = []) Get virtual currency packages http://developers.xsolla.com/api.html#list-virtual-currency-packages
104
 * @method array GetStorefrontVirtualGroups(array $args = [])   Get virtual items groups http://developers.xsolla.com/api.html#list-item-groups
105
 * @method array GetStorefrontVirtualItems(array $args = [])    Get virtual items http://developers.xsolla.com/api.html#list-virtual-items
106
 * @method array GetStorefrontSubscriptions(array $args = [])   Get available subscriptions http://developers.xsolla.com/api.html#list-subscription-plans
107
 * @method array GetStorefrontBonus(array $args = [])           Get the information about active promotion http://developers.xsolla.com/api.html#list-promotions
108
 *
109
 * @method array CreateProject(array $args = []) Create a new project http://developers.xsolla.com/api.html#create-a-new-project
110
 * @method array GetProject(array $args = [])    Get a project http://developers.xsolla.com/api.html#get-a-project
111
 * @method void  UpdateProject(array $args = []) Update a project http://developers.xsolla.com/api.html#update-a-project
112
 * @method array ListProjects(array $args = [])  List all projects http://developers.xsolla.com/api.html#list-all-projects
113
 *
114
 * @method array ListPaymentAccounts(array $args = [])  List of the saved payment accounts http://developers.xsolla.com/api.html#list-saved-payment-accounts
115
 * @method array ChargePaymentAccount(array $args = []) Charge using the saved payment account http://developers.xsolla.com/api.html#charge-using-saved-payment-account
116
 * @method array DeletePaymentAccount(array $args = []) Delete the saved payment account http://developers.xsolla.com/api.html#delete-a-saved-payment-account
117
 */
118
class XsollaClient extends Client
119
{
120
    private static $merchantId;
121
    private static $serviceDescription;
122
123
    /**
124
     * @internal
125
     * @param  mixed  $value
126
     * @return string
127
     */
128 3
    public static function jsonEncode($value)
129
    {
130 3
        $flags = defined('JSON_PRETTY_PRINT') ? JSON_PRETTY_PRINT : 0;
131
132 3
        return json_encode($value, $flags);
133
    }
134
135
    /**
136
     * @param  array  $config
137
     * @return static
138
     */
139
    public static function factory($config = [])
140
    {
141
        $required = ['merchant_id', 'api_key'];
142
        $default = ['ssl.certificate_authority' => 'system'];
143
144
        $config = Collection::fromConfig($config, $default, $required)->toArray();
145
146
        $client = new static($config);
147
        $client->setDefaultOption('auth', [$config['merchant_id'], $config['api_key'], 'Basic']);
148
        $client->setDefaultOption('headers', [
149
            'Accept' => 'application/json',
150
            'Content-Type' => 'application/json',
151
            'User-Agent' => Version::getVersion(),
152
        ]);
153
154
        self::$serviceDescription = require __DIR__.'/Resources/api.php';
155
        self::$merchantId = (int) $config['merchant_id'];
156
157
        return $client;
158
    }
159
160
    /**
161
     * @param $name
162
     * @param $arguments
163
     * @return mixed
164
     */
165 91
    public function __call($name, $arguments)
166
    {
167 91
        $params = count($arguments) > 0 ? $arguments[0] : [];
168
169 91
        $operation = self::$serviceDescription['operations'][$name];
170 91
        $uri = self::$serviceDescription['baseUrl'].$operation['uri'];
171
172 91
        foreach ($operation['parameters'] as $parameterName => $parameterValue) {
173 91
            if ('uri' === $parameterValue['location'] && null !== strpos($uri, sprintf('{%s}', $parameterName))) {
174 91
                $replacementValue = 'merchant_id' === $parameterName ? self::$merchantId : $params[$parameterName];
175
176 91
                $uri = str_replace(sprintf('{%s}', $parameterName), $replacementValue, $uri);
177 60
            } elseif ('query' === $parameterValue['location']) {
178 91
                $params['request'][$parameterName] = $params[$parameterName] ?? null;
179
            }
180
        }
181
182 91
        $requestParams = 'GET' === $operation['httpMethod'] ? ['query' => $params['request'] ?? []] : ['json' => $params['request'] ?? []];
183
184
        try {
185 91
            $request = $this->createRequest($operation['httpMethod'], $uri, $requestParams);
186 91
            $response = $this->send($request);
187 1
        } catch (BadResponseException | ClientException $exception) {
188 1
            throw XsollaAPIException::fromBadResponse($exception);
189
        } catch (\Exception $exception) {
190
            throw new XsollaAPIException('XsollaClient Exception: '.$exception->getMessage().' Please check troubleshooting section in README.md https://github.com/xsolla/xsolla-sdk-php#troubleshooting', 0, $exception);
191
        }
192
193 90
        return json_decode($response->getBody(), true);
194
    }
195
196
    /**
197
     * @param  int    $projectId
198
     * @param  string $userId
199
     * @param  bool   $sandboxMode
200
     * @return string
201
     */
202 1
    public function createCommonPaymentUIToken($projectId, $userId, $sandboxMode = false)
203
    {
204 1
        $tokenRequest = new TokenRequest($projectId, $userId);
205 1
        $tokenRequest->setSandboxMode($sandboxMode);
206
207 1
        return $this->createPaymentUITokenFromRequest($tokenRequest);
208
    }
209
210
    /**
211
     * @param  TokenRequest $tokenRequest
212
     * @return string
213
     */
214 2
    public function createPaymentUITokenFromRequest(TokenRequest $tokenRequest)
215
    {
216 2
        $parsedResponse = $this->CreatePaymentUIToken(['request' => $tokenRequest->toArray()]);
217
218 2
        return $parsedResponse['token'];
219
    }
220
}
221