Commit b9fb3e6e authored by innerfly's avatar innerfly
Browse files

first edition of module

parent 56df691a
Loading
Loading
Loading
Loading

images/logo.gif

0 → 100644
+1.36 KiB
Loading image diff...

uc_rbkmoney.module

0 → 100644
+308 −0
Original line number Diff line number Diff line
<?php

/**
 * Implementation of hook_perm().
 */
function uc_rbkmoney_perm() {
  return array('administer uc_rbkmoney');
}

/**
 * Implementation of hook_menu().
 */
function uc_rbkmoney_menu() {
  $items['admin/store/settings/uc_rbkmoney'] = array(
    'title' => 'RBK Money',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('uc_rbkmoney_setup'),
    'access arguments' => array('access content'),
    'type' => MENU_NORMAL_ITEM,
  );
  $items['uc_rbkmoney/response'] = array(
    'title' => 'Internal Data',
    'page callback' => 'uc_rbkmoney_done_payment',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  $items['uc_rbkmoney/success'] = array(
    'title' => 'Internal Data',
    'page callback' => 'uc_rbkmoney_payment_end',
    'page arguments' => array('success'),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  $items['uc_rbkmoney/fail'] = array(
    'title' => 'Internal Data',
    'page callback' => 'uc_rbkmoney_payment_end',
    'page arguments' => array('fail'),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

/**
 * Callback for settings page
 */
function uc_rbkmoney_setup() {
  $form['responseURL'] = array(
    '#type' => 'fieldset',
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
    '#title' => t('URL оповещения о платеже')
  );
  global $base_url;
  $form['responseURL']['url'] = array(
    '#type' => 'textfield',
    '#value' => $base_url . '/uc_rbkmoney/response',
    '#description' => t("Для вставки в поле \"Оповещение о платеже\" в личном кабинете на сайте <a target=_blank href=\"http://www.rbkmoney.ru\">RBK Money</a>"),
  );
  $form['actionURL'] = array(
    '#type' => 'textfield',
    '#title' => t('URL формы запроса платежа'),
    '#default_value' => variable_get('uc_rbkmoney_actionURL', 'https://rbkmoney.ru/acceptpurchase.aspx'),
    '#description' => t("По-умолчанию \"https://rbkmoney.ru/acceptpurchase.aspx\""),
    '#required' => TRUE,
  );
  $form['eshopId'] = array(
    '#type' => 'textfield',
    '#title' => t('ID сайта'),
    '#default_value' => variable_get('uc_rbkmoney_eshopId', ''),
    '#description' => t("Введите ID вашего сайта в системе RBK Money"),
    '#required' => TRUE,
  );
  $curr = variable_get('uc_rbkmoney_recipientCurrency', 'RUR');
  $form['recipientCurrency'] = array(
    '#type' => 'select',
    '#title' => t('Валюта платежей'),
    '#options' => array($curr => $curr, 'RUR' => 'RUR', 'USD' => 'USD', 'EUR' => 'EUR', 'UAH' => 'UAH'),
    '#description' => t("Укажите валюту платежей"),
    '#required' => TRUE,
  );
  $form['secretKey'] = array(
    '#type' => 'textfield',
    '#title' => t('Секретный ключ'),
    '#default_value' => variable_get('uc_rbkmoney_secretKey', ''),
    '#description' => t("Секретный ключ, указанный вами в личном кабинете на сайте <a target=_blank href=\"http://www.rbkmoney.ru\">RBK Money</a>"),
    '#required' => TRUE,
  );
  $form['log'] = array(
    '#type' => 'radios',
    '#title' => t('Записывать ответы сервера RBK Money о платежах в <a href="/admin/reports/dblog">системный журнал</a>'),
    '#options' => array('on' => t('Да'), 'off' => t('Нет')),
    '#default_value' => variable_get('uc_rbkmoney_log', 'on'),
  );
  $form['preference'] = array(
    '#type' => 'fieldset',
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
    '#title' => t('Дополнительные опции протокола')
  );
  $pref = variable_get('uc_rbkmoney_preference', 'all');
  $form['preference']['method'] = array(
    '#type' => 'select',
    '#title' => t('Предпочитаемый способ оплаты'),
    '#options' => array(
      $pref => '',
      'all' => 'Все (по-умолчанию)',
      'inner' => 'С кошелька RBK Money',
      'bankCard' => 'Банковская карта Visa/MasterCard',
      'exchangers' => 'Электронные платежные системы',
      'prepaidcard' => 'Предоплаченная карта RBK Money',
      'transfers' => 'Системы денежных переводов',
      'terminals' => 'Платёжные терминалы',
      'iFree' => 'SMS',
      'bank' => 'Банковский платёж',
      'postRus' => 'Почта России',
      'atm' => 'Банкоматы',
      'yandex' => 'Яндекс',
      'ibank' => 'Интернет банкинг',
      'euroset' => 'Евросеть'
    ),
    '#description' => t("Способ оплаты, который будет выбран при оплате покупки, минуя экран выбора"),
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Сохранить'),
  );
  return $form;
}

/**
 * Submit setup form
 */
function uc_rbkmoney_setup_submit($form, &$form_state) {
  variable_set('uc_rbkmoney_actionURL', trim($form_state['values']['actionURL']));
  variable_set('uc_rbkmoney_eshopId', trim($form_state['values']['eshopId']));
  variable_set('uc_rbkmoney_recipientCurrency', $form_state['values']['recipientCurrency']);
  variable_set('uc_rbkmoney_secretKey', $form_state['values']['secretKey']);
  variable_set('uc_rbkmoney_log', $form_state['values']['log']);
  variable_set('uc_rbkmoney_preference', $form_state['values']['method']);
  drupal_set_message(t('Настройки сохранены'), $type = 'status');
}

/**
 * Implementation of hook_payment_method().
 */
function uc_rbkmoney_payment_method() {
  $path = base_path() . drupal_get_path('module', 'uc_rbkmoney');
  $title = t('RBK Money') . '<br /><img src="' . $path . '/images/logo.gif" style="position: relative; left: 2.5em;">';
  $methods[] = array(
    'id' => 'rbkmoney',
    'name' => t('RBK Money'),
    'title' => $title,
    'desc' => t('Оплата через систему RBK Money'),
    'weight' => 1,
    'callback' => 'uc_payment_method_rbkmoney',
    'checkout' => TRUE,
    'no_gateway' => TRUE,
  );
  return $methods;
}

/**
 * Callback for rbkmoney payment method settings.
 */
function uc_payment_method_rbkmoney($op, &$arg1) {
  switch ($op) {
    case 'cart-details':
      return $details;
    case 'cart-process':
      return;
  }
}

/**
 * Implementation of hook_form_alter().
 */
function uc_rbkmoney_form_alter(&$form, $form_state, $form_id) {
  $order_id = (int) $_SESSION['cart_order'];
  if ($form_id == 'uc_cart_checkout_review_form' && $order_id > 0) {
    $order = uc_order_load($order_id);
    if ($order->payment_method == 'rbkmoney') {
      unset($form['submit']);
      $form['#prefix'] = '<table><tr><td>';
      $form['#suffix'] = '</td><td>' . drupal_get_form('uc_rbkmoney_submit_form', $order) . '</td></tr></table>';
    }
  }
}

/**
 * Payment request form
 */
function uc_rbkmoney_submit_form($form_state, $order) {
  global $base_url;
  $desc = '';
  foreach ($order->products as $value) {
    $desc .= $value->qty . ' x ' . $value->title . ', ';
  }
  $form['eshopId'] = array(
    '#type' => 'hidden',
    '#value' => variable_get('uc_rbkmoney_eshopId', ''),
  );
  $form['orderId'] = array(
    '#type' => 'hidden',
    '#value' => $order->order_id,
  );
  $form['serviceName'] = array(
    '#type' => 'hidden',
    '#value' => $desc,
  );
  $form['recipientAmount'] = array(
    '#type' => 'hidden',
    '#value' => $order->order_total,
  );
  $form['recipientCurrency'] = array(
    '#type' => 'hidden',
    '#value' => variable_get('uc_rbkmoney_recipientCurrency', ''),
  );
  $form['successUrl'] = array(
    '#type' => 'hidden',
    '#value' => $base_url . '/uc_rbkmoney/success',
  );
  $form['failUrl'] = array(
    '#type' => 'hidden',
    '#value' => $base_url . '/uc_rbkmoney/fail',
  );
  $pref = variable_get('uc_rbkmoney_preference', '');
  if ($pref != 'all') {
    $form['preference'] = array(
      '#type' => 'hidden',
      '#value' => $pref,
    );
  }
  $form['#action'] = variable_get('uc_rbkmoney_actionURL', '');
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Перейти к оплате'),
  );
  return $form;
}

/**
 * Callback for RBK Money system response
 */
function uc_rbkmoney_done_payment() {
  drupal_set_header('Content-type: text/html; charset=iso-8859-1');

  if (variable_get('uc_rbkmoney_log', '') == 'on') {
    $log = '<pre>' . var_export($GLOBALS['_POST'], TRUE) . '</pre>';
    watchdog('RBK Money', $log);
  }

  $response['eshopId'] = $GLOBALS['_POST']['eshopId'];
  $response['orderId'] = $GLOBALS['_POST']['orderId'];
  $response['serviceName'] = $GLOBALS['_POST']['serviceName'];
  $response['eshopAccount'] = $GLOBALS['_POST']['eshopAccount'];
  $response['recipientAmount'] = $GLOBALS['_POST']['recipientAmount'];
  $response['recipientCurrency'] = $GLOBALS['_POST']['recipientCurrency'];
  $response['paymentStatus'] = $GLOBALS['_POST']['paymentStatus'];
  $response['userName'] = $GLOBALS['_POST']['userName'];
  $response['userEmail'] = $GLOBALS['_POST']['userEmail'];
  $response['paymentData'] = $GLOBALS['_POST']['paymentData'];
  $response['hash'] = $GLOBALS['_POST']['hash'];

  if (!empty($response['hash'])) {
    $crc = md5($response['eshopId'] . '::' . $response['orderId'] . '::' . $response['serviceName'] . '::' . $response['eshopAccount'] . '::' . $response['recipientAmount'] . '::' . $response['recipientCurrency'] . '::' . $response['paymentStatus'] . '::' . $response['userName'] . '::' . $response['userEmail'] . '::' . $response['paymentData'] . '::' . variable_get('uc_rbkmoney_secretKey', ''));
    $order = uc_order_load($response['orderId']);

    if ($response['hash'] == $crc) {
      switch ($response['paymentStatus']) {
        case "3" :
          uc_order_update_status($response['orderId'], 'processing');
          uc_order_comment_save($response['orderId'], $order->uid, t('RBK Money: платеж обрабатывается'), $type = 'admin', $status = 1, $notify = FALSE);
          break;
        case "5" :
          uc_payment_enter($response['orderId'], 'RBK Money', $response['recipientAmount'], $order->uid, NULL, NULL);
          uc_cart_complete_sale($order);
          uc_order_comment_save($response['orderId'], $order->uid, t('RBK Money: платеж успешно выполнен'), $type = 'admin', $status = 1, $notify = FALSE);
          break;
      }
    } elseif ($response['hash'] != $crc) {
      uc_order_update_status($response['orderId'], 'canceled');
      uc_order_comment_save($response['orderId'], $order->uid, t('Контрольная подпись не совпадает, платеж отменен'), $type = 'admin', $status = 1, $notify = FALSE);
      drupal_set_message(t('Контрольная подпись не совпадает, платеж отменен'), 'warning');
      drupal_goto('cart');
    }
  }
}

/**
 * Callback redirect from RBK Money site
 */
function uc_rbkmoney_payment_end($arg) {
  switch ($arg) {
    case "success" :
      if (isset($_SESSION['cart_order'])) {
        $_SESSION['do_complete'] = TRUE;
        drupal_goto('cart/checkout/complete');
      }
      break;
    case "fail" :
      unset($_SESSION['cart_order']);
      drupal_set_message(t("Your payment has been declined."));
      drupal_goto('cart');
      break;
  }
  return;
}
 No newline at end of file