From 3cac46f3ca0be397bc856e9addaabbd751af36c4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=95=D0=B2=D0=B3=D0=B5=D0=BD=D0=B8=D0=B9?= Date: Sun, 11 Mar 2018 22:42:47 +0300 Subject: [PATCH] =?UTF-8?q?=D0=B2=D0=B5=D1=80=D1=81=D0=B8=D1=8F=201.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- controllers/front/paying.php | 160 ++++++++++++++-- controllers/front/validation.php | 56 +++++- lib/api.php | 236 ++++++++++++++++++++++++ lib/base.php | 65 +++++++ lib/exceptions.php | 34 ++++ lib/external_payment.php | 57 ++++++ translations/index.php | 11 ++ translations/ru.php | 0 views/templates/front/payment_infos.tpl | 17 +- views/templates/hook/info.tpl | 10 +- yadpay.jpg | Bin 2687 -> 2929 bytes yadpay.php | 155 +++++++++++----- 12 files changed, 719 insertions(+), 82 deletions(-) create mode 100644 lib/api.php create mode 100644 lib/base.php create mode 100644 lib/exceptions.php create mode 100644 lib/external_payment.php create mode 100644 translations/index.php create mode 100644 translations/ru.php diff --git a/controllers/front/paying.php b/controllers/front/paying.php index da7f4dc..de40770 100644 --- a/controllers/front/paying.php +++ b/controllers/front/paying.php @@ -1,24 +1,162 @@ context->cart; + $wallet = $this->module->yadWallet; + $client_id = $this->module->yadClientId; + $redirect_uri = $this->module->yadRedirectUrl; + $client_secret = $this->module->yadSecret; + + $cart = $this->context->cart; + $cid = (int)$cart->id); $currency = $this->context->currency; - $total = (float)$cart->getOrderTotal(true, Cart::BOTH); + $total = 2;//(float)$cart->getOrderTotal(true, Cart::BOTH); + + $rub_currency_id = Currency::getIdByIsoCode('RUB'); + if ($cart->id_currency != $rub_currency_id) { + $from_currency = new Currency($cart->id_currency); + $to_currency = new Currency($rub_currency_id); + $total = Tools::convertPriceFull($total, $from_currency, $to_currency); + } + + + $shop_name = Configuration::get('PS_SHOP_NAME'); + $comment = 'Оплата заказа в '.$shop_name.' на сумму '.$total.' руб.'; + $message = 'Оплата корзины '.$cart->id.' в '.$shop_name.' на сумму '.$total.' руб.'; + $label = $shop_name.'/'.$cart->id; + + $this->module->sendToVk($shop_name.': '.'Началась оплата ' . $total); + + //Оплата деньгами + if (Tools::getValue('by') == 'yad') { + + $scope = array( + "payment.to-account(\"".$wallet."\",\"account\").limit(,".$total.")", + "money-source(\"wallet\")" + ); + + $auth_url = API::buildObtainTokenUrl($client_id, $redirect_uri, $scope); + Tools::redirect($auth_url); + } + + //Получаем код от Яндекса и снимаем деньги + if (Tools::getValue('code')) { + $code = Tools::getValue('code'); + + $response = API::getAccessToken($client_id, $code, $redirect_uri, $client_secret); + + if(property_exists($response, "error")) { + $this->module->sendToVk($shop_name.': '.Tools::getValue('error')); + Tools::redirect('index.php?controller=order&step=3'); + } + $access_token = $response->access_token; + + if ($access_token) { + $api = new API($access_token); + + $request_payment = $api->requestPayment(array( + "pattern_id" => "p2p", + "to" => $wallet, + "amount_due" => $total, + "comment" => $comment, + "message" => $message, + "label" => $label, + )); + + $process_payment = $api->processPayment(array( + "request_id" => $request_payment->request_id, + )); + + $this->module->sendToVk($shop_name.': '.'Оплачено я.деньгами ' . $total .' руб.'); + + Tools::redirect($this->context->link->getModuleLink($this->module->name, 'validation', array(), true)); + + }else{ + $this->module->sendToVk($shop_name.': '.'Ошибка access_token Я.Деньги'); + Tools::redirect('index.php?controller=order&step=3'); + } + + + } + + //Оплата картой + if (Tools::getValue('by') == 'card') { + + $res = ExternalPayment::getInstanceId($client_id); + + if ($res->status == 'success') { + $instance_id = $res->instance_id; + $external_payment = new ExternalPayment($instance_id); + + $payment_options = array( + "pattern_id" => "p2p", + "to" => $wallet, + "amount_due" => $total, + "comment" => trim($comment), + "message" => trim($message), + "label" => $label, + ); + + $response = $external_payment->request($payment_options); + + if ($response->status == "success") { + + $request_id = $response->request_id; + $this->context->cookie->yadpay_encrypt_CRequestId + = urlencode($this->module->getCipher()->encrypt($request_id)); + $this->context->cookie->yadpay_encrypt_CInstanceId + = urlencode($this->module->getCipher()->encrypt($instance_id)); + $this->context->cookie->write(); + + do { + $process_options = array( + 'request_id' => $request_id, + 'instance_id' => $instance_id, + 'ext_auth_success_uri' => $this->context->link->getModuleLink($this->module->name, 'validation', array('cart_id'=> $cid), true), + 'ext_auth_fail_uri' => Tools::getShopDomainSsl(true, true).__PS_BASE_URI__.'index.php?controller=order&step=3' + ); + + $result = $external_payment->process($process_options); + if ($result->status == "in_progress") { + sleep($result->next_retry); + } + } while ($result->status == "in_progress"); + + if ($result->status == 'success') { + $this->module->sendToVk($shop_name.': '.'Оплачено Картой ' . $total .' руб. (без 3D secure)'); + Tools::redirect($this->context->link->getModuleLink($this->module->name, 'validation', array('cart_id'=> $cid, true)); + + } elseif ($result->status == 'ext_auth_required') { + $url = sprintf("%s?%s", $result->acs_uri, http_build_query($result->acs_params)); + Tools::redirect($url, ''); + exit; + } elseif ($result->status == 'refused') { + $this->module->sendToVk($shop_name.' - Ошибка оплаты картой: ' . $result->error); + Tools::redirect('index.php?controller=order&step=3'); + } + } else { + $this->module->sendToVk($shop_name.' - Ошибка оплаты картой: '.$response->error); + Tools::redirect('index.php?controller=order&step=3'); + } - foreach($cart as $key => $value) - { - echo "[$key]", $value, "
"; + } else { + $this->module->sendToVk($shop_name.' - Ошибка оплаты картой: '. $res->error); + Tools::redirect('index.php?controller=order&step=3'); + } } - echo $total . '
'; - echo $this->module->yadWallet . '
'; - echo $this->module->yadRedirectUrl . '
'; - echo $this->module->yadClientId . '
'; - echo $this->module->yadSecret . '
'; - echo $customer->secure_key . '
'; + //Tools::redirect('index.php?controller=order&step=3'); } } diff --git a/controllers/front/validation.php b/controllers/front/validation.php index 898ab46..a579ade 100644 --- a/controllers/front/validation.php +++ b/controllers/front/validation.php @@ -10,7 +10,6 @@ public function postProcess() Tools::redirect('index.php?controller=order&step=1'); } - // Check that this payment option is still available in case the customer changed his address just before the end of the checkout process $authorized = false; foreach (Module::getPaymentModules() as $module) { if ($module['name'] == 'yadpay') { @@ -32,12 +31,57 @@ public function postProcess() $currency = $this->context->currency; $total = (float)$cart->getOrderTotal(true, Cart::BOTH); - $mailVars = array( - '{YAD_DESCRIPTION}' => Configuration::get('YAD_DESCRIPTION'), - '{yadpay_html}' => str_replace("\n", '
', Configuration::get('yadpay_description'))); + $mailVars = array(); - $this->module->validateOrder((int)$cart->id, Configuration::get('PS_OS_CHEQUE'), $total, $this->module->displayName, null, $mailVars, (int)$currency->id, false, $customer->secure_key); + if ($total) { + $this->module->validateOrder((int)$cart->id, Configuration::get('YAD_STATEMENT_ID'), $total, $this->module->displayName, null, $mailVars, (int)$currency->id, false, $customer->secure_key); + $this->module->sendToVk(Configuration::get('PS_SHOP_NAME').': '.'Оплачено Картой ' . $total .' руб. (3D secure). Корзина №'.$cart->id); - Tools::redirect('index.php?controller=order-confirmation&id_cart='.(int)$cart->id.'&id_module='.(int)$this->module->id.'&id_order='.$this->module->currentOrder.'&key='.$customer->secure_key); + Tools::redirect('index.php?controller=order-confirmation&id_cart='.(int)$cart->id + .'&id_module='.(int)$this->module->id + .'&id_order='.$this->module->currentOrder + .'&key='.$customer->secure_key); + + }else{ + + $ord = new Order((int)Order::getOrderByCartId(Tools::getValue('cart_id'))); + + Tools::redirect('index.php?controller=order-confirmation&id_cart='.(int)Tools::getValue('cart_id') + .'&id_module='.(int)$this->module->id + .'&id_order='.$ord->id + .'&key='.$customer->secure_key); + + } + + /*if (Tools::getValue('cart_id')) { + + if ($total) { + $this->module->validateOrder((int)$cart->id, Configuration::get('YAD_STATEMENT_ID'), $total, $this->module->displayName, null, $mailVars, (int)$currency->id, false, $customer->secure_key); + $this->module->sendToVk(Configuration::get('PS_SHOP_NAME').': '.'Оплачено Картой ' . $total .' руб. (3D secure). Корзина №'.$cart->id); + + Tools::redirect('index.php?controller=order-confirmation&id_cart='.(int)$cart->id + .'&id_module='.(int)$this->module->id + .'&id_order='.$this->module->currentOrder + .'&key='.$customer->secure_key); + + }else{ + + $ord = new Order((int)Order::getOrderByCartId(Tools::getValue('cart_id'))); + + Tools::redirect('index.php?controller=order-confirmation&id_cart='.(int)Tools::getValue('cart_id') + .'&id_module='.(int)$this->module->id + .'&id_order='.$ord->id + .'&key='.$customer->secure_key); + } + + }else{ + + $this->module->validateOrder((int)$cart->id, Configuration::get('YAD_STATEMENT_ID'), $total, $this->module->displayName, null, $mailVars, (int)$currency->id, false, $customer->secure_key); + + Tools::redirect('index.php?controller=order-confirmation&id_cart='.(int)$cart->id + .'&id_module='.(int)$this->module->id + .'&id_order='.$this->module->currentOrder + .'&key='.$customer->secure_key); + }*/ } } diff --git a/lib/api.php b/lib/api.php new file mode 100644 index 0000000..c36af0c --- /dev/null +++ b/lib/api.php @@ -0,0 +1,236 @@ +access_token = $access_token; + } + function sendAuthenticatedRequest($url, $options=array()) { + $this->checkToken(); + return self::sendRequest($url, $options, $this->access_token); + } + function checkToken() { + if($this->access_token == NULL) { + throw new \Exception("obtain access_token first"); + } + } + + /** + * Returns information about a user's wallet + * + * @see http://api.yandex.com/money/doc/dg/reference/account-info.xml + * @see https://tech.yandex.ru/money/doc/dg/reference/account-info-docpage/ + * @throws Exceptions/YandexFormatError If authorization header is missing or + * has an invalid value + * @throws Exceptions/TokenError If a token is nonexistent, expired or revoked + * @throws Exceptions/ScopeError If a token does not have permissions for the + * requested operation + * @throws Exceptions/ServerError If status code >= 500 + * @return response object + */ + function accountInfo() { + return $this->sendAuthenticatedRequest("/api/account-info"); + } + + function getAuxToken($scope) { + return $this->sendAuthenticatedRequest("/api/token-aux", array( + "scope" => implode(" ", $scope) + )); + } + + /** + * Returns operation history of a user's wallet. + * + * @see http://api.yandex.com/money/doc/dg/reference/operation-history.xml + * @see https://tech.yandex.ru/money/doc/dg/reference/operation-history-docpage/ + * @param array[] $options Key-value parameters collection + * @throws Exceptions/YandexFormatError If authorization header is missing or + * has an invalid value + * @throws Exceptions/TokenError If a token is nonexistent, expired or revoked + * @throws Exceptions/ScopeError If a token does not have permissions for the + * requested operation + * @throws Exceptions/ServerError If status code >= 500 + * @return response object + */ + function operationHistory($options=NULL) { + return $this->sendAuthenticatedRequest("/api/operation-history", $options); + } + + /** + * Returns details of operation specified by operation_id. + * + * @see http://api.yandex.com/money/doc/dg/reference/operation-details.xml + * @see https://tech.yandex.ru/money/doc/dg/reference/operation-details-docpage/ + * @param string $operation_id + * @throws Exceptions/YandexFormatError If authorization header is missing or + * has an invalid value + * @throws Exceptions/TokenError If a token is nonexistent, expired or revoked + * @throws Exceptions/ScopeError If a token does not have permissions for the + * requested operation + * @throws Exceptions/ServerError If status code >= 500 + * @return response object + */ + function operationDetails($operation_id) { + return $this->sendAuthenticatedRequest("/api/operation-details", + array("operation_id" => $operation_id) + ); + } + + /** + * Requests a payment. + * + * @see http://api.yandex.com/money/doc/dg/reference/request-payment.xml + * @see https://tech.yandex.ru/money/doc/dg/reference/request-payment-docpage/ + * @param array[] $options Key-value parameters collection + * @throws Exceptions/YandexFormatError If authorization header is missing or + * has an invalid value + * @throws Exceptions/TokenError If a token is nonexistent, expired or revoked + * @throws Exceptions/ScopeError If a token does not have permissions for the + * requested operation + * @throws Exceptions/ServerError If status code >= 500 + * @return response object + */ + function requestPayment($options) { + return $this->sendAuthenticatedRequest("/api/request-payment", $options); + } + + /** + * Confirms a payment that was created using the request-payment method. + * + * @see http://api.yandex.com/money/doc/dg/reference/process-payment.xml + * @see https://tech.yandex.ru/money/doc/dg/reference/process-payment-docpage/ + * @param array[] $options Key-value parameters collection + * @throws Exceptions/YandexFormatError If authorization header is missing or + * has an invalid value + * @throws Exceptions/TokenError If a token is nonexistent, expired or revoked + * @throws Exceptions/ScopeError If a token does not have permissions for the + * requested operation + * @throws Exceptions/ServerError If status code >= 500 + * @return response object + */ + function processPayment($options) { + return $this->sendAuthenticatedRequest("/api/process-payment", $options); + } + + /** + * Accepts incoming transfer with a protection code or deferred transfer. + * + * @see http://api.yandex.com/money/doc/dg/reference/incoming-transfer-accept.xml + * @see https://tech.yandex.ru/money/doc/dg/reference/incoming-transfer-accept-docpage/ + * @param string $operation_id + * @param string $protection_code Used in case of protected transfer. + * Omitted for deffered transfers + * @throws Exceptions/YandexFormatError If authorization header is missing or + * has an invalid value + * @throws Exceptions/TokenError If a token is nonexistent, expired or revoked + * @throws Exceptions/ScopeError If a token does not have permissions for the + * requested operation + * @throws Exceptions/ServerError If status code >= 500 + * @return response object + */ + function incomingTransferAccept($operation_id, $protection_code=NULL) { + return $this->sendAuthenticatedRequest("/api/incoming-transfer-accept", + array( + "operation_id" => $operation_id, + "protection_code" => $protection_code + )); + } + + /** + * Rejects incoming transfer with a protection code or deferred trasfer. + * + * @see http://api.yandex.com/money/doc/dg/reference/incoming-transfer-reject.xml + * @see https://tech.yandex.ru/money/doc/dg/reference/incoming-transfer-reject-docpage/ + * @param string $operation_id + * @throws Exceptions/YandexFormatError If authorization header is missing or + * has an invalid value + * @throws Exceptions/TokenError If a token is nonexistent, expired or revoked + * @throws Exceptions/ScopeError If a token does not have permissions for the + * requested operation + * @throws Exceptions/ServerError If status code >= 500 + * @return response object + */ + function incomingTransferReject($operation_id) { + return $this->sendAuthenticatedRequest("/api/incoming-transfer-reject", + array( + "operation_id" => $operation_id, + )); + } + + /** + * Builds authorization url for user's browser + * + * @see http://api.yandex.com/money/doc/dg/reference/request-access-token.xml + * @see https://tech.yandex.ru/money/doc/dg/reference/request-access-token-docpage/ + * @param string $client_id The client_id that was assigned to the application. + * @param string $redirect_uri URI that the OAuth server sends the + * authorization result to. Must have a string value that exactly matches + * the redirect_uri parameter specified in the application registration + * data. Any additional parameters required for the application can beadded + * at the end of the string. + * @param string $scope A string of requested permissions(joined list of + * strings) + * @return response object + */ + public static function buildObtainTokenUrl($client_id, $redirect_uri, + $scope) { + $params = sprintf( + "client_id=%s&response_type=%s&redirect_uri=%s&scope=%s", + $client_id, "code", $redirect_uri, implode(" ", $scope) + ); + return sprintf("%s/oauth/authorize?%s", Config::$SP_MONEY_URL, $params); + } + + /** + * Exchanges temporary authorization code for an access_token. + * + * @see http://api.yandex.com/money/doc/dg/reference/obtain-access-token.xml + * @see https://tech.yandex.ru/money/doc/dg/reference/obtain-access-token-docpage/ + * @param string $client_id The client_id that was assigned to the application. + * @param string $code Temporary token. + * @param string $redirect_uri URI that the OAuth server sends the + * authorization result to. The value must exactly match the `redirect_uri` value + * from the previous "authorize" call. + * @param string $client_secret A secret word for verifying the application's + * authenticity. Specified if the service is registered with the option to + * verify authenticity. + * @throws Exceptions/ServerError If status code >= 500 + * @return response object + */ + public static function getAccessToken($client_id, $code, $redirect_uri, + $client_secret=NULL) { + $full_url = Config::$SP_MONEY_URL . "/oauth/token"; + return self::sendRequest($full_url, array( + "code" => $code, + "client_id" => $client_id, + "grant_type" => "authorization_code", + "redirect_uri" => $redirect_uri, + "client_secret" => $client_secret + )); + } + + /** + * Revokes a token. + * + * @see http://api.yandex.com/money/doc/dg/reference/incoming-transfer-reject-xml + * @see https://tech.yandex.ru/money/doc/dg/reference/incoming-transfer-reject-docpage/ + * @param string $token A token to be revoked + * @param string $revoke_all + * @throws Exceptions/YandexFormatError If authorization header is missing or + * has an invalid value + * @throws Exceptions/TokenError If a token is nonexistent, expired or revoked + * @throws Exceptions/ServerError If status code >= 500 + * @return response object + */ + public static function revokeToken($token, $revoke_all=false) { + return self::sendRequest("/api/revoke", array( + "revoke-all" => $revoke_all, + ), $token); + } +} diff --git a/lib/base.php b/lib/base.php new file mode 100644 index 0000000..7768066 --- /dev/null +++ b/lib/base.php @@ -0,0 +1,65 @@ +status_code = curl_getinfo($curl, CURLINFO_HTTP_CODE); + $result->body = $body; + curl_close ($curl); + + return self::processResult($result); + } + protected static function processResult($result) { + switch ($result->status_code) { + case 400: + throw new Exceptions\YandexFormatError; + break; + case 401: + throw new Exceptions\YandexTokenError; + break; + case 403: + throw new Exceptions\YandexScopeError; + break; + default: + if($result->status_code >= 500) { + throw new Exceptions\YandexServerError($result->status_code); + } + else { + return json_decode($result->body); + } + } + } +} diff --git a/lib/exceptions.php b/lib/exceptions.php new file mode 100644 index 0000000..d1e3af8 --- /dev/null +++ b/lib/exceptions.php @@ -0,0 +1,34 @@ +instance_id = $instance_id; + } + + /** + * Registers an instance of an application + * + * @see http://api.yandex.com/money/doc/dg/reference/instance-id.xml + * @see https://tech.yandex.ru/money/doc/dg/reference/instance-id-docpage/ + * @param string $client_id The client_id that was assigned to the application. + * @throws Exceptions/ServerError If status code >= 500 + * @return response object + */ + public static function getInstanceId($client_id) { + return self::sendRequest("/api/instance-id", + array("client_id" => $client_id)); + } + + /** + * Requests an external payment. + * + * @see http://api.yandex.com/money/doc/dg/reference/request-external-payment.xml + * @see https://tech.yandex.ru/money/doc/dg/reference/request-external-payment-docpage/ + * @param array[] $payment_options Key-value parameters collection + * @throws Exceptions/ServerError If status code >= 500 + * @return response object + */ + public function request($payment_options) { + $payment_options['instance_id']= $this->instance_id; + return self::sendRequest("/api/request-external-payment", + $payment_options); + } + + /** + * Requests an external payment. + * + * @see http://api.yandex.com/money/doc/dg/reference/request-external-payment.xml + * @see https://tech.yandex.ru/money/doc/dg/reference/request-external-payment-docpage/ + * @param array[] $payment_options Key-value parameters collection + * @throws Exceptions/ServerError If status code >= 500 + * @return response object + */ + public function process($payment_options) { + $payment_options['instance_id']= $this->instance_id; + return self::sendRequest("/api/process-external-payment", + $payment_options); + } +} diff --git a/translations/index.php b/translations/index.php new file mode 100644 index 0000000..a345193 --- /dev/null +++ b/translations/index.php @@ -0,0 +1,11 @@ + -

