<?php 

/**
* Инициальзация платежа
*/

if (isset($_POST['shop_qiwi'])) {
  
    // Получение настроек системы
    $set_paytype = $payment->getSettings('qiwi');
    
    $data = array(
        'user' => 'tel:' . $_POST['to'],
        'amount' => $_POST['summ'],
        'ccy' => 'RUB',
        'comment' => $_POST['comm'],
        'lifetime' => $_POST['lifetime'],
        'pay_source' => 'qw',
    );
    
    if (!preg_match('/^tel:\+\d{1,15}$/', $data['user'])) {
        $err[] = __('Неверный формат номера телефона');
    }
    
    if (!isset($err)) {
        require 'classes/Qiwi.php';
        
        $authAPI = array(
            'id' => $set_paytype['PAYMENT']['SHOP_ID'],
            'api_id' => $set_paytype['PAYMENT']['API_ID'],
            'api_pass' => $set_paytype['PAYMENT']['API_PASS'],
        );
        
        $url = 'https://w.qiwi.com/api/v2/prv/' . $set_paytype['PAYMENT']['SHOP_ID'] . '/bills/' . $_POST['txn_id'];
        
        $qiwi = new Qiwi($authAPI);
        
        $dataID = explode(':', base64_decode($_POST['txn_id']));
        $sign = sha1($dataID[0].$_POST['summ'].$set_paytype['PAYMENT']['SECRET_KEY']);
        $hash = base64_encode($dataID[0].':'.$sign);
        
        if ($hash === $_POST['txn_id']) {
            $init = $qiwi->create($url, $data);
            
            $response = json_decode($init, true);
            
            if ($response['response']['result_code'] != 0) {
                $err[] = $qiwi->parseError($response['response']['result_code']);
            }
            
            if (isset($response['response']['bill']) && $response['response']['bill']['status'] == 'waiting') 
            {
                $uri = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
                $_SESSION['i_phone'] = $_POST['to'];
                header('Location: https://w.qiwi.com/order/external/main.action?shop=' . $set_paytype['PAYMENT']['SHOP_ID'] . '&transaction=' . $_POST['txn_id'] . '&successUrl=' . $uri . '&request=success&failUrl=' . $uri . '&request=fail&qiwi_phone=' . $data['user']);
                exit;
            }
        }      
    }
}

/**
* Входящий платеж
*/

if (isset($_POST['bill_id'])) {
  
  // Получение настроек системы
  $set_paytype = $payment->getSettings('qiwi');
  
  $dataID = explode(':', base64_decode($_POST['bill_id']));
  
  $checkPOST = array(
                  'id' => (int) $dataID[0], 
                  'service' => '', 
                  'service_id' => '', 
                  'wmr' => round($_POST['amount'], 2), 
                  'array' => serialize($_POST),
                  'paytype' => 'qiwi',
                  'method' => 'QIWI Wallet - ' . my_esc($_POST['user']) . "\nСчет в QIWI #" . my_esc($_POST['prv_name']),
                  'http_code' => array(
                                  'HTTP/1.1 200 OK', 
                                  'content-type: text/xml; charset=UTF-8',
                                  ),
                  'resp' => '<!--?xml version="1.0"?--><result><result_code>0</result_code></result>',
                  );
  
  $sign = sha1($dataID[0].$_POST['amount'].$set_paytype['PAYMENT']['SECRET_KEY']);
  $hash = base64_encode($dataID[0].':'.$sign);

  if ($request === 'result') {
    if ($hash === $_POST['bill_id'] && $_POST['status'] == 'paid') {
      $pay_result = 'result';
    } else {
      header('HTTP/1.1 200 OK');
      header('content-type: text/xml; charset=UTF-8');
      echo '<!--?xml version="1.0"?--><result><result_code>151</result_code></result>';
      exit;
    }
  }
}