/**
  * Проверяем header уведомлений и ответов от PayQR на соответствие значению SecretKeyIn
  *
  * @param $secretKeyIn
  * @return bool
  */
 public static function checkHeader($secretKeyIn, $headers = false)
 {
     if (!payqr_config::$checkHeader) {
         return true;
     }
     if (!$headers) {
         if (!function_exists('getallheaders')) {
             $headers = payqr_base::getallheaders();
         } else {
             $headers = getallheaders();
         }
     }
     if (!$headers) {
         header("HTTP/1.0 404 Not Found");
         payqr_logs::log("Не удалось выполнить проверку входящего секретного ключа SecretKeyIn, отсутствует headers", __FILE__ . " " . __METHOD__, __LINE__);
         return false;
     }
     // Проверяем соответствие пришедшего значения поля PQRSecretKey значению SecretKeyIn из конфигурации библиотеки
     if (isset($headers['PQRSecretKey']) && $headers['PQRSecretKey'] == $secretKeyIn) {
         return true;
     }
     foreach ($headers as $key => $header) {
         $headers[strtolower($key)] = $header;
     }
     if (isset($headers['pqrsecretkey']) && $headers['pqrsecretkey'] == $secretKeyIn) {
         return true;
     }
     header("HTTP/1.0 404 Not Found");
     payqr_logs::log("Входящий секретный ключ из headers не совпадает с входящим ключом из файла конфигурации \n\r Текущее значение SecretKeyIn из вашего payqr_config.php: " . $secretKeyIn . " \n\r Содержание headers полученного уведомления от PayQR: " . print_r($headers, true), __FILE__ . " " . __METHOD__, __LINE__);
     return false;
 }
示例#2
0
 /**
  * Отправка PUT-запроса
  * @param $url
  * @param array $vars
  * @return mixed|string
  */
 public function put($url, $vars = array())
 {
     $response = $this->curl->put($url, $vars);
     payqr_logs::log(print_r($response, true), __FILE__ . " " . __FUNCTION__, __LINE__);
     $this->check_response($response);
     return $response->body;
 }
$order_id = $payqrOrder->checkInvoice($inv_id);
if (!empty($order_id)) {
    //заказ с заданнными параметрами уже создавался
    //производим обновление состояния заказа
    if ($payqrOrder->updateShopkeeper3Order($order_id)) {
        payqr_logs::log("Успешно произведено обновление товаров");
    } else {
        payqr_logs::log("Не смогли произвести обновление товаров в заказе");
    }
} else {
    //создаем заказ на основе актуализированным данных
    $order_id = $payqrOrder->createShopkeeper3Order($user_id);
    $payqrOrder->setInvoice($order_id, $inv_id);
}
//Получаем стоимость товара с доставкой
$amount = $payqrOrder->getTotal(true);
if (empty($amount)) {
    payqr_logs::log('Не смогли получить amount у заказа!');
    return false;
}
payqr_logs::log('Итоговая стоимость amount у заказа : ' . $amount);
$Payqr->objectOrder->setAmount($amount);
if (!$order_id) {
    payqr_logs::log('Не смогли получить orderId у заказа!');
    return false;
}
payqr_logs::log('Устанавливаем orderId: ' . $order_id);
$Payqr->objectOrder->setOrderId($order_id);
//Корзину необходимо очищать
$userdata = array("cart_id" => isset($config['cart_id']) ? (int) $config['cart_id'] : null, "user_id" => $user_id, "session_id" => "session", "order_id" => $order_id, "amount" => $amount, "message" => isset($config['user_message_text']) ? $config['user_message_text'] : "", "messageImageURL" => isset($config['user_message_imageurl']) ? $config['user_message_imageurl'] : "", "messageURL" => isset($config['user_message_url']) ? $config['user_message_url'] : "");
$Payqr->objectOrder->setUserData(json_encode($userdata));
示例#4
0
 /**
  * Проверяет наличие обязательных параметров в ответе на уведомление от PayQR
  * @return bool
  */
 private function validateResponse()
 {
     switch ($this->type) {
         case 'invoice.order.creating':
             if (intval($this->objectOrder->getOrderId()) < 1 || strlen($this->objectOrder->getOrderId()) == 0) {
                 payqr_logs::log('Критическая ошибка: интернет-сайт не указал уникальный номер созданного заказа (orderId) в ответе на уведомление invoice.order.creating', 'payqr_receiver::validateResponse()', __LINE__);
                 return false;
             }
     }
     return true;
 }
示例#5
0
 /**
  * Makes an HTTP request of the specified $method to a $url with an optional array or string of $vars
  *
  * Returns a payqr_curl_response object if the request was successful, false otherwise
  *
  * @param string $method
  * @param string $url
  * @param array|string $vars
  * @return payqr_curl_response|boolean
  **/
 function request($method, $url, $vars = array())
 {
     $this->error = '';
     $this->request = curl_init();
     if (is_array($vars)) {
         $vars = http_build_query($vars, '', '&');
     }
     $this->set_request_method($method);
     $this->set_request_options($url, $vars);
     $this->set_request_headers();
     $response = curl_exec($this->request);
     if ($response) {
         $response = new payqr_curl_response($response);
     } else {
         $this->error = curl_errno($this->request) . ' - ' . curl_error($this->request);
         payqr_logs::log(__FILE__ . "\n\r" . __METHOD__ . "\n\r L:" . __LINE__ . "\n\r" . 'Ошибка при запросе ' . $method . ' ' . $url . ' ' . var_export($vars, true) . "\n" . ' ' . $this->error);
     }
     curl_close($this->request);
     return $response;
 }