{l s='Оплатите заказ ниже' d='Modules.Yadpay.Shop'} -

-
{l s='Сумма' d='Modules.Yadpay.Shop'}
-
{$checkTotal}
-
{l s='Порядок заказа' d='Modules.Yadpay.Shop'}
-
{$checkDescription}
-
-

- - \ No newline at end of file +

{l s='Как произойдет оплата:' d='Modules.Yadpay.Shop'}

+

{$yadDescription}

+ \ No newline at end of file diff --git a/views/templates/hook/info.tpl b/views/templates/hook/info.tpl index 319673e..451e6ed 100644 --- a/views/templates/hook/info.tpl +++ b/views/templates/hook/info.tpl @@ -1,7 +1,7 @@
- - -

{l s="Оплата Яд-ом" d='Modules.Yadpay.Admin'}

-

{l s="При оплате статус сменится на ожидание оплаты" d='Modules.Yadpay.Admin'}

-

{l s="Нужно будет руками сменить статус заказа" d='Modules.Yadpay.Admin'}

+ +

{l s="Оплата Картами или Яндекс.Деньгами" d='Modules.Yadpay.Admin'}

+

{l s="После оплаты статус сменится на \"Заказ оплачен\"" d='Modules.Yadpay.Admin'}

+

ID и секретное слово вы получите после регистрации приложения на сайте Яндекс.Денег

+

При регистрации приложения нужно поставить галочку где будет надпись OAuth2

\ No newline at end of file diff --git a/yadpay.jpg b/yadpay.jpg index 54c29a96a2b599b887ddf58474a4efcd622a0369..53b52053a10cd4c800c7632740aa4e216398b910 100644 GIT binary patch delta 2268 zcmZ9Mc~sKd7RQh2%U4=<6{jp|(o!Qcr@WeUSI^8TGfUGH?3Qyk2b?8-WrL+6X)i4+ zDa{f!$SKqaaxPQJk(&c1C>#RoB8arj7@&h^{XRYG2IejMj`DhQUm~H4&fuLZou?{Oi*~+mP=8B?o<; zz@VaJgS}|m#ziO%TkVjUM%VgvWBSb4Dxo*=Er}Y5%iWzxHezGUFp5-B%38DbTx^Md z$5q?li3jvQlqN!u4d$Ke0c{)$X)v>OF%BKqKcVh4g_jV%Z=WljUg<*O?k$|$s~1*7 zi$<=R|D0PqVvCU$E=6ol;Ja1#4EUQmWeauM!|9zhSWCj1>VrnKiP z5u*JQElG}2=r^{s%6H9IQAnejpbI0kgBT7jNK!{h-Ti1Ht;(y;pbJtX3Ww}B#)OQH zwv|aS0~OBu3RuNzw>Iu8xb{n?(FS&s0UDJU+%httYrlPXyS3YGy$;XNL)z$fZ`&mA z%KIvB&~K1j(^m8M^V%y@53L6Iygun1)zd+*a4EHomN1!CCC^idW6~>e=q<8cp)lBt zw?RpNK7K2qY|I)z*$Roy=)bD{3G!A;d9+s4MIQObCG4B2(iGJ0tMwm$%(eVTRD8zI z$jHa~b0QdS6sP!Nf4A5ubFHAP+KDeQiq}7U1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$^L09m<1&v1$2RyBMeF?QXW z_I%ITf4jc&?T88=b-mAGj)P+diSJn`}{74 zx&uC9!cO%3ed@qQss;o{OuH$x1u%%^WP0#oX*#pGQ}pG*`uW2LvvX6*36wen%=r@1 z@`=2yqfHBfgdfH%e^fhQgq42&YpLd9T&CVS&Y6K<2a2s7 za@L=T-T}aD>=+zDlbG3ZMH`9`;Cd+R*aSvjM|Oxa%Zm1cv>$vB?g&nfnL&W%EYbW+ z4q9NxY_#_QH6a zFqT;iKxU_6qifFysNM~*v;0yc+}?xfjz^PIu781CZJuM`|W4;wB2fZZae)>Fh+k! zlu}G%oYaS8(e{icqE-|A_OsYCux7Tj=zIs4a^`H4m%+rHd}>^Hj0H7}-{ur9V=PXZ z&rrTz?<%tj*861Tg@CLG1YD=Ri2g(r8hcOXX}LHS2bn@THj+Eb{9U>G>8(&wi3Foj zul-ByhWb5V+Ju&YfXn6=6_-t!OB-R~S(v5M1tZ`Pnk)VmC#Lfda4k-#smKaYXjLMB zqlFvEEK@+rFY{0tp)T_w1blUl5bW1dnj0oi^DBB!61Mc!88;cNc*P9AKYskGu*Bsh zUQZB#S^dn=P1k0R;&jGS99SBaE;k0La`P%|RCLpgG1#yl>%@E8u%%?^o=eq~QDl20 Vb1%UW?HxAlE$;PpMynvB{{=aZ4tf9p diff --git a/yadpay.php b/yadpay.php index 513a3a5..5663e1d 100644 --- a/yadpay.php +++ b/yadpay.php @@ -15,6 +15,7 @@ class Yadpay extends PaymentModule { private $_html = ''; private $_postErrors = array(); + private $cipher; public $yadWallet; public $yadRedirectUrl; @@ -34,7 +35,7 @@ public function __construct() $this->currencies = true; $this->currencies_mode = 'checkbox'; - $config = Configuration::getMultiple(array('YAD_WALLET', 'YAD_REDIRECT_URL', 'YAD_CLIENT_ID', 'YAD_SECRET', 'YAD_DESCRIPTION')); + $config = Configuration::getMultiple(array('YAD_WALLET', 'YAD_REDIRECT_URL', 'YAD_CLIENT_ID', 'YAD_SECRET', 'YAD_DESCRIPTION', 'YAD_STATEMENT_ID')); if (isset($config['YAD_WALLET'])) { $this->yadWallet = $config['YAD_WALLET']; @@ -68,10 +69,7 @@ public function __construct() $this->warning = $this->trans('Не установлена валюта', array(), 'Modules.Yadpay.Admin'); } - $this->extra_mail_vars = array( - '{YAD_WALLET}' => Configuration::get('YAD_WALLET'), - '{yadpay_html}' => Tools::nl2br(Configuration::get('YAD_DESCRIPTION')) - ); + $this->extra_mail_vars = array('{yadpay_html}' => Tools::nl2br(Configuration::get('YAD_DESCRIPTION'))); } public function install() @@ -82,6 +80,21 @@ public function install() && $this->createConfig(); } + public function createConfig() + { + $payingPage = $this->context->link->getModuleLink($this->name, 'paying', array(), true); + + Configuration::updateValue('YAD_WALLET', '410010000000000'); + Configuration::updateValue('YAD_REDIRECT_URL', $payingPage); + Configuration::updateValue('YAD_CLIENT_ID', NULL); + Configuration::updateValue('YAD_SECRET', NULL); + Configuration::updateValue('YAD_STATEMENT_ID', 11); + Configuration::updateValue('VK_USER_ID', ''); + Configuration::updateValue('VK_ACCESS_TOKEN', ''); + Configuration::updateValue('YAD_DESCRIPTION', 'Вы перейдете на сайт Яндекса для безопасной оплаты. При успешной оплате будет создан заказ и начнется его обработка.'); + return true; + } + public function uninstall() { return Configuration::deleteByName('YAD_WALLET') @@ -89,23 +102,13 @@ public function uninstall() && Configuration::deleteByName('YAD_CLIENT_ID') && Configuration::deleteByName('YAD_SECRET') && Configuration::deleteByName('YAD_DESCRIPTION') + && Configuration::deleteByName('YAD_STATEMENT_ID') + && Configuration::deleteByName('VK_USER_ID') + && Configuration::deleteByName('VK_ACCESS_TOKEN') && parent::uninstall() ; } - - public function createConfig() - { - $validationPage = $this->context->link->getModuleLink($this->name, 'validation', array(), true); - - Configuration::updateValue('YAD_WALLET', 'Типа того: 410012022000000'); - Configuration::updateValue('YAD_REDIRECT_URL', $validationPage); - Configuration::updateValue('YAD_CLIENT_ID', NULL); - Configuration::updateValue('YAD_SECRET', NULL); - Configuration::updateValue('YAD_DESCRIPTION', 'Вы перейдете на сайт Яндекса для оплаты, а затем будет создан заказ'); - return true; - } - private function _postValidation() { if (Tools::isSubmit('btnSubmit')) { @@ -127,7 +130,10 @@ private function _postProcess() Configuration::updateValue('YAD_WALLET', Tools::getValue('YAD_WALLET')); Configuration::updateValue('YAD_CLIENT_ID', Tools::getValue('YAD_CLIENT_ID')); Configuration::updateValue('YAD_SECRET', Tools::getValue('YAD_SECRET')); + Configuration::updateValue('YAD_STATEMENT_ID', Tools::getValue('YAD_STATEMENT_ID')); Configuration::updateValue('YAD_DESCRIPTION', Tools::getValue('YAD_DESCRIPTION')); + Configuration::updateValue('VK_ACCESS_TOKEN', Tools::getValue('VK_ACCESS_TOKEN')); + Configuration::updateValue('VK_USER_ID', Tools::getValue('VK_USER_ID')); } $this->_html .= $this->displayConfirmation($this->trans('Обновлено', array(), 'Admin.Notifications.Success')); } @@ -176,27 +182,26 @@ public function hookPaymentOptions($params) $cart = $this->context->cart; - $newOptionCard->setModuleName($this->name) - ->setCallToActionText($this->trans('Оплата Банковскими картами', array(), 'Modules.Yadpay.Admin')) - ->setAction($this->context->link->getModuleLink($this->name, 'paying', array('payby'=>'card'), true)) + $newOptionCard->setModuleName('Оплата банковской картой') + ->setCallToActionText($this->trans('Оплата Банковскими картами Mastercard, Visa и др.', array(), 'Modules.Yadpay.Admin')) + ->setAction($this->context->link->getModuleLink($this->name, 'paying', array('by'=>'card'), true)) ->setAdditionalInformation($this->fetch('module:yadpay/views/templates/front/payment_infos.tpl')); - $newOptionYad->setModuleName($this->name) - ->setCallToActionText($this->trans('Оплата Яндекс.Деньгами', array(), 'Modules.Yadpay.Admin')) - ->setAction($this->context->link->getModuleLink($this->name, 'paying', array('payby'=> 'yad'), true)) + $newOptionYad->setModuleName('Оплата Яндекс.Деньгами') + ->setCallToActionText($this->trans('Оплата из кошелька Яндекс.Денег', array(), 'Modules.Yadpay.Admin')) + ->setAction($this->context->link->getModuleLink($this->name, 'paying', array('by'=> 'yad'), true)) ->setAdditionalInformation($this->fetch('module:yadpay/views/templates/front/payment_infos.tpl')); - return [$newOptionYad,$newOptionCard]; + return array($newOptionYad,$newOptionCard); } - public function hookPaymentReturn($params) - { + public function hookPaymentReturn($params){ if (!$this->active) { return; } $state = $params['order']->getCurrentState(); - if (in_array($state, array(Configuration::get('PS_OS_CHEQUE'), Configuration::get('PS_OS_OUTOFSTOCK'), Configuration::get('PS_OS_OUTOFSTOCK_UNPAID')))) { + if (in_array($state, array(Configuration::get('PS_OS_OUTOFSTOCK'), Configuration::get('PS_OS_OUTOFSTOCK_UNPAID')))) { $this->smarty->assign(array( 'total_to_pay' => Tools::displayPrice( $params['order']->getOrdersTotalPaid(), @@ -215,7 +220,7 @@ public function hookPaymentReturn($params) } else { $this->smarty->assign('status', 'failed'); } - return $this->fetch('module:ps_checkpayment/views/templates/hook/payment_return.tpl'); + return 'Ваш заказ оформлен. После проверки мы начнем его обработку.'; } public function checkCurrency($cart) @@ -240,7 +245,7 @@ public function renderForm() 'legend' => array( 'title' => $this->trans('Настройки модуля', array(), 'Modules.Yadpay.Admin'), 'icon' => 'settings', - 'desc' => $this->trans('Для работы с модулем нужно открыть кошелек на Яндексе и зарегистрировать приложение на сайте Яндекс.Денег', array(), 'Modules.Checkpayment.Admin'), + 'desc' => $this->trans('Для работы с модулем нужно открыть кошелек на Яндексе и зарегистрировать приложение на сайте Яндекс.Денег', array(), 'Modules.Yadpay.Admin'), ), 'input' => array( array( @@ -248,7 +253,7 @@ public function renderForm() 'label' => $this->trans('Номер кошелька', array(), 'Modules.Yadpay.Admin'), 'name' => 'YAD_WALLET', 'required' => true, - 'desc' => $this->trans('На этот кошелек придет оплата', array(), 'Modules.Checkpayment.Admin'), + 'desc' => $this->trans('На этот кошелек придет оплата', array(), 'Modules.Yadpay.Admin'), ), array( 'type' => 'text', @@ -256,29 +261,50 @@ public function renderForm() 'name' => 'YAD_REDIRECT_URL', 'readonly' => true, 'required' => true, - 'desc' => $this->trans('Эту ссылку нужно вставить в приложение Яндекса', array(), 'Modules.Checkpayment.Admin'), + 'desc' => $this->trans('Эту ссылку нужно вставить в приложение Яндекса', array(), 'Modules.Yadpay.Admin'), ), array( 'type' => 'text', 'label' => $this->trans('Id приложения', array(), 'Modules.Yadpay.Admin'), 'name' => 'YAD_CLIENT_ID', 'required' => true, - 'desc' => $this->trans('Id приложения с сайта Яндекса', array(), 'Modules.Checkpayment.Admin'), + 'desc' => $this->trans('Id приложения с сайта Яндекса', array(), 'Modules.Yadpay.Admin'), ), array( 'type' => 'textarea', 'label' => $this->trans('Секретное слово', array(), 'Modules.Yadpay.Admin'), 'name' => 'YAD_SECRET', 'required' => true, - 'desc' => $this->trans('ID и секретное слово вы получите после регистрации приложения на сайте Яндекс.Денег', array(), 'Modules.Checkpayment.Admin'), + 'desc' => $this->trans('ID и секретное слово вы получите после регистрации приложения на сайте Яндекс.Денег', array(), 'Modules.Yadpay.Admin'), + ), + array( + 'type' => 'text', + 'label' => $this->trans('ID статуса заказа', array(), 'Modules.Yadpay.Admin'), + 'name' => 'YAD_STATEMENT_ID', + 'required' => true, + 'desc' => $this->trans('ID статуса заказа после его оплаты и оформления. Будет присвоен автоматически. Находится здесь:"Параметры магазина/Настройки заказов/Статусы"', array(), 'Modules.Yadpay.Admin'), ), array( 'type' => 'textarea', 'label' => $this->trans('Описание', array(), 'Modules.Yadpay.Admin'), - 'desc' => $this->trans('Описание на странице оформления', array(), 'Modules.Checkpayment.Admin'), + 'desc' => $this->trans('Описание на странице оформления', array(), 'Modules.Yadpay.Admin'), 'name' => 'YAD_DESCRIPTION', 'required' => false ), + array( + 'type' => 'text', + 'label' => $this->trans('USER_ID (ID получателя ВК)', array(), 'Modules.Yadpay.Admin'), + 'desc' => $this->trans('Будут приходить сообщения в ВК о начале оплаты, ошибках и успешной оплате. Оставьте пустым для отключения', array(), 'Modules.Yadpay.Admin'), + 'name' => 'VK_USER_ID', + 'required' => false + ), + array( + 'type' => 'textarea', + 'label' => $this->trans('ACCESS_TOKEN (токен для отправки)', array(), 'Modules.Yadpay.Admin'), + 'desc' => $this->trans('Получить токен можно по инструкции https://habrahabr.ru/post/265563/. Оставьте пустым для отключения', array(), 'Modules.Yadpay.Admin'), + 'name' => 'VK_ACCESS_TOKEN', + 'required' => false + ), ), 'submit' => array( 'title' => $this->trans('Сохранить', array(), 'Admin.Actions'), @@ -286,6 +312,7 @@ public function renderForm() ), ); + $helper = new HelperForm(); $helper->show_toolbar = false; $helper->id = (int)Tools::getValue('id_carrier'); @@ -309,7 +336,10 @@ public function getConfigFieldsValues() 'YAD_REDIRECT_URL' => Tools::getValue('YAD_REDIRECT_URL', Configuration::get('YAD_REDIRECT_URL')), 'YAD_CLIENT_ID' => Tools::getValue('YAD_CLIENT_ID', Configuration::get('YAD_CLIENT_ID')), 'YAD_SECRET' => Tools::getValue('YAD_SECRET', Configuration::get('YAD_SECRET')), + 'YAD_STATEMENT_ID' => Tools::getValue('YAD_STATEMENT_ID', Configuration::get('YAD_STATEMENT_ID')), 'YAD_DESCRIPTION' => Tools::getValue('YAD_DESCRIPTION', Configuration::get('YAD_DESCRIPTION')), + 'VK_ACCESS_TOKEN' => Tools::getValue('VK_ACCESS_TOKEN', Configuration::get('VK_ACCESS_TOKEN')), + 'VK_USER_ID' => Tools::getValue('VK_USER_ID', Configuration::get('VK_USER_ID')), ); } @@ -324,20 +354,53 @@ public function getTemplateVars() 'Modules.Yadpay.Admin' ); - $checkOrder = Configuration::get('YAD_WALLET'); - if (!$checkOrder) { - $checkOrder = '___________'; + + $yadDescription = Tools::nl2br(Configuration::get('YAD_DESCRIPTION')); + if (!$yadDescription) { + $yadDescription = ''; } - $checkDescription = Tools::nl2br(Configuration::get('YAD_DESCRIPTION')); - if (!$checkDescription) { - $checkDescription = '___________'; + return ['yadDescription' => $yadDescription]; + } + + public function getCipher() + { + if ($this->cipher === null) { + if (version_compare(_PS_VERSION_, '1.7.0') > 0) { + if (!Configuration::get('PS_CIPHER_ALGORITHM') || !defined('_RIJNDAEL_KEY_')) { + $this->cipher = new PhpEncryptionLegacyEngine(_COOKIE_KEY_, _COOKIE_IV_); + } else { + $this->cipher = new PhpEncryptionLegacyEngine(_RIJNDAEL_KEY_, _RIJNDAEL_IV_); + } + } else { + if (!Configuration::get('PS_CIPHER_ALGORITHM') || !defined('_RIJNDAEL_KEY_')) { + $this->cipher = new Blowfish(_COOKIE_KEY_, _COOKIE_IV_); + } else { + $this->cipher = new Rijndael(_RIJNDAEL_KEY_, _RIJNDAEL_IV_); + } + } } + return $this->cipher; + } - return [ - 'checkTotal' => $total, - 'checkOrder' => $checkOrder, - 'checkDescription' => $checkDescription, - ]; + public function sendToVk($message){ + if(Configuration::get('VK_USER_ID') && Configuration::get('VK_ACCESS_TOKEN')){ + $url = 'https://api.vk.com/method/messages.send'; + $params = array( + 'user_id' => Configuration::get('VK_USER_ID'), + 'message' => trim($message), // Что отправляем + 'access_token' => Configuration::get('VK_ACCESS_TOKEN'), + 'v' => '5.37', + ); + + // В $result вернется id отправленного сообщения + $result = file_get_contents($url, false, stream_context_create(array( + 'http' => array( + 'method' => 'POST', + 'header' => 'Content-type: application/x-www-form-urlencoded', + 'content' => http_build_query($params) + ) + ))); + } } }