-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample.php
More file actions
582 lines (509 loc) · 17.3 KB
/
example.php
File metadata and controls
582 lines (509 loc) · 17.3 KB
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
<?php
require_once __DIR__ . '/vendor/autoload.php';
use Tapsilat\TapsilatAPI;
use Tapsilat\APIException;
use Tapsilat\Models\BuyerDTO;
use Tapsilat\Models\OrderCreateRequest;
use Tapsilat\Models\BasketItemDTO;
use Tapsilat\Models\BasketItemPayerDTO;
use Tapsilat\Models\BillingAddressDTO;
use Tapsilat\Models\CheckoutDesignDTO;
use Tapsilat\Models\ShippingAddressDTO;
use Tapsilat\Models\SubscriptionCreateRequest;
use Tapsilat\Models\SubscriptionGetRequest;
use Tapsilat\Models\SubscriptionCancelRequest;
use Tapsilat\Models\SubscriptionRedirectRequest;
use Tapsilat\Models\SubscriptionBillingDTO;
use Tapsilat\Models\SubscriptionUserDTO;
use Tapsilat\Models\OrderConsentDTO;
use Tapsilat\Validators;
/**
* Load environment variables from .env file
*/
function loadEnv($path = __DIR__ . '/.env')
{
if (!file_exists($path)) {
return;
}
$lines = file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($lines as $line) {
if (strpos(trim($line), '#') === 0) {
continue;
}
list($name, $value) = explode('=', $line, 2);
$name = trim($name);
$value = trim($value);
if (!array_key_exists($name, $_ENV)) {
$_ENV[$name] = $value;
}
}
}
/**
* Get API client from environment variable
*/
function getApiClient()
{
// Load .env file
loadEnv();
$apiKey = $_ENV['API_KEY'] ?? $_ENV['TAPSILAT_API_KEY'] ?? '';
if (empty($apiKey)) {
echo "Error: API_KEY or TAPSILAT_API_KEY is not set in .env file.\n";
return null;
}
echo "Using API Key from .env file...\n";
return new TapsilatAPI($apiKey);
}
/**
* Process order creation with error handling and logging
*/
function processOrderCreation($client, $orderPayload, $scenarioName)
{
echo str_repeat("#", 16) . "\n";
echo $scenarioName . "\n";
if (!$client) {
echo "Client is not initialized.\n";
return;
}
$sanitizedName = strtolower(str_replace([' ', ':'], '_', $scenarioName));
$resultsDir = __DIR__ . '/test_results';
if (!is_dir($resultsDir)) {
mkdir($resultsDir, 0777, true);
}
// Capture Input (Request Payload)
$inputData = $orderPayload->toArray();
file_put_contents("$resultsDir/{$sanitizedName}_input.json", json_encode($inputData, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
try {
$response = $client->createOrder($orderPayload);
echo "Order created successfully!\n";
echo "Reference ID: " . $response->getReferenceId() . "\n";
// Capture Output (Response)
file_put_contents("$resultsDir/{$sanitizedName}_output.json", json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
// Get checkout URL using reference_id (like Python version)
$checkoutUrl = $client->getCheckoutUrl($response->getReferenceId());
echo "Checkout URL: " . $checkoutUrl . "\n";
} catch (APIException $e) {
echo "API Error: " . $e->error . "\n";
file_put_contents("$resultsDir/{$sanitizedName}_output.json", json_encode(['error' => $e->error, 'code' => $e->code, 'statusCode' => $e->statusCode], JSON_PRETTY_PRINT));
} catch (Exception $e) {
echo "Unexpected error: " . $e->getMessage() . "\n";
file_put_contents("$resultsDir/{$sanitizedName}_output.json", json_encode(['error' => $e->getMessage()], JSON_PRETTY_PRINT));
}
}
/**
* Scenario 1: Basic Order
*/
function runScenario1BasicOrder($client)
{
$buyer = new BuyerDTO("John", "Doe", null, null, null, "test@example.com");
$orderPayload = new OrderCreateRequest(100.00, "TRY", "tr", $buyer);
processOrderCreation($client, $orderPayload, "Scenario 1: Basic Order");
}
/**
* Scenario 2: Order with Basket Items
*/
function runScenario2OrderWithBasketItems($client)
{
$buyer = new BuyerDTO("John", "Doe", null, null, null, "test@example.com");
$basketItemPayer = new BasketItemPayerDTO(
"Test Address", // address
"payer_ref0_item1", // reference_id
"Test Tax Office", // tax_office
"Test Company", // title
"PERSONAL", // type
"12345678901", // vat
);
$basketItem1 = new BasketItemDTO(
"Electronics", // category1
"Phones", // category2
5.0, // commission_amount
"DISCOUNT10", // coupon
10.0, // coupon_discount
"Item data", // data
"item_1", // id
"PHYSICAL", // item_type
"Test Product 1", // name
0, // paid_amount
$basketItemPayer, // payer
50.0, // price
1 // quantity
);
$basketItem2 = new BasketItemDTO(
"Electronics", // category1
"Accessories", // category2
2.5, // commission_amount
null, // coupon
0.0, // coupon_discount
"Item data 2", // data
"item_2", // id
"PHYSICAL", // item_type
"Test Product 2", // name
0, // paid_amount
$basketItemPayer, // payer
50.0, // price
1 // quantity
);
$orderPayload = new OrderCreateRequest(
100.00, // amount
"TRY", // currency
"tr", // locale
$buyer, // buyer
[$basketItem1, $basketItem2] // basket_items
);
processOrderCreation($client, $orderPayload, "Scenario 2: Order with Basket Items");
}
/**
* Scenario 3: Order with Addresses
*/
function runScenario3OrderWithAddresses($client)
{
$buyer = new BuyerDTO("John", "Doe", null, null, null, "test@example.com");
$billingAddress = new BillingAddressDTO(
"Test Billing Address", // address
"PERSONAL", // billing_type
"TC", // citizenship
"Istanbul", // city
"John Doe", // contact_name
"+905551234567", // contact_phone
"Turkey", // country
"Besiktas", // district
"Istanbul Tax Office", // tax_office
"John Doe", // title
"12345678901", // vat_number
"34000" // zip_code
);
$shippingAddress = new ShippingAddressDTO(
"Test Shipping Address", // address
"Istanbul", // city
"John Doe", // contact_name
"Turkey", // country
"2025-12-31", // shipping_date
"TRACK123", // tracking_code
"34000" // zip_code
);
$orderPayload = new OrderCreateRequest(
100.00, // amount
"TRY", // currency
"tr", // locale
$buyer, // buyer
null, // basket_items
$billingAddress, // billing_address
null, // checkout_design
null, // conversation_id
null, // enabled_installments
null, // external_reference_id
null, // metadata
null, // order_cards
null, // paid_amount
null, // partial_payment
null, // payment_failure_url
null, // payment_methods
null, // payment_mode
null, // payment_options
null, // payment_success_url
null, // payment_terms
null, // pf_sub_merchant
null, // redirect_failure_url
null, // redirect_success_url
$shippingAddress // shipping_address
);
processOrderCreation($client, $orderPayload, "Scenario 3: Order with Addresses");
}
/**
* Scenario 4: Installments and Payment Methods
*/
function runScenario4InstallmentsAndPaymentMethods($client)
{
$buyer = new BuyerDTO("John", "Doe", null, null, null, "test@example.com");
$orderPayload = new OrderCreateRequest(
1200.00, // amount
"TRY", // currency
"tr", // locale
$buyer, // buyer
null, // basket_items
null, // billing_address
null, // checkout_design
null, // conversation_id
[1, 2, 3, 6], // enabled_installments
"EXT_REF_123", // external_reference_id
null, // metadata
null, // order_cards
null, // paid_amount
false, // partial_payment
"https://example.com/payment-failure", // payment_failure_url
true, // payment_methods - boolean value instead of string
null, // payment_mode
null, // payment_options
"https://example.com/payment-success" // payment_success_url
);
processOrderCreation($client, $orderPayload, "Scenario 4: Installments and Payment Methods");
}
/**
* Scenario 5: Detailed Checkout Design
*/
function runScenario5DetailedCheckoutDesign($client)
{
$buyer = new BuyerDTO("John", "Doe", null, null, null, "test@example.com");
$checkoutDesign = new CheckoutDesignDTO(
"#FFFFFF", // input_background_color
"#000000", // input_text_color
"#333333", // label_text_color
"#F5F5F5", // left_background_color
"https://example.com/logo.png", // logo
"<p>Custom order details HTML content</p>", // order_detail_html
"#007BFF", // pay_button_color
"https://example.com/custom-redirect", // redirect_url
"#FFFFFF", // right_background_color
"#000000" // text_color
);
$orderPayload = new OrderCreateRequest(
250.00, // amount
"TRY", // currency
"tr", // locale
$buyer, // buyer
null, // basket_items
null, // billing_address
$checkoutDesign // checkout_design
);
processOrderCreation($client, $orderPayload, "Scenario 5: Detailed Checkout Design");
}
/**
* Scenario 11: Order with Consents
*/
function runScenario11OrderWithConsents($client)
{
$buyer = new BuyerDTO("John", "Doe", null, null, null, "test@example.com");
$consents = [
new OrderConsentDTO("User Agreement", "https://example.com/agreement"),
new OrderConsentDTO("Privacy Policy", "https://example.com/privacy")
];
$orderPayload = new OrderCreateRequest(
150.00, // amount
"TRY", // currency
"tr", // locale
$buyer, // buyer
null, // basket_items
null, // billing_address
null, // checkout_design
null, // conversation_id
null, // enabled_installments
null, // external_reference_id
null, // metadata
null, // order_cards
null, // paid_amount
null, // partial_payment
null, // payment_failure_url
null, // payment_methods
null, // payment_mode
null, // payment_options
null, // payment_success_url
null, // payment_terms
null, // pf_sub_merchant
null, // redirect_failure_url
null, // redirect_success_url
null, // shipping_address
$consents // consents
);
processOrderCreation($client, $orderPayload, "Scenario 11: Order with Consents");
}
/**
* Scenario 6: Validation Demo
*/
function runScenario6ValidationDemo($client)
{
echo str_repeat("#", 16) . "\n";
echo "Scenario 6: Validation Demo\n";
// GSM Number Validation Demo
echo "GSM Number Validation:\n";
try {
$cleanGsm = Validators::validateGsmNumber("+90 555 123-45-67");
echo "Cleaned GSM: $cleanGsm\n";
$validGsm = Validators::validateGsmNumber("05551234567");
echo "Valid GSM: $validGsm\n";
} catch (APIException $e) {
echo "GSM Validation Error: " . $e->error . "\n";
}
// Installments Validation Demo
echo "\nInstallments Validation:\n";
try {
$installments = Validators::validateInstallments("1,2,3,6");
echo "Valid installments: " . json_encode($installments) . "\n";
$installmentsWithSpaces = Validators::validateInstallments("1, 2, 3, 6");
echo "Installments with spaces: " . json_encode($installmentsWithSpaces) . "\n";
$defaultInstallments = Validators::validateInstallments("");
echo "Default installments: " . json_encode($defaultInstallments) . "\n";
} catch (APIException $e) {
echo "Installments Validation Error: " . $e->error . "\n";
}
}
/**
* Scenario 7: Validation Errors
*/
function runScenario7ValidationErrors($client)
{
echo str_repeat("#", 16) . "\n";
echo "Scenario 7: Validation Errors\n";
// Invalid GSM Number
echo "Testing invalid GSM number:\n";
try {
Validators::validateGsmNumber("invalid-phone");
} catch (APIException $e) {
echo "Expected GSM Error: " . $e->error . "\n";
}
// Invalid Installments
echo "\nTesting invalid installments:\n";
try {
Validators::validateInstallments("1,15,abc");
} catch (APIException $e) {
echo "Expected Installments Error: " . $e->error . "\n";
}
// Too short phone number
echo "\nTesting too short phone number:\n";
try {
Validators::validateGsmNumber("+90123");
} catch (APIException $e) {
echo "Expected Short Phone Error: " . $e->error . "\n";
}
}
/**
* Scenario 8: Subscription Demo
*/
function runScenario8SubscriptionDemo($client)
{
echo str_repeat("#", 16) . "\n";
echo "Scenario 8: Subscription Demo\n";
if (!$client) {
echo "Client is not initialized.\n";
return;
}
try {
// Create subscription billing
$billing = new SubscriptionBillingDTO(
"123 Main St",
"Istanbul",
"John Doe",
"TR",
"1234567890",
"34000"
);
// Create subscription user
$user = new SubscriptionUserDTO(
"user_123",
"John",
"Doe",
"john@example.com",
"5551234567",
"12345678901",
"123 Main St",
"Istanbul",
"TR",
"34000"
);
// Create subscription
$subscription = new SubscriptionCreateRequest(
100.0,
"TRY",
"Monthly Subscription",
30,
1,
1,
"ext_sub_" . time(),
"https://example.com/success",
"https://example.com/failure",
"card_token_123",
$billing,
$user
);
$response = $client->createSubscription($subscription);
echo "Subscription created successfully!\n";
echo "Reference ID: " . $response->getReferenceId() . "\n";
echo "Order Reference ID: " . $response->getOrderReferenceId() . "\n";
// Get subscription
if ($response->getReferenceId()) {
$getRequest = new SubscriptionGetRequest($response->getReferenceId(), null);
$subscriptionDetail = $client->getSubscription($getRequest);
echo "Subscription Title: " . $subscriptionDetail->getTitle() . "\n";
echo "Subscription Amount: " . $subscriptionDetail->getAmount() . "\n";
// Capture Subscription Detail Output
$resultsDir = __DIR__ . '/test_results';
file_put_contents("$resultsDir/scenario_8_subscription_detail_output.json", json_encode($subscriptionDetail, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
}
// List subscriptions
$subscriptions = $client->listSubscriptions(1, 10);
echo "Total Subscriptions: " . $subscriptions['total'] . "\n";
} catch (APIException $e) {
echo "API Error: " . $e->error . "\n";
echo "Status Code: " . $e->statusCode . "\n";
echo "Code: " . $e->code . "\n";
} catch (Exception $e) {
echo "Unexpected error: " . $e->getMessage() . "\n";
}
}
/**
* Scenario 9: Organization Settings Demo
*/
function runScenario9OrganizationSettings($client)
{
echo str_repeat("#", 16) . "\n";
echo "Scenario 9: Organization Settings Demo\n";
if (!$client) {
echo "Client is not initialized.\n";
return;
}
try {
$settings = $client->getOrganizationSettings();
echo "Organization Settings Retrieved:\n";
print_r($settings);
} catch (APIException $e) {
echo "API Error: " . $e->error . "\n";
echo "Status Code: " . $e->statusCode . "\n";
echo "Code: " . $e->code . "\n";
} catch (Exception $e) {
echo "Unexpected error: " . $e->getMessage() . "\n";
}
}
/**
* Scenario 10: Missing Endpoint Tests
*/
function runScenario10MissingEndpoints($client)
{
echo str_repeat("#", 16) . "\n";
echo "Scenario 10: Missing Endpoint Tests\n";
if (!$client) {
echo "Client is not initialized.\n";
return;
}
try {
echo "Fetching Currencies...\n";
$currencies = $client->getOrganizationCurrencies();
print_r($currencies);
echo "Fetching Scopes...\n";
$scopes = $client->getOrganizationScopes();
print_r($scopes);
echo "Fetching Organization Callback...\n";
$cb = $client->getOrganizationCallback();
print_r($cb);
} catch (Tapsilat\APIException $e) {
echo "API Error: " . $e->error . "\n";
} catch (Exception $e) {
echo "Unexpected error: " . $e->getMessage() . "\n";
}
}
// Main execution
if (php_sapi_name() === 'cli') {
echo "=== Tapsilat PHP SDK Usage Examples ===\n\n";
$apiClient = getApiClient();
if ($apiClient) {
runScenario1BasicOrder($apiClient);
runScenario2OrderWithBasketItems($apiClient);
runScenario3OrderWithAddresses($apiClient);
runScenario4InstallmentsAndPaymentMethods($apiClient);
runScenario5DetailedCheckoutDesign($apiClient);
runScenario6ValidationDemo($apiClient);
runScenario7ValidationErrors($apiClient);
runScenario8SubscriptionDemo($apiClient);
runScenario9OrganizationSettings($apiClient);
runScenario10MissingEndpoints($apiClient);
runScenario11OrderWithConsents($apiClient);
}
echo "\n=== Examples completed ===\n";
}