-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp_status_handling.php
More file actions
105 lines (85 loc) · 2.8 KB
/
Copy pathhttp_status_handling.php
File metadata and controls
105 lines (85 loc) · 2.8 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
<?php
require 'vendor/autoload.php';
include 'secrets.php';
use GuzzleHttp\Client;
function tpaga_api_post($url, $data, $expected_http_codes) {
global $TPAGA_API_PRIVATE_TOKEN;
$client = new Client([
'base_uri' => 'https://sandbox.tpaga.co',
'timeout' => 30,
'headers' => [
'Content-Type' => 'application/json'
],
'http_errors' => false,
]);
$response = null;
try {
$response = $client->post(
$url,
[
'auth' => [ $TPAGA_API_PRIVATE_TOKEN, '' ],
'json' => $data,
]
);
} catch (Exception $e) {
error_log("Caught exception: " . $e->getMessage());
header("Location: http://" . $_SERVER[HTTP_HOST] . "/");
die();
}
if (!in_array($response->getStatusCode(), $expected_http_codes)) {
$_SESSION["error_msg"] = message_for_failed_request($response);
# TODO set proper path for redirect
header("Location: http://" . $_SERVER[HTTP_HOST] . "/");
die();
}
return json_decode($response->getBody(), true);
}
function unsafe_tpaga_api_post($url, $data, $expected_http_codes) {
global $TPAGA_API_PRIVATE_TOKEN;
$client = new Client([
'base_uri' => 'https://sandbox.tpaga.co',
'timeout' => 30,
'headers' => [
'Content-Type' => 'application/json'
],
'http_errors' => false,
]);
$response = $client->post(
$url,
[
'auth' => [ $TPAGA_API_PRIVATE_TOKEN, '' ],
'json' => $data,
]
);
// any 5XX HTTP status code will also be handled by the caller
if (
!in_array($response->getStatusCode(), $expected_http_codes)
&& $response->getStatusCode() < 500
) {
$_SESSION["error_msg"] = message_for_failed_request($response);
# TODO set proper path for redirect
header("Location: http://" . $_SERVER[HTTP_HOST] . "/");
die();
}
return $response;
}
function message_for_failed_request($response) {
$http_status_code = $response->getStatusCode();
error_log("TPaga API answered: " . $http_status_code);
if ($http_status_code == 401) {
return "Ooops, credentials for Tpaga API are wrong";
}
if ($http_status_code == 422) {
$response_data = json_decode($response->getBody(), true);
error_log(print_r($response_data, true));
return "Ooops, we sent wrong data to the Tpaga API: invalid data in field: " . $response_data['errors'][0]['field'];
}
if ($http_status_code >= 400 && $http_status_code < 500) {
return "Ooops, we did something wrong with the Tpaga API";
}
if ($http_status_code >= 500) {
return "Ooops, the Tpaga API failed";
}
return "What?! unknown error";
}
?>