Создание заявок на кредит в Финсервис
После оформления заказа на сайте, необходимо оформить кредит через Финсервис на платформе Poslogic. Согласно предоставленой от Финсервиcа инструкции, был создан обработчик заказов на minishop2.
Согласно документации к minishop2 создаем свой обработчик платежей. В системе minishop2 создадим способ оплаты - Оформить кредит. На него повесим свой обработчик - CreditPayment, заранее его зарегистрировав в minishop2. core/components/minishop2/custom/payment/creditpayment.class.php
<?php if (!class_exists('msPaymentInterface')) { require_once dirname(dirname(dirname(__FILE__))) . '/model/minishop2/mspaymenthandler.class.php'; } class CreditPayment extends msPaymentHandler implements msPaymentInterface { /** * CreditPayment constructor. * * @param xPDOObject $object * @param array $config */ function __construct(xPDOObject $object, $config = array()) { parent::__construct($object, $config); $siteUrl = $this->modx->getOption('site_url'); $assetsUrl = $this->modx->getOption('assets_url') . 'components/minishop2/'; $paymentUrl = $siteUrl . substr($assetsUrl, 1) . 'payment/credit.php'; $this->config = array_merge(array( 'paymentUrl' => $paymentUrl, 'apiUrl' => $this->modx->getOption('ms2_payment_credit_api_url', null, 'https://poslogic.pro/'), 'client_id' => $this->modx->getOption('ms2_payment_credit_client_id'), 'client_secret' => $this->modx->getOption('ms2_payment_credit_client_secret'), 'point_id' => $this->modx->getOption('ms2_payment_credit_point_id'), 'redirect_url' => $this->modx->getOption('ms2_payment_credit_redirect_id'), 'order_url' => $this->modx->getOption('ms2_payment_credit_cancel_id'), 'brand' => $this->modx->getOption('ms2_payment_credit_brand'), 'type' => $this->modx->getOption('ms2_payment_credit_type'), 'status' => $this->modx->getOption('ms2_payment_credit_status'), ), $config); } /** * @param msOrder $order * * @return array|string */ public function send(msOrder $order) { if ($order->get('status') > 1) { return $this->error('ms2_err_status_wrong'); } $context = ''; $params_url = array(); $products = $order->getMany('Products'); $count_prod=count($products); $arr_product=array(); foreach ($products as $item) { $name = $item->get('name'); if (empty($name) && $product = $item->getOne('Product')) { $name = $product->get('pagetitle'); } $arr_product[]=["name"=> $name, "brand"=> $this->config['brand'], "type"=> $this->config['type'], "quant"=> $item->get('count'), "price"=> str_replace(',', '.', $item->get('price')) ]; } $address = $order->getOne('Address'); if (isset($address)) { $phone = preg_replace("~[^0-9]~", "", $address->get('phone')); preg_match('~([0-9]{1})([0-9]{3})([0-9]{7})~', $phone, $matches); if (!empty($matches)) { $arr_phone = new stdClass(); $arr_phone->area = $matches[1]; $arr_phone->code = $matches[2]; $arr_phone->number = $matches[3]; } } if (($_SESSION['minishop2']['created_at'] + $_SESSION['minishop2']['expires_in']) >= time()){ $token = $_SESSION['minishop2']['access_token']; } if (!isset($token)){ $response = $this->request($params,'/oauth/token'); if($response['code'] == 200){ $_SESSION['minishop2']['access_token'] = $response['access_token']; $_SESSION['minishop2']['created_at'] = $response['created_at']; $_SESSION['minishop2']['expires_in'] = $response['expires_in']; $token = $response['access_token']; }else{ $this->modx->log(modX::LOG_LEVEL_ERROR,'[miniShop2] Credit error while request. Response: ' . print_r($response,1)); return $this->success('', array('msorder' => $order->get('id'))); } } if (isset($token)){ $params_url['msorder'] = $order->get('id'); $params = ['access_token' => $token, 'order_id' =>$order->get('num'), 'point_id'=> $this->config['point_id'], 'redirect_url'=> $this->modx->makeUrl($this->config['redirect_url'],$context, $params_url, 'full'), 'order_url'=> $this->modx->makeUrl($this->config['order_url'],$context, $params_url, 'full'), 'mobile_phone'=> $arr_phone, 'goods'=> $arr_product, ]; $response = $this->request($params,'/ecommerce_api/v2/orders',$count_prod); $properties = array(); if (is_array($response) && !empty($response['success'])){ $properties['credit_id'] = $response['_id']; if (count($properties) > 0){ $address->set('properties', json_encode($properties)); $address->save(); } return $this->success('', array('redirect' => $response['redirect_url'])); } else { $this->modx->log(modX::LOG_LEVEL_ERROR, '[miniShop2] Credit error while request. Params: ' . print_r($params, 1) . ', response: ' . print_r($response, 1)); return $this->success('', array('msorder' => $order->get('id'))); } } } /** * Building query * @param array $params Query params * @return array/boolean */ public function request($params = array(),$url,$count=0) { if ($url == '/oauth/token'){ $customrequest = 'POST'; $params = array( 'grant_type' => 'client_credentials', 'client_id' => $this->config['client_id'], 'client_secret' => $this->config['client_secret'], ); } if ($url == '/ecommerce_api/v2/orders'){ $customrequest = 'POST'; } $reguest = http_build_query($params); /*согласно инструкции у массива с товарами не должно быть индекса товара, не придумал другого, как от него избавиться*/ for ($i = 0; $i < $count; $i++){ $reguest = strtr($reguest, array('%5B'.$i.'%5D'=>'%5B%5D','%5B'.$i.'%5D'=>'%5B%5D')); } //$this->modx->log(modX::LOG_LEVEL_ERROR, print_r($response,1)); $curlOptions = array( CURLOPT_RETURNTRANSFER => 1, CURLOPT_URL => $this->config['apiUrl'].$url, CURLOPT_CUSTOMREQUEST => $customrequest, CURLOPT_POSTFIELDS => $reguest, CURLOPT_HEADER => 0, CURLOPT_SSL_VERIFYPEER => 0, CURLOPT_SSL_VERIFYHOST => 0, ); $ch = curl_init(); curl_setopt_array($ch, $curlOptions); $out = curl_exec($ch); $result = json_decode($out, true); $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); $code = (int) $code; $errors = array( 200 => 'Successfully', 201 => 'Successfully', 400 => 'Bad request', 401 => 'Unauthorized', 403 => 'Forbidden', 404 => 'Not found', 500 => 'Internal server error', 502 => 'Bad gateway', 503 => 'Service unavailable', ); $result['code'] = $code; if ($code != 200 && $code != 201) { $result['message'] = $errors[$code]; }else{ $result['success'] = $errors[$code]; } curl_close($ch); return $result; } };
Так же необходимо прописать Пространство имен в MODX
И создать системные настройки, в которые в дальнейшем прописываем параметры подключения к Финсервису.
Создаем страницу куда будет перенаправляться после заполнения Анкеты на кредит. И в на эту страницу вешаем скрипт для изминения статуса Заказа. Статус создаем в настройка minishop2 и прописываем в настройках обработчика.
<?php if (isset($_GET['msorder'])){ //$ms2->changeOrderStatus($_GET['msorder'], $modx->getOption('ms2_payment_credit_status')); $item = $modx->getObject('msOrder',$_GET['msorder']); $item->set('status',$modx->getOption('ms2_payment_credit_status')); $item->save(); } return ;
Комментарии ()