-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathqiwi.class.php
224 lines (186 loc) · 8.08 KB
/
qiwi.class.php
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
<?php
/**
* Qiwi - класс для работы с платежным API от QIWI
* @package Qiwi
* @author atnartur (Атнагулов Артур) <i@atnartur.ru>
* @copyright 2014 atnartur (Атнагулов Артур)
*/
class Qiwi{
/**
* ID магазина
* @var int
*/
public $shop_id = 000000;
/**
* API ID (REST ID) для BASIC авторизации
* @var int
*/
public $rest_id = 00000000;
/**
* пароль API
* @var string
*/
public $rest_pass = 'PASSWORD';
/**
* валюта
* @var string
*/
public $currency = 'RUB';
/**
* Источник оплаты: mobile - оплата с мобильного телефона пользователя, qw - с любых источников оплаты Visa Qiwi Wallet
* @var string
*/
public $pay_source = 'qw';
/**
* название провайдера
* @var string
*/
public $prv_name = 'My store';
/**
* Флаг отладки. Если true, выводятся отладочные сообщения
* @var boolean
*/
public $debug = false;
/**
* Конструктор класса. Проверяет наличие CURL
*/
function __construct(){
if(!function_exists('curl_init')){
throw new Exception('CURL library not found on this server');
}
}
/**
* Создает новый CURL запрос и выставляет таймаут соединения 30 секунд
*
* @returns {resource} CURL resourse
*/
private function __curl_start($url){
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
return $ch;
}
/**
* Выставление счета
*
* @param {string} tel Телефон пользователя, на которого выставляется счет
* @param {int} amount Сумма счета
* @param {string} date Срок годности счета (в формате ISO 8601)
* @param {string} bill_id Уникальный номер счета
* @param {string} comment Комментарий к платежу (не обязательно)
* @returns {object} Объект ответа от сервера QIWI
*/
function create($tel, $amount, $date, $bill_id, $comment = null){
$parameters = array(
'user' => 'tel:+'.$tel, // телефон начинается с +
'amount' => $amount,
'ccy' => $this->currency,
'comment' => $comment,
'pay_source' => $this->pay_source,
'lifetime' => $date,
'prv_name' => $this->prv_name,
);
$ch = $this->__curl_start('https://w.qiwi.com/api/v2/prv/'.$this->shop_id.'/bills/'.$bill_id);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Accept: text/json",
"Content-Type: application/x-www-form-urlencoded; charset=utf-8"
));
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, $this->rest_id . ':' . $this->rest_pass);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($parameters));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$httpResponse = curl_exec($ch);
if($this->debug)
var_dump($httpResponse);
if (!$httpResponse) {
// Описание ошибки, к примеру
throw new Exception(curl_error($ch).'('.curl_errno($ch).')');
return false;
}
$httpResponseAr = @json_decode($httpResponse);
return $httpResponseAr->response;
}
/**
* Возвращает ссылку на страницу оплаты счета. Используется в redir()
*
* @param {string} bill_id Уникальный номер счета
* @param {string} success_url URL, на который пользователь будет переброшен в случае успешного проведения операции (не обязательно)
* @param {string} fail_url URL, на который пользователь будет переброшен в случае неудачного завершения операции (не обязательно)
* @return {string} Ссылка на страницу оплаты счета
*/
function redir_link($bill_id, $success_url = '', $fail_url = ''){
return "https://w.qiwi.com/order/external/main.action?shop=" . $this->shop_id . "&transaction=" . $bill_id .
"&successUrl=" . $success_url . "&failUrl=" . $fail_url;
}
/**
* Переадресация на страницу оплаты счета
*
* @param {string} bill_id Уникальный номер счета
* @param {string} success_url URL, на который пользователь будет переброшен в случае успешного проведения операции (не обязательно)
* @param {string} fail_url URL, на который пользователь будет переброшен в случае неудачного завершения операции (не обязательно)
*/
function redir($bill_id, $success_url = '', $fail_url = ''){
header("Location: " . $this->redir_link($bill_id, $success_url, $fail_url));
}
/**
* Информация о счете
*
* @param {string} bill_id Уникальный номер счета
* @returns {object} Объект ответа от сервера QIWI
*/
function info($bill_id){
$ch = $this->__curl_start('https://w.qiwi.com/api/v2/prv/'.$this->shop_id.'/bills/'.$bill_id);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Accept: text/json",
"Content-Type: application/x-www-form-urlencoded; charset=utf-8"
));
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, $this->rest_id . ':' . $this->rest_pass);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$httpResponse = curl_exec($ch);
if($this->debug)
var_dump($httpResponse);
if (!$httpResponse) {
// Описание ошибки, к примеру
throw new Exception(curl_error($ch).'('.curl_errno($ch).')');
return false;
}
$httpResponseAr = @json_decode($httpResponse);
return $httpResponseAr->response;
}
/**
* Отмена платежа
*
* @param {string} bill_id Уникальный номер счета
* @returns {object} Объект ответа от сервера QIWI
*/
function reject($bill_id){
$parameters = array(
'status' => 'rejected'
);
$ch = $this->__curl_start('https://w.qiwi.com/api/v2/prv/'.$this->shop_id.'/bills/'.$bill_id);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Accept: text/json",
"Content-Type: application/x-www-form-urlencoded; charset=utf-8"
));
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, $this->rest_id . ':' . $this->rest_pass);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PATCH');
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($parameters));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$httpResponse = curl_exec($ch);
if($this->debug)
var_dump($httpResponse);
if (!$httpResponse) {
// Описание ошибки, к примеру
throw new Exception(curl_error($ch).'('.curl_errno($ch).')');
return false;
}
$httpResponseAr = @json_decode($httpResponse);
return $httpResponseAr->response;
}
}