示例#6
0
 /**
  * Отправка POST-запроса
  * @param $url
  * @param $postdata
  * @return bool|payqr_curl_response
  */
 public function post($url, $postdata)
 {
     if (is_array($postdata)) {
         $postdata = payqr_base::http_build_query($postdata, '', '&');
     }
     $url_obj = parse_url($url);
     if (!isset($url_obj['host'])) {
         payqr_logs::log(__FILE__ . "\n\r" . __METHOD__ . "\n\r L:" . __LINE__ . "\n\r" . " Неверный параметр url: " . $url . " не удалось определить host для запроса");
         return false;
     }
     $host = $url_obj['host'];
     $errno = "";
     $errstr = "";
     $fp = fsockopen("ssl://" . $host, 443, &$errno, &$errstr, intval(payqr_config::$maxTimeOut));
     if (!$fp) {
         payqr_logs::log(__FILE__ . "\n\r" . __METHOD__ . "\n\r L:" . __LINE__ . "\n\r" . 'Ошибка при запросе ' . $url . ' ' . $errstr($errno) . "\n");
     } else {
         $out = "POST {$url} HTTP/1.1\r\n";
         $out .= "User-Agent: PayQr Lib\r\n";
         $out .= "Host: {$host}\r\n";
         $out .= "Accept: */*\r\n";
         if (is_array($this->headers)) {
             foreach ($this->headers as $key => $value) {
                 $out .= "{$key}: {$value}\r\n";
             }
         }
         $out .= "Connection: Close\r\n\r\n";
         $out .= "{$postdata}\n\n";
         $out .= "\r\n";
         fwrite($fp, $out);
         $output = "";
         while (!feof($fp)) {
             $output .= fgets($fp, 1024);
         }
         fclose($fp);
         $response = false;
         if ($output) {
             $response = new payqr_curl_response($output);
         } else {
             payqr_logs::log(__FILE__ . "\n\r" . __METHOD__ . "\n\r L:" . __LINE__ . "\n\r" . 'Ошибка при запросе ' . $url . ' пустой или неправильный ответ ' . print_r($output, true) . "\n");
         }
         return $response;
     }
 }
示例#7
0
$rest->prepare();
// Make sure the user has the proper permissions, send the user a 401 error if not
if (!$rest->checkPermissions()) {
    $rest->sendUnauthorized(true);
}
//
require_once $modx->getOption('payqr_core_path', null, $modx->getOption('core_path') . 'components/payqr/') . 'model/payqr/Payqr/payqr_config.php';
$payqr_button = new payqr_button($modx, []);
$config = $payqr_button->getPayqrItems();
$payqrConfig = payqr_config::init($config['merchant_id'], $config['secret_key_in'], $config['secret_key_out']);
if (isset($config['log_url']) && !empty($config['log_url'])) {
    payqr_config::$enabledLog = true;
    $log_file_name = pathinfo($config['log_url']);
    payqr_config::setLogFile($log_file_name['basename']);
}
payqr_logs::addEnter();
try {
    $Payqr = new payqr_receiver();
    // создаем объект payqr_receiver
    $Payqr->receiving();
    // получаем идентификатор счета на оплату в PayQR
    // проверяем тип уведомления от PayQR
    switch ($Payqr->getType()) {
        case 'invoice.deliverycases.updating':
            // нужно вернуть в PayQR список способов доставки для покупателя
            require_once PAYQR_HANDLER . 'invoice.deliverycases.updating.php';
            break;
        case 'invoice.pickpoints.updating':
            // нужно вернуть в PayQR список пунктов самовывоза для покупателя
            require_once PAYQR_HANDLER . 'invoice.pickpoints.updating.php';
            break;
示例#8
0
 /**
  * Отменяет заказ (счет) до его оплаты (не через отдельный запрос в PayQR, а ответом в PayQR на полученное уведомление как HTTP/1.1 409 Conflict, поэтому подходит для использования только на этапе получения уведомления о событии invoice.order.creating)
  */
 public function cancelOrder()
 {
     payqr_logs::log('payqr_invoice::cancelOrder()');
     $this->cancel = true;
 }
示例#9
0
 /**
  * Возвращает сумму возврата по счету из объекта PayQR "Возвраты"
  * @return float
  */
 public function getAmount()
 {
     payqr_logs::log('payqr_revert::getAmount()');
     return isset($this->data->amount) ? $this->data->amount : 0;
 }
示例#10
0
 /**
  * Default Constructor
  *
  * @param string|null $message
  * @param int  $code
  */
 public function __construct($message = null, $code = 0, $response = false)
 {
     parent::__construct($message, $code);
     $this->response = $response;
     payqr_logs::log('Вызвано исключение : ' . $this->errorMessage());
 }