Skip to content

Commit d8e5bd1

Browse files
authored
Merge pull request #4 from b24io/task#4950
task#4950 add accrual and payment operations in Operations journal
2 parents 389813a + bd37431 commit d8e5bd1

File tree

93 files changed

+4824
-410
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

93 files changed

+4824
-410
lines changed

CHANGELOG.md

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,34 @@
11
# loyalty-php-sdk
2+
## 1.0.0 (8.01.2020)
3+
* add OperationsJournal
4+
* add operation type `AccrualTransaction`
5+
* add operation type `PaymentTransaction`
6+
* add operation type `BlockCard`
7+
* add operation type `CreateCard`
8+
* add operation type `DeleteCard`
9+
* add operation type `UnblockCard`
10+
* add operation type `IncrementPercentage`
11+
* add operation type `DecrementPercentage`
12+
* add operation type `Purchase`
13+
* add operation type `DealMonetaryDiscount` for Bitrix24 deal
14+
* add operation type `DealPercentageDiscount` for Bitrix24 deal
15+
* add field `OperationUuid` in Operation entity
16+
* add field `CardUuid` in Card entity
17+
* add method `filterContactsByEmail` in `\Bitrix24\Contacts\Transport\Admin` transport, return FiltrationResult with two items: CardDTO and ContactDTO
18+
* add method `filterContactsByPhone` in `\Bitrix24\Contacts\Transport\Admin` transport, return FiltrationResult with two items: CardDTO and ContactDTO
19+
* add method `getByCardUuid` in `\Bitrix24\Contacts\Transport\Admin` transport, return ContactResponse with two items: CardDTO and ContactDTO
20+
* add method `getByCardUuid` in `\Bitrix24\Contacts\Transport\User` transport, return ContactResponse with two items: CardDTO and ContactDTO
21+
* add method `getCardByUuid` in `\Cards\Transport\Admin` transport, return CardDTO or throw exception `CardNotFound`
22+
* add method `getCardByUuid` in `\Cards\Transport\User` transport, return CardDTO or throw exception `CardNotFound`
23+
* add method `getOperationsByPeriod` in `\OperationsJournal\Transport\Admin` transport, return `OperationsJournalResponse`
24+
* add method `getOperationsByPeriod` in `\OperationsJournal\Transport\User` transport, return `OperationsJournalResponse`
25+
* add MetricDTO and transport
26+
* change mobile phone data structure in Contact DTO in JSON API response
27+
* change mobile phone in ContactDTO can be nullable
28+
* change `authKey` and `clientKey` in `TokenDTO` string values to `UuidInterface`
29+
* remove `countryRegionCode` argument in methods `add` and `addWithCardNumber` in `\Bitrix24\Contacts\Transport\Admin` transport
30+
* remove setters in CardDTO object
31+
232
## 0.1.3 (6.08.2019)
333
* fix contact formatter error
434

README.md

Lines changed: 187 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,189 @@
11
# loyalty-php-sdk
2-
B24io.Loyalty application PHP-SDK
2+
Loyalty PHP SDK is a tool for work with REST-API Bitrix24 Application [Loyalty Program and bonus cards for Bitrix24 CRM](https://www.bitrix24.ru/apps/?app=b24io.loyalty)
33

4-
## Domain items
4+
* Loyalty app adds bonus card for Bitrix24 client profile in CRM
5+
* Loyalty app support transactions for payment and accrual operations
6+
* store percentage of discount
7+
* operations with cards: create, read, delete, block
8+
9+
## Who uses loyalty PHP SDK
10+
* B2C companies who works with customers and grow they LTV
11+
* HoReCa companies such us fast food or restaurants
12+
13+
## How it works
14+
<p align="center">
15+
<img src="./docs/img/loyalty-php-sdk-base-schema.jpg" alt="Loyalty Program and bonus cards for Bitrix24 CRM" width="1333">
16+
</p>
17+
18+
## Domain entities
19+
In loyalty-php-sdk available domain entities from application with DTO (data transfer objects).
20+
21+
### Cards
22+
Loyalty card object:
23+
* `number` - card number
24+
* `barcode` - card barcode
25+
* `status` - card status enumeration (active, blocked or deleted)
26+
* `user` - card owner user id
27+
* `balance` - card balance with php-money object
28+
* `percentage` - card percentage
29+
* `created` - card date create
30+
* `modified` - card date modified
31+
* `uuid` - card [universally unique identifier](https://en.wikipedia.org/wiki/Universally_unique_identifier)
32+
33+
### Transactions
34+
Transactions - accrual or payment operation with card balance
35+
36+
Transaction object:
37+
38+
* `value` - transaction amount with php-money object
39+
* `operationId` - internal operation id, read only
40+
* `type` - payment or accrual transaction
41+
* `cardNumber` - card number
42+
* `created` - transaction date create
43+
* `reason` - transaction reason with comment
44+
45+
### Turnovers
46+
Turnover object:
47+
48+
* `modified` - last operation date
49+
* `totalPurchasesSum` - total purchases sum for card
50+
* `totalPurchasesCount` - total purchases count for card
51+
52+
### OperationsJournal
53+
Operations journal with card - it's read only log with card state history
54+
55+
Operation objects implements operation interface:
56+
57+
* `Uuid` - operation uuid
58+
* `OperationType` - enumeration of operation types ()
59+
* `CardUuid` - card uuid
60+
* `UserId` - user id
61+
* `Timestamp` - operation timestamp
62+
* `Reason` - operation reason
63+
64+
#### Operation types
65+
* `accrual_transaction` - accrual transaction
66+
* `payment_transaction` - payment transaction
67+
* `create_card` - card create
68+
* `block_card` - block card
69+
* `unblock_card` - unblock card
70+
* `delete_card` - delete card
71+
* `decrement_percent` - decrement percent on card
72+
* `increment_percent` - increment percent on card
73+
* `purchase` - purchase registration
74+
* `b24_deal_monetary_discount_payment_trx` - Bitrix24 deal partial payment with monetary discount
75+
* `b24_deal_percentage_discount_payment_trx` - Bitrix24 deal partial payment with percentage discount
76+
77+
### Metrics
78+
Metrics describe operational parameters loyalty application
79+
80+
Metric object:
81+
* `uuid` - metric uuid
82+
* `name` - metric name
83+
* `description` - metric description
84+
* `code` - metric code
85+
* `type` - metric type enumeration: INTEGER, FLOAT, MONEY, PERCENTAGE
86+
* `created` - metric created date time
87+
88+
### Bitrix24 Contacts
89+
Bitrix24 Loyalty application do not store contacts, app fetch Bitrix24 contacts in realtime with each API-request.
90+
91+
Contact object:
92+
* `contactId` - Bitrix24 contact id
93+
* `name` - name
94+
* `secondName` - second name
95+
* `lastName` - last name
96+
* `birthday` - contact birthday
97+
* `comments` - comments about contact
98+
* `created` - contact date create
99+
* `modified` - contact date modified
100+
* `mobilePhone` - contact mobile phone
101+
* `email` - contact personal email
102+
* `address` - contact address
103+
* `originId` - origin identifier
104+
* `originatorId` - originator identifier
105+
* `utm` - utm labels for contact ads channel tracking
106+
* `sourceDescription` - source description
107+
108+
## Installation
109+
Via Composer
110+
111+
```bash
112+
$ composer require b24io/loyalty-php-sdk
113+
```
114+
115+
### Requirements
116+
Loyalty PHP SDK works with PHP 7.1 or above, need `ext-json` and `ext-curl` support
117+
118+
## Authentication with admin and user roles
119+
SDK can work with two roles:
120+
* `admin` - can work with all cards in his Bitrix24 account and loyalty application instance
121+
* `user` - can work only with his card
122+
123+
Bitrix24 Application Loyalty Program and bonus cards work with many Bitrix24 accounts, each account has a `CLIENT_API_KEY`
124+
If you want work in admin role you must use `ADMIN_API_KEY` to sign queries.
125+
126+
```php
127+
$token = new SDK\Auth\DTO\Token(
128+
SDK\Transport\DTO\Role::initializeByCode('admin'),
129+
Uuid::fromString('CLIENT_API_KEY'),
130+
Uuid::fromString('ADMIN_API_KEY')
131+
);
132+
```
133+
If you want work with client role in JS you must use `CLIENT_API_KEY` and `CARD_UUID` as user API key.
134+
135+
## Basic Usage
136+
```php
137+
use \Monolog\Logger;
138+
use \B24io\Loyalty\SDK;
139+
use Ramsey\Uuid\Uuid;
140+
141+
use GuzzleHttp\HandlerStack;
142+
use GuzzleHttp\Middleware;
143+
use GuzzleHttp\MessageFormatter;
144+
145+
$log = new Logger('loyalty-php-sdk');
146+
$log->pushHandler(new \Monolog\Handler\StreamHandler('loyalty-php-sdk-example.log', Logger::DEBUG));
147+
$guzzleHandlerStack = HandlerStack::create();
148+
$guzzleHandlerStack->push(
149+
Middleware::log(
150+
$log,
151+
new MessageFormatter(MessageFormatter::SHORT)
152+
)
153+
);
154+
$httpClient = new \GuzzleHttp\Client();
155+
156+
$log->info('loyalty.apiClient.start');
157+
$token = new SDK\Auth\DTO\Token(
158+
SDK\Transport\DTO\Role::initializeByCode('admin'),
159+
Uuid::fromString('CLIENT_API_KEY'),
160+
Uuid::fromString('ADMIN_API_KEY')
161+
);
162+
$apiClient = new SDK\ApiClient($apiEndpoint, $token, $httpClient, $log);
163+
$apiClient->setGuzzleHandlerStack($guzzleHandlerStack);
164+
165+
$cardsTransport = SDK\Cards\Transport\Admin\Fabric::getCardTransport($apiClient, $log);
166+
167+
$cardResponse = $cardsTransport->getCardByNumber(22222);
168+
169+
$decimalMoneyFormatter = new \Money\Formatter\DecimalMoneyFormatter(new \Money\Currencies\ISOCurrencies());
170+
var_dump($cardResponse->getCard()->getNumber());
171+
var_dump($cardResponse->getCard()->getStatus()->getCode());
172+
var_dump($decimalMoneyFormatter->format($cardResponse->getCard()->getBalance()));
173+
var_dump($cardResponse->getCard()->getPercentage()->format());
174+
```
175+
## Documentation and examples
176+
More complex examples and use cases you can see in folder [examples](examples)
177+
178+
## Submitting bugs and feature requests
179+
Bugs and feature request are tracked on [GitHub](https://github.com/b24io/loyalty-php-sdk/issues)
180+
181+
## Support
182+
* [Telegram chat](https://t.me/joinchat/PhcdgxWKHu7gOGRmowqCpA) with developers
183+
* [app@b24.io](mailto:app@b24.io)
184+
185+
## Security
186+
If you discover any security related issues, please contact us at [app@b24.io](mailto:app@b24.io)
187+
188+
## License
189+
The MIT License (MIT). Please see [License File](LICENSE) for more information.

composer.json

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,9 @@
3030
"fig/http-message-util": "1.*",
3131
"eloquent/enumeration": "^5.1",
3232
"crell/api-problem": "^3.0",
33-
"giggsey/libphonenumber-for-php": "^8.0"
33+
"giggsey/libphonenumber-for-php": "^8.0",
34+
"ramsey/uuid": "^3.8",
35+
"symfony/http-foundation": "^4.2"
3436
},
3537
"require-dev": {
3638
"phpunit/phpunit": "^7",
52.8 KB
Loading
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
require_once 'vendor/autoload.php';
5+
6+
use \Monolog\Logger;
7+
use \B24io\Loyalty\SDK;
8+
use \B24io\Loyalty\SDK\OperationsJournal\DTO\OperationType;
9+
use Ramsey\Uuid\Uuid;
10+
11+
use GuzzleHttp\HandlerStack;
12+
use GuzzleHttp\Middleware;
13+
use GuzzleHttp\MessageFormatter;
14+
15+
$argv = getopt('', ['clientApiKey::', 'authApiKey::', 'apiEndpoint::', 'cardUuid::']);
16+
$fileName = basename(__FILE__);
17+
18+
$clientApiKey = $argv['clientApiKey'];
19+
if ($clientApiKey === null) {
20+
throw new \InvalidArgumentException(sprintf('error: argument «clientApiKey» not found') . PHP_EOL);
21+
}
22+
$authApiKey = $argv['authApiKey'];
23+
if ($authApiKey === null) {
24+
throw new \InvalidArgumentException(sprintf('error: argument «authApiKey» not found') . PHP_EOL);
25+
}
26+
$apiEndpoint = $argv['apiEndpoint'];
27+
if ($apiEndpoint === null) {
28+
throw new \InvalidArgumentException(sprintf('error: argument «apiEndpoint» not found') . PHP_EOL);
29+
}
30+
$cardUuid = Uuid::fromString($argv['cardUuid']);
31+
32+
33+
// check connection to API
34+
$log = new Logger('loyalty-php-sdk');
35+
$log->pushHandler(new \Monolog\Handler\StreamHandler('loyalty-php-sdk-example.log', Logger::DEBUG));
36+
$guzzleHandlerStack = HandlerStack::create();
37+
$guzzleHandlerStack->push(
38+
Middleware::log(
39+
$log,
40+
new MessageFormatter(MessageFormatter::SHORT)
41+
)
42+
);
43+
$httpClient = new \GuzzleHttp\Client();
44+
45+
$log->info('loyalty.apiClient.start');
46+
$token = new SDK\Auth\DTO\Token(
47+
SDK\Transport\DTO\Role::initializeByCode('admin'),
48+
Uuid::fromString($clientApiKey),
49+
Uuid::fromString($authApiKey)
50+
);
51+
$apiClient = new SDK\ApiClient($apiEndpoint, $token, $httpClient, $log);
52+
$apiClient->setGuzzleHandlerStack($guzzleHandlerStack);
53+
54+
$bitrix24Transport = SDK\Bitrix24\Contacts\Transport\Admin\Fabric::getBitrix24ContactsTransport($apiClient, $log);
55+
56+
try {
57+
$result = $bitrix24Transport->getByCardUuid($cardUuid);
58+
59+
print(sprintf('query result:') . PHP_EOL);
60+
print(sprintf(' - message operation: %s', $result->getMeta()->getMessage()) . PHP_EOL);
61+
print(sprintf(' - role: %s', $result->getMeta()->getRole()->key()) . PHP_EOL);
62+
print(sprintf(' - duration: %s', $result->getMeta()->getDuration()) . PHP_EOL);
63+
64+
print(sprintf('filtration result items:') . PHP_EOL);
65+
$phoneNumberFormatter = \libphonenumber\PhoneNumberUtil::getInstance();
66+
67+
if ($result->getContact() !== null) {
68+
print(sprintf('- contact:') . PHP_EOL);
69+
print(sprintf(' id: %s', $result->getContact()->getContactId()->getId()) . PHP_EOL);
70+
print(sprintf(' email: %s', $result->getContact()->getEmail()) . PHP_EOL);
71+
print(sprintf(
72+
' phone: %s',
73+
$result->getContact()->getMobilePhone() !== null ?
74+
$phoneNumberFormatter->format(
75+
$result->getContact()->getMobilePhone(),
76+
\libphonenumber\PhoneNumberFormat::INTERNATIONAL
77+
) : null
78+
) . PHP_EOL);
79+
}
80+
if ($result->getCard() !== null) {
81+
$decimalMoneyFormatter = new \Money\Formatter\DecimalMoneyFormatter(new \Money\Currencies\ISOCurrencies());
82+
print(sprintf('- card:') . PHP_EOL);
83+
print(sprintf(' number: %s', $result->getCard()->getNumber()) . PHP_EOL);
84+
print(sprintf(' uuid: %s', $result->getCard()->getUuid()->toString()) . PHP_EOL);
85+
print(sprintf(' status: %s', $result->getCard()->getStatus()->getCode()) . PHP_EOL);
86+
print(sprintf(
87+
' balance: %s %s',
88+
$decimalMoneyFormatter->format($result->getCard()->getBalance()),
89+
$result->getCard()->getBalance()->getCurrency()->getCode() . PHP_EOL
90+
));
91+
print(sprintf(' percentage: %s', $result->getCard()->getPercentage()->format()) . PHP_EOL);
92+
}
93+
} catch (SDK\Exceptions\ApiClientException $exception) {
94+
var_dump($exception->getApiProblem()->asArray());
95+
} catch (\Throwable $exception) {
96+
var_dump($exception->getMessage());
97+
}

0 commit comments

Comments
 (0)