diff --git a/README.md b/README.md new file mode 100644 index 0000000..787b579 --- /dev/null +++ b/README.md @@ -0,0 +1,37 @@ +# WHMCS DOKU HOSTED PAYMENT MODULE # + +DOKU ❤️ WHMCS ! Let your WHMCS store integrated with DOKU payment gateway. + +## Description ## + +DOKU payment gateway is an online payment gateway. We strive to make payments simple for both the merchant and customers. +With this plugin you can accept online payment on your WHMCS using DOKU payment gateway. + +### Minimum Requirements ### + +- WHMCS v7.2.3 or WHMCS v7.x +- PHP version 5.5.x or greater +- MySQL version 5.0 or greater + +### Installation ### + +1. Download the modules from this repository. +2. Extract Whmcs-master.zip file you have previously downloaded. +3. Upload & merged module folder that you have extracted into your WHMCS directory. + +## Installation & Configuration ## + +1. Access your WHMCS admin page. +2. Go to menu Setup -> Payments -> Payment Gateways. +3. Click DOKU Hosted as payment method. +4. Then choose Setup -> Payments -> Payment Gateways -> Manage Existing Gateways +5. Fill the input as instructed on the screen. +6. Click Save Changes + +#### NOTES #### + +* Please note that our this our payment modules not using `composer.json` +* Add the url on the admin panel to cron on your WHMCS hosted for check status payment process. +* In order to use this module please register at [DOKU Website](https://www.doku.com) to get an API. + +Further infornation about DOKU, please check our website on [DOKU Website](https://www.doku.com) \ No newline at end of file diff --git a/modules/gateways/.gitignore b/modules/gateways/.gitignore new file mode 100644 index 0000000..c9e8e8d --- /dev/null +++ b/modules/gateways/.gitignore @@ -0,0 +1,28 @@ +# Composer files +composer.phar +vendor/ + +# Local configs +config/autoload/*.local.php + +# Binary gettext files +*.mo + +# Data +data/logs/ +data/cache/ +data/sessions/ +data/tmp/ +temp/ + +#Doctrine 2 +data/DoctrineORMModule/Proxy/ +data/DoctrineORMModule/cache/ + + +# Legacy ZF1 +demos/ +extras/documentation + +# IGNORE .vscode +.vscode/ diff --git a/modules/gateways/callback/dokuhosted.php b/modules/gateways/callback/dokuhosted.php new file mode 100644 index 0000000..b877533 --- /dev/null +++ b/modules/gateways/callback/dokuhosted.php @@ -0,0 +1,1108 @@ +setTimezone(new DateTimeZone("Asia/Bangkok")); +if (((int)$Datezone->format('His') >= 85959) && ((int)$Datezone->format('His') <= 225959)) { + $Void_Enabled = (isset($gatewayParams['Void-Enabled']) ? $gatewayParams['Void-Enabled'] : ''); + $Void_Enabled = (!is_array($Void_Enabled) ? trim($Void_Enabled) : ''); + $Void_Enabled = ((strtolower($Void_Enabled) === strtolower('on')) ? TRUE : FALSE); +} else { + $Void_Enabled = FALSE; +} +// Constant disabled VOID +$Void_Enabled = FALSE; +//------------------------------------------------------------------------------------------------ +$LocalApiAdminUsername = (isset($gatewayParams['Local-Api-Admin-Username']) ? $gatewayParams['Local-Api-Admin-Username'] : ''); +$Log_Enabled = FALSE; +if (isset($gatewayParams['Log-Enabled'])) { + $Log_Enabled = ((strtolower($gatewayParams['Log-Enabled']) == 'on') ? TRUE : FALSE); +} +$PaymentCheck_Enabled = (isset($gatewayParams['PaymentCheck-Enabled']) ? $gatewayParams['PaymentCheck-Enabled'] : ''); +$PaymentCheck_Enabled = ((strtolower($PaymentCheck_Enabled) === strtolower('on')) ? TRUE : FALSE); +// Die if module is not active. +if (!$gatewayParams['type']) { + die("Module Not Activated"); +} +$Environment = (isset($gatewayParams['Environment']) ? $gatewayParams['Environment'] : 'sandbox'); // Let sandbox as default +$DokuConfigs = array( + 'isofile' => 'dokuhosted/assets/iso3166.json', + 'merchant' => array( + 'mallid' => (isset($gatewayParams['MallId']) ? $gatewayParams['MallId'] : ''), + 'shopname' => (isset($gatewayParams['ShopName']) ? $gatewayParams['ShopName'] : ''), + 'chainmerchant' => (isset($gatewayParams['ChainMerchant']) ? $gatewayParams['ChainMerchant'] : ''), + 'sharedkey' => (isset($gatewayParams['SharedKey']) ? $gatewayParams['SharedKey'] : ''), + ), + 'endpoint' => (is_string($Environment) ? strtolower($Environment) : 'sandbox'), // sandbox as default +); +if (class_exists('dokuhosted_DokuPayment')) { + $DokuPayment = new dokuhosted_DokuPayment($DokuConfigs); +} else { + require_once($dokulib); + $DokuPayment = new dokuhosted_DokuPayment($DokuConfigs); +} +// Getting URL Querystring +$doku_get = dokuhosted_DokuPayment::_GET(); +// Make Global @CallbackPage +$CallbackPage = (isset($doku_get['page']) ? $doku_get['page'] : 'notify'); // notify as default-callback-page +$CallbackPage = (is_string($CallbackPage) ? strtolower($CallbackPage) : 'notify'); +/* +*************************************************************************** +* +* IF IPN : $doku_ipn_params +* IF Redirect : $doku_redirect_params +* +*************************************************************************** +*/ +$REQUEST_METHOD = (isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : 'HEAD'); +$REQUEST_METHOD_MSG = ""; +# Get Doku IPN Params: +$doku_ipn_params = $DokuPayment->doku_incoming_callback(); +if ($Log_Enabled) { logTransaction($gatewayParams['paymentmethod'], $doku_ipn_params, "({$REQUEST_METHOD}) Incoming Callback Params"); } +# Get Doku Redirect Params from Request-Uri +$doku_redirect_params = dokuhosted_DokuPayment::get_query_string(); +################################ +//------------------------------ +// Global Validation +$doku_error = FALSE; +$doku_error_msg = array(); +// Make GLOBAL @success +$success = FALSE; +//------------------------------ +// Make GLOBAL @checkCbTransID +$checkCbTransID = FALSE; +// Previously get 500 Internal Error for this transaction: checkCbTransID($transactionId); +// Make GLOBAL @XMLPaymentStatus +$XMLPaymentStatus = array(); +if ($EDU_Enabled > 0) { + $XMLPaymentStatus['edu-enabled'] = $EDU_Enabled; +} else { + $XMLPaymentStatus['edu-enabled'] = 0; +} +// Make GLOBAL @StringVoidStatus +$StringVoidStatus = ""; +/* +// Use localAPI to handle and redirect user +*/ +$localApi = array( + 'command' => 'GetInvoice', //'GetOrders', + 'data' => array( + //'id' => '', // Later updated on review case + 'invoiceid' => '', # Later updated on review case + ), + 'username' => $LocalApiAdminUsername, // Optional for WHMCS 7.2 and later +); +//------------------------------ +################################ +switch (strtolower($CallbackPage)) { + //------------------ + // Debug Invoice + //------------------ + case 'debug': + $invoiceId = (isset($doku_redirect_params['id']) ? $doku_redirect_params['id'] : ''); + $invoiceId = (int)$invoiceId; + $cbInvoiceId = checkCbInvoiceID($invoiceId, $gatewayParams['paymentmethod']); + if ($invoiceId) { + echo "
";
+			echo "{$invoiceId}";
+			echo "
"; + echo $cbInvoiceId; + echo "
"; + if (isset($localApi['data']['id'])) { + unset($localApi['data']['id']); + } + $data = array( + //'id' => $invoiceId, + 'invoiceid' => $invoiceId, + ); + $InvoiceData = localAPI('GetInvoice', $data, $localApi['username']); + print_r($InvoiceData); + } + exit; + break; + case 'identify': + if ($_SERVER['REQUEST_METHOD'] == 'POST') { + if (count($doku_ipn_params['body']) > 0) { + # DOKU Identify + $dokuparams = array( + 'TRANSIDMERCHANT' => (isset($doku_ipn_params['body']['TRANSIDMERCHANT']) ? $doku_ipn_params['body']['TRANSIDMERCHANT'] : ''), + 'PURCHASECURRENCY' => (isset($doku_ipn_params['body']['PURCHASECURRENCY']) ? $doku_ipn_params['body']['PURCHASECURRENCY'] : ''), + 'CURRENCY' => (isset($doku_ipn_params['body']['CURRENCY']) ? $doku_ipn_params['body']['CURRENCY'] : ''), + 'PAYMENTCHANNEL' => (isset($doku_ipn_params['body']['PAYMENTCHANNEL']) ? $doku_ipn_params['body']['PAYMENTCHANNEL'] : ''), + 'PAYMENTCODE' => (isset($doku_ipn_params['body']['PAYMENTCODE']) ? $doku_ipn_params['body']['PAYMENTCODE'] : ''), + 'AMOUNT' => (isset($doku_ipn_params['body']['AMOUNT']) ? $doku_ipn_params['body']['AMOUNT'] : ''), + 'SESSIONID' => (isset($doku_ipn_params['body']['SESSIONID']) ? $doku_ipn_params['body']['SESSIONID'] : ''), + ); + if ($Identify_Enabled) { + if ($Log_Enabled) { + logTransaction($gatewayParams['paymentmethod'], $dokuparams, "Payment Identify"); + } + } + $REQUEST_METHOD_MSG = "IDENTIFY:Continue"; + } else { + $REQUEST_METHOD_MSG = "STOP : BODY Have no content - Identify"; + } + } else { + $REQUEST_METHOD_MSG = "STOP : POST Method Required - Identify"; + } + break; + case 'review': + $dokuparams = array(); + $REQUEST_METHOD_MSG = "Review Page - Redirect to main-page"; + // Get from Querystring + $dokuparams['TRANSIDMERCHANT'] = (isset($doku_redirect_params['TRANSIDMERCHANT']) ? $doku_redirect_params['TRANSIDMERCHANT'] : ''); + // Get from Postbody + if (count($doku_ipn_params['body']) > 0) { + $dokuparams['TRANSIDMERCHANT'] = (isset($doku_ipn_params['body']['TRANSIDMERCHANT']) ? $doku_ipn_params['body']['TRANSIDMERCHANT'] : $dokuparams['TRANSIDMERCHANT']); + } + $transaction_id_part = substr($dokuparams['TRANSIDMERCHANT'], 0, 14); + /* + if (!$doku_error) { + try { + $transaction_id_part = date_create_from_format('YmdHis', $transaction_id_part); + } catch (Exception $ex) { + $doku_error = true; + $doku_error_msg[] = "STOP : Exception error of date-created from form: {$ex->getMessage()}."; + } + } + if (!$doku_error) { + if (!strtotime(date_format($transaction_id_part, 'Y-m-d H:i:s'))) { + $doku_error = true; + $doku_error_msg[] = "STOP : Transaction id part not in Dateformat structured."; + } + } + if (!$doku_error) { + $transaction_id_part = date_format($transaction_id_part, 'YmdHis'); + $merchant_transaction = explode("{$transaction_id_part}", $dokuparams['TRANSIDMERCHANT']); + if (!isset($merchant_transaction[1])) { + $doku_error = true; + $doku_error_msg[] = "STOP : There is no Transaction-id from IPN Callback as expected: #DATETIME#TRANSID."; + } + } + */ + if (!$doku_error) { + $merchant_transaction = array( + 0 => FALSE, + 1 => $dokuparams['TRANSIDMERCHANT'], + ); + $invoiceId = trim($merchant_transaction[1]); + /** + * Validate Callback Invoice ID. + * + * Checks invoice ID is a valid invoice number. Note it will count an + * invoice in any status as valid. + * + * Performs a die upon encountering an invalid Invoice ID. + * + * Returns a normalised invoice ID. + * + * @param int $invoiceId Invoice ID + * @param string $gatewayName Gateway Name + **/ + $invoiceId = checkCbInvoiceID($invoiceId, $gatewayParams['paymentmethod']); + if (!$invoiceId) { + $doku_error = true; + $doku_error_msg[] = "STOP : Invoice Id is not found."; + if ($Log_Enabled) { + logTransaction($gatewayParams['paymentmethod'], $doku_error_msg, "InvoiceId Not Found"); + } + } + } + if (!$doku_error) { + $localApi['command'] = 'GetInvoice'; + if (isset($localApi['data']['id'])) { + unset($localApi['data']['id']); + } + $localApi['data']['invoiceid'] = $invoiceId; + $InvoiceData = localAPI($localApi['command'], $localApi['data'], $localApi['username']); + $Redirect_Url = ""; + if (isset($InvoiceData['invoiceid'])) { + if (intval($InvoiceData['invoiceid']) > 0) { + $GetConfigurationValue = localAPI('GetConfigurationValue', array('setting' => 'SystemURL'), $localApi['username']); + $Redirect_Url .= (isset($GetConfigurationValue['value']) ? $GetConfigurationValue['value'] : ''); + $Redirect_Url .= ((substr($systemUrl, -1) == '/') ? '' : '/'); + $Redirect_Url .= "viewinvoice.php?id={$invoiceId}"; + header("HTTP/1.1 301 Moved Permanently"); + header("Location: {$Redirect_Url}"); + exit; + } + } else { + $doku_error = true; + $doku_error_msg[] = "STOP : Local API Result not get invoiceid while review of InvoiceData from GetInvoice()."; + } + } + break; + case 'notify': + default: + if ($_SERVER['REQUEST_METHOD'] == 'POST') { + if (count($doku_ipn_params['body']) > 0) { + # DOKU Notify + $dokuparams = array( + 'PAYMENTDATETIME' => (isset($doku_ipn_params['body']['PAYMENTDATETIME']) ? $doku_ipn_params['body']['PAYMENTDATETIME'] : ''), + 'PURCHASECURRENCY' => (isset($doku_ipn_params['body']['PURCHASECURRENCY']) ? $doku_ipn_params['body']['PURCHASECURRENCY'] : ''), + 'LIABILITY' => (isset($doku_ipn_params['body']['LIABILITY']) ? $doku_ipn_params['body']['LIABILITY'] : ''), + 'PAYMENTCHANNEL' => (isset($doku_ipn_params['body']['PAYMENTCHANNEL']) ? $doku_ipn_params['body']['PAYMENTCHANNEL'] : ''), + 'AMOUNT' => (isset($doku_ipn_params['body']['AMOUNT']) ? $doku_ipn_params['body']['AMOUNT'] : ''), + 'PAYMENTCODE' => (isset($doku_ipn_params['body']['PAYMENTCODE']) ? $doku_ipn_params['body']['PAYMENTCODE'] : ''), + 'MCN' => (isset($doku_ipn_params['body']['MCN']) ? $doku_ipn_params['body']['MCN'] : ''), + 'WORDS' => (isset($doku_ipn_params['body']['WORDS']) ? $doku_ipn_params['body']['WORDS'] : ''), + 'RESULTMSG' => (isset($doku_ipn_params['body']['RESULTMSG']) ? $doku_ipn_params['body']['RESULTMSG'] : ''), + 'VERIFYID' => (isset($doku_ipn_params['body']['VERIFYID']) ? $doku_ipn_params['body']['VERIFYID'] : ''), + 'TRANSIDMERCHANT' => (isset($doku_ipn_params['body']['TRANSIDMERCHANT']) ? $doku_ipn_params['body']['TRANSIDMERCHANT'] : ''), + 'BANK' => (isset($doku_ipn_params['body']['BANK']) ? $doku_ipn_params['body']['BANK'] : ''), + 'STATUSTYPE' => (isset($doku_ipn_params['body']['STATUSTYPE']) ? $doku_ipn_params['body']['STATUSTYPE'] : ''), + 'APPROVALCODE' => (isset($doku_ipn_params['body']['APPROVALCODE']) ? $doku_ipn_params['body']['APPROVALCODE'] : ''), + 'EDUSTATUS' => (isset($doku_ipn_params['body']['EDUSTATUS']) ? $doku_ipn_params['body']['EDUSTATUS'] : ''), + 'THREEDSECURESTATUS' => (isset($doku_ipn_params['body']['THREEDSECURESTATUS']) ? $doku_ipn_params['body']['THREEDSECURESTATUS'] : ''), + 'VERIFYSCORE' => (isset($doku_ipn_params['body']['VERIFYSCORE']) ? $doku_ipn_params['body']['VERIFYSCORE'] : ''), + 'CURRENCY' => (isset($doku_ipn_params['body']['CURRENCY']) ? $doku_ipn_params['body']['CURRENCY'] : ''), + 'RESPONSECODE' => (isset($doku_ipn_params['body']['RESPONSECODE']) ? $doku_ipn_params['body']['RESPONSECODE'] : ''), + 'CHNAME' => (isset($doku_ipn_params['body']['CHNAME']) ? $doku_ipn_params['body']['CHNAME'] : ''), + 'BRAND' => (isset($doku_ipn_params['body']['BRAND']) ? $doku_ipn_params['body']['BRAND'] : ''), + 'VERIFYSTATUS' => (isset($doku_ipn_params['body']['VERIFYSTATUS']) ? $doku_ipn_params['body']['VERIFYSTATUS'] : ''), + 'SESSIONID' => (isset($doku_ipn_params['body']['SESSIONID']) ? $doku_ipn_params['body']['SESSIONID'] : ''), + ); + $REQUEST_METHOD_MSG = "NOTIFY:Continue"; + } else { + $REQUEST_METHOD_MSG = "STOP : BODY Have no content"; + } + } else { + $REQUEST_METHOD_MSG = "STOP : POST Method Required"; + } + break; + case 'redirect': + # DOKU Params (GET) + $dokuparams = array( + 'PAYMENTDATETIME' => (isset($doku_redirect_params['PAYMENTDATETIME']) ? $doku_redirect_params['PAYMENTDATETIME'] : ''), + 'PURCHASECURRENCY' => (isset($doku_redirect_params['PURCHASECURRENCY']) ? $doku_redirect_params['PURCHASECURRENCY'] : ''), + 'LIABILITY' => (isset($doku_redirect_params['LIABILITY']) ? $doku_redirect_params['LIABILITY'] : ''), + 'PAYMENTCHANNEL' => (isset($doku_redirect_params['PAYMENTCHANNEL']) ? $doku_redirect_params['PAYMENTCHANNEL'] : ''), + 'AMOUNT' => (isset($doku_redirect_params['AMOUNT']) ? $doku_redirect_params['AMOUNT'] : ''), + 'PAYMENTCODE' => (isset($doku_redirect_params['PAYMENTCODE']) ? $doku_redirect_params['PAYMENTCODE'] : ''), + 'MCN' => (isset($doku_redirect_params['MCN']) ? $doku_redirect_params['MCN'] : ''), + 'WORDS' => (isset($doku_redirect_params['WORDS']) ? $doku_redirect_params['WORDS'] : ''), + 'RESULTMSG' => (isset($doku_redirect_params['RESULTMSG']) ? $doku_redirect_params['RESULTMSG'] : ''), + 'VERIFYID' => (isset($doku_redirect_params['VERIFYID']) ? $doku_redirect_params['VERIFYID'] : ''), + 'TRANSIDMERCHANT' => (isset($doku_redirect_params['TRANSIDMERCHANT']) ? $doku_redirect_params['TRANSIDMERCHANT'] : ''), + 'BANK' => (isset($doku_redirect_params['BANK']) ? $doku_redirect_params['BANK'] : ''), + 'STATUSTYPE' => (isset($doku_redirect_params['STATUSTYPE']) ? $doku_redirect_params['STATUSTYPE'] : ''), + 'APPROVALCODE' => (isset($doku_redirect_params['APPROVALCODE']) ? $doku_redirect_params['APPROVALCODE'] : ''), + 'EDUSTATUS' => (isset($doku_redirect_params['EDUSTATUS']) ? $doku_redirect_params['EDUSTATUS'] : ''), + 'THREEDSECURESTATUS' => (isset($doku_redirect_params['THREEDSECURESTATUS']) ? $doku_redirect_params['THREEDSECURESTATUS'] : ''), + 'VERIFYSCORE' => (isset($doku_redirect_params['VERIFYSCORE']) ? $doku_redirect_params['VERIFYSCORE'] : ''), + 'CURRENCY' => (isset($doku_redirect_params['CURRENCY']) ? $doku_redirect_params['CURRENCY'] : ''), + 'RESPONSECODE' => (isset($doku_redirect_params['RESPONSECODE']) ? $doku_redirect_params['RESPONSECODE'] : ''), + 'CHNAME' => (isset($doku_redirect_params['CHNAME']) ? $doku_redirect_params['CHNAME'] : ''), + 'BRAND' => (isset($doku_redirect_params['BRAND']) ? $doku_redirect_params['BRAND'] : ''), + 'VERIFYSTATUS' => (isset($doku_redirect_params['VERIFYSTATUS']) ? $doku_redirect_params['VERIFYSTATUS'] : ''), + 'SESSIONID' => (isset($doku_redirect_params['SESSIONID']) ? $doku_redirect_params['SESSIONID'] : ''), + 'STATUSCODE' => (isset($doku_redirect_params['STATUSCODE']) ? $doku_redirect_params['STATUSCODE'] : ''), + ); + # DOKU Params (POST) + if (count($doku_ipn_params['body']) > 0) { + foreach ($doku_ipn_params['body'] as $key => $val) { + if (!isset($dokuparams[$key])) { + $dokuparams[$key] = $val; + } else { + if ($dokuparams[$key] != $val) { + $dokuparams[$key] = $val; + } + } + } + } + if (count($doku_redirect_params) > 0) { + $REQUEST_METHOD_MSG = "REDIRECT:Continue"; + } else { + $REQUEST_METHOD_MSG = "STOP : QUERYSTRING Have no content"; + } + break; +} +/* +** +* CONTINUE +** +*/ +switch (strtolower($CallbackPage)) { + case 'notify': + default: + if ($Log_Enabled) { logTransaction($gatewayParams['paymentmethod'], $dokuparams, 'Payment Notify From Doku'); } + break; + case 'redirect': + if ($Log_Enabled) { logTransaction($gatewayParams['paymentmethod'], $dokuparams, 'Payment Redirect From Doku'); } + break; + case 'review': + case 'identify': + echo "{$REQUEST_METHOD_MSG}"; + exit; + break; +} +/* +** +* CONTINUE +** +*/ +switch (strtolower($CallbackPage)) { + case 'review': + case 'identify': + die(); + break; + case 'notify': + case 'redirect': + default: + //-------------------------------------------------------------------- + if (!$doku_error) { + if (is_array($dokuparams['TRANSIDMERCHANT']) || is_object($dokuparams['TRANSIDMERCHANT'])) { + $doku_error = true; + $doku_error_msg[] = "STOP : Array or Object return for TRANSIDMERCHANT."; + } + } + /* + if (!$doku_error) { + $transaction_id = $dokuparams['TRANSIDMERCHANT']; + $transaction_id_part = substr($dokuparams['TRANSIDMERCHANT'], 0, 14); + try { + $transaction_id_part = date_create_from_format('YmdHis', $transaction_id_part); + } catch (Exception $ex) { + $doku_error = true; + $doku_error_msg[] = "STOP : Exception error of date-created from form: {$ex->getMessage()}."; + } + } + if (!$doku_error) { + if (!strtotime(date_format($transaction_id_part, 'Y-m-d H:i:s'))) { + $doku_error = true; + $doku_error_msg[] = "STOP : Transaction id part not in Dateformat structured."; + } + } + if (!$doku_error) { + $transaction_id_part = date_format($transaction_id_part, 'YmdHis'); + $merchant_transaction = explode("{$transaction_id_part}", $dokuparams['TRANSIDMERCHANT']); + if (!isset($merchant_transaction[1])) { + $doku_error = true; + $doku_error_msg[] = "STOP : There is no Transaction-id from IPN Callback as expected: #DATETIME#TRANSID."; + } + } + */ + ######################################### + if (!$doku_error) { + $merchant_transaction = array( + 0 => FALSE, + 1 => $dokuparams['TRANSIDMERCHANT'], + ); + $invoiceId = trim($merchant_transaction[1]); + /** + * Validate Callback Invoice ID. + * + * Checks invoice ID is a valid invoice number. Note it will count an + * invoice in any status as valid. + * + * Performs a die upon encountering an invalid Invoice ID. + * + * Returns a normalised invoice ID. + * + * @param int $invoiceId Invoice ID + * @param string $gatewayName Gateway Name + **/ + $invoiceId = checkCbInvoiceID($invoiceId, $gatewayParams['paymentmethod']); + if (!$invoiceId) { + $doku_error = true; + $doku_error_msg[] = "STOP : Invoice Id is not found."; + if ($Log_Enabled) { logTransaction($gatewayParams['paymentmethod'], $doku_error_msg, "InvoiceId Not Found"); } + } + } + ######################################## + //-------------------------------------------------------------------- + if (!$doku_error) { + $params_input = array(); + $params_input['amount'] = (isset($dokuparams['AMOUNT']) ? $dokuparams['AMOUNT'] : '0.00'); + $params_input['transaction_id'] = (isset($dokuparams['TRANSIDMERCHANT']) ? $dokuparams['TRANSIDMERCHANT'] : 0); + $params_input['transaction_session'] = (isset($dokuparams['SESSIONID']) ? $dokuparams['SESSIONID'] : ''); + $params_input['transaction_currency'] = (isset($dokuparams['CURRENCY']) ? $dokuparams['CURRENCY'] : '360'); + $params_input['result_msg'] = (isset($dokuparams['RESULTMSG']) ? $dokuparams['RESULTMSG'] : ''); // SUCCESS | FAILED + $params_input['verify_status'] = (isset($dokuparams['VERIFYSTATUS']) ? $dokuparams['VERIFYSTATUS'] : ''); // NA + $params_input['words'] = (isset($dokuparams['WORDS']) ? $dokuparams['WORDS'] : ''); + // Make notify structured + $CheckNotifyPaymentStructure = $DokuPayment->create_payment_structure('notify', 0, $params_input, $dokuparams); + if ($Log_Enabled) { logTransaction($gatewayParams['paymentmethod'], $CheckNotifyPaymentStructure, 'Payment Notify Structured: ' . (__LINE__)); } + if (!isset($CheckNotifyPaymentStructure['WORDS'])) { + $doku_error = true; + $doku_error_msg[] = "STOP : Not get WORDS string from created notify structured."; + } + } + if (!$doku_error) { + if (!is_string($params_input['words'])) { + $doku_error = true; + $doku_error_msg[] = "STOP : Words should be a string."; + } + } + //--------------------------------------------------------------------------------- + break; +} +/* +** +* CONTINUE +** +*/ +switch (strtolower($CallbackPage)) { + case 'review': + case 'identify': + die(); + break; + case 'notify': + case 'redirect': + default: + // Make more @XMLPaymentStatus params + if (count($dokuparams) > 0) { + foreach ($dokuparams as $key => $val) { + $key = preg_replace("/[^a-zA-Z0-9]+/", "", $key); + if (!empty($key) || ($key != '')) { + $XMLPaymentStatus[$key] = $val; + } + } + } + //------------------------------------ + $Redirect_Url = "/"; + if (!$doku_error) { + If (isset($localApi['data']['id'])) { + unset($localApi['data']['id']); + } + $localApi['data']['invoiceid'] = $invoiceId; + //unset($localApi['data']['invoiceid']); + //$localApi['data']['id'] = $invoiceId; + //$InvoiceData = localAPI($localApi['command'], $localApi['data'], $localApi['username']); + // query localApi from invoiceid + $InvoiceData = localAPI('GetInvoice', $localApi['data'], $localApi['username']); + if (isset($InvoiceData['invoiceid'])) { + if (intval($InvoiceData['invoiceid']) > 0) { + $GetConfigurationValue = localAPI('GetConfigurationValue', array('setting' => 'SystemURL'), $localApi['username']); + $Redirect_Url = (isset($GetConfigurationValue['value']) ? $GetConfigurationValue['value'] : ''); + $Redirect_Url .= ((substr($systemUrl, -1) == '/') ? '' : '/'); + $Redirect_Url .= "viewinvoice.php?id={$invoiceId}"; + } + } else { + $doku_error = true; + $doku_error_msg[] = "STOP : Local API Result not get invoiceid of InvoiceData from GetInvoice()."; + } + } + $orders_debug = array( + 'order_id' => 0, + 'order_num' => 0, + 'order_status' => '', + ); + $order_id = 0; + $order_num = 0; + $order_status = ''; + if (!$doku_error) { + if (isset($InvoiceData['invoiceid']) && isset($InvoiceData['invoicenum']) && isset($InvoiceData['status'])) { + if (intval($InvoiceData['invoiceid']) > 0) { + $order_id = $InvoiceData['invoiceid']; + $orders_debug['order_id'] = $order_id; + } + if (intval($InvoiceData['invoicenum']) > 0) { + $order_num = $InvoiceData['invoicenum']; + $orders_debug['order_num'] = $order_num; + } + $order_status = (is_string($InvoiceData['status']) ? strtolower($InvoiceData['status']) : ''); + $orders_debug['order_status'] = $order_status; + } else { + $doku_error = true; + $doku_error_msg[] = "STOP : Local API Result for GetInvoice() not get proper data as expected."; + } + } + break; +} +/* +** +* CONTINUE +** +*/ +switch (strtolower($CallbackPage)) { + case 'review': + case 'identify': + die(); + break; + case 'notify': + default: + // Only for Notify + if (strtolower($CallbackPage) === strtolower('notify')) { + if (!$doku_error) { + //----------------------------------------- + // check if WORDS is match or not + //----------------------------------------- + if (strtolower($CheckNotifyPaymentStructure['WORDS']) !== strtolower($params_input['words'])) { + $doku_error = true; + $doku_error_msg[] = "STOP : Words from Notify-Structured not same with Dokuparams"; + } + } + } + //------------------------------------------------------------------------------------------ + if (!$doku_error) { + //--------------------------------- + // IMPORTANT GLOBAL VARS + //--------------------------------- + $invoiceId = (isset($invoiceId) ? $invoiceId : ''); + //$transactionId = (isset($dokuparams['APPROVALCODE']) ? $dokuparams['APPROVALCODE'] : ''); + $transactionId = $invoiceId; + /** + * Adding Unique generated Invoice-Id to Transaction-Id + * Got bugs: DOKU always send: + * Constant APPROVALCODE for first time Notify (DOKU Always send same Approval-code for each invoice-id) + * Using @$transaction_id_part + */ + $transactionId .= "_"; + if (isset($dokuparams['TRANSIDMERCHANT'])) { + $explode_transid = explode("{$invoiceId}_", $dokuparams['TRANSIDMERCHANT']); + if (isset($explode_transid[1])) { + $transactionId .= sprintf("%s", $explode_transid[1]); + } + } + //$transactionId .= (isset($transaction_id_part) ? $transaction_id_part : ''); + //$transactionId .= (isset($dokuparams['APPROVALCODE']) ? $dokuparams['APPROVALCODE'] : ''); + $paymentAmount = (isset($dokuparams['AMOUNT']) ? $dokuparams['AMOUNT'] : 0); + $paymentFee = (isset($dokuparams['FEE']) ? $dokuparams['FEE'] : 0); + $paymentEDU = (isset($dokuparams['EDUSTATUS']) ? $dokuparams['EDUSTATUS'] : 'NA'); // NA (Default) + # + $paymentResponseStatus = (isset($dokuparams['RESULTMSG']) ? $dokuparams['RESULTMSG'] : ''); // SUCCESS, VOIDED, FAILED + $paymentResponseCode = (isset($dokuparams['RESPONSECODE']) ? $dokuparams['RESPONSECODE'] : ''); // 0000 (Success), Other is failed + switch (strtoupper($paymentResponseStatus)) { + case 'SUCCESS': + $success = TRUE; + if ($paymentResponseCode == '0000') { + $success = TRUE; + } else { + $success = FALSE; + $doku_error = true; + $doku_error_msg[] = "Payment Response Code is Not : 0000 from Payment-Notify."; + } + break; + case 'VOIDED': + if ($paymentResponseCode == '0000') { + $success = TRUE; + } else { + $success = FALSE; + $doku_error = true; + $doku_error_msg[] = "STOP : Payment Response Code is Not : 0000."; + } + break; + case 'FAILED': + $success = FALSE; + $doku_error = true; + $doku_error_msg[] = "STOP : Payment Response Status is not Success: {$paymentResponseStatus}."; + break; + default: + $success = FALSE; + $doku_error = true; + $doku_error_msg[] = "STOP : Un-Expected Payment-Response-Status: (" . (__LINE__) . ") {$paymentResponseStatus}"; + break; + } + } + break; + case 'redirect': + //------------------------------------------------------------------------------------------------------------- + /** + * Check Status Payment: Call DOKU + * Applied only for Redirect-Page not for First Time Notify + * ******************************************************** + */ + //------------------------------------------------------------------------------------------------------------- + if ($PaymentCheck_Enabled) { + if (strtolower($order_status) !== strtolower('paid')) { + // Should call to redirect-page + //*********************************************************************** + if (!$doku_error) { + // Make checking payment structured + # add puchase-currency + $params_input['transaction_currency_purchase'] = (isset($dokuparams['PURCHASECURRENCY']) ? $dokuparams['PURCHASECURRENCY'] : '360'); + $CheckStatusPaymentStructure = $DokuPayment->create_payment_structure('check', 0, $params_input, $dokuparams); + $headers = $DokuPayment->create_curl_headers($DokuPayment->dokupayment_headers); + if (isset($CheckStatusPaymentStructure['WORDS_STRING'])) { + unset($CheckStatusPaymentStructure['WORDS_STRING']); + } + try { + $payment_status = $DokuPayment->create_curl_request('POST', $DokuPayment->endpoint['checkstatus'], 'API.Context (http://whmcs.alumniparhata.org)', $headers, $CheckStatusPaymentStructure, 30); + } catch (Exception $ex) { + $doku_error = true; + $doku_error_msg[] = "STOP : Exception Error: {$ex->getMessage()}."; + throw $ex; + } + } + if (!$doku_error) { + if (!isset($payment_status['response']['body'])) { + $doku_error = true; + $doku_error_msg[] = "STOP : There is no body from Doku check -payment-status."; + } + } + // Format XML to Array + if (!$doku_error) { + # Log payment-status Body + //logTransaction($gatewayParams['paymentmethod'], $payment_status['response']['body'], 'Payment Status XML:' . (__LINE__)); + try { + $payment_status = $DokuPayment->xmltoarray($payment_status['response']['body']); + } catch (Exception $ex) { + $doku_error = true; + $doku_error_msg[] = "STOP : Exception Error while render xml format to array: {$ex->getMessage()}."; + throw $ex; + } + } + if (!$doku_error) { + if (!isset($payment_status['PAYMENT_STATUS'])) { + $doku_error = true; + $doku_error_msg[] = "STOP : XML Format is not-expected."; + } + } + if (!$doku_error) { + if (count($payment_status['PAYMENT_STATUS']) > 0) { + foreach ($payment_status['PAYMENT_STATUS'] as $key => $val) { + $XMLPaymentStatus[$key] = (isset($val['value']) ? $val['value'] : ''); + } + } else { + $doku_error = true; + $doku_error_msg[] = "STOP : Count payment-status not have an array."; + } + } + if (!$doku_error) { + // Make checking redirect-payment structured + # add transaction-words, transaction-status, transaction-code + $params_input['transaction_words'] = (isset($dokuparams['WORDS']) ? $dokuparams['WORDS'] : ''); + $params_input['transaction_status'] = (isset($dokuparams['STATUSCODE']) ? strval($dokuparams['STATUSCODE']) : ''); // 0000 = Success, Other = Failed + $params_input['transaction_channel'] = (isset($dokuparams['PAYMENTCHANNEL']) ? $dokuparams['PAYMENTCHANNEL'] : ''); + $CheckRedirectPaymentStructure = $DokuPayment->create_payment_structure('redirect', 0, $params_input, $dokuparams); + if (strtolower($CallbackPage) === strtolower('redirect')) { + //----------------------------------------- + // check if WORDS is match or not (On 'redirect' stage) + //----------------------------------------- + if (strtolower($params_input['transaction_words']) !== strtolower($CheckRedirectPaymentStructure['WORDS'])) { + $doku_error = true; + $doku_error_msg[] = "STOP : Words from Redirect-Structured not same with Dokuparams.
\n"; + $doku_error_msg[] .= "Input words: {$params_input['transaction_words']}
\n"; + $doku_error_msg[] .= "Structured words: {$CheckRedirectPaymentStructure['WORDS']}
\n"; + /* + $doku_error_msg['structured'] = $CheckRedirectPaymentStructure; + $doku_error_msg['input'] = $params_input; + $doku_error_msg['dokuparams'] = $dokuparams; + */ + } + } + } + if (!$doku_error) { + //--------------------------------- + // IMPORTANT GLOBAL VARS + //--------------------------------- + $invoiceId = (isset($invoiceId) ? $invoiceId : ''); + #$transactionId = (isset($XMLPaymentStatus['APPROVALCODE']) ? $XMLPaymentStatus['APPROVALCODE'] : ''); + $transactionId = $invoiceId; + // + // Adding Unique generated Invoice-Id to Transaction-Id + // Got bugs: DOKU always send: + // Constant APPROVALCODE for first time Notify (DOKU Always send same Approval-code foe each invoice-id) + // Using @$merchant_transaction[0] + // + $transactionId .= "_"; + if (isset($dokuparams['TRANSIDMERCHANT'])) { + $explode_transid = explode("{$invoiceId}_", $dokuparams['TRANSIDMERCHANT']); + if (isset($explode_transid[1])) { + $transactionId .= sprintf("%s", $explode_transid[1]); + } + } + //$transactionId .= (isset($transaction_id_part) ? $transaction_id_part : ''); + //$transactionId .= (isset($XMLPaymentStatus['APPROVALCODE']) ? $XMLPaymentStatus['APPROVALCODE'] : ''); + $paymentAmount = (isset($XMLPaymentStatus['AMOUNT']) ? $XMLPaymentStatus['AMOUNT'] : 0); + $paymentFee = (isset($XMLPaymentStatus['FEE']) ? $XMLPaymentStatus['FEE'] : 0); + $paymentEDU = (isset($XMLPaymentStatus['EDUSTATUS']) ? $XMLPaymentStatus['EDUSTATUS'] : 'NA'); // NA (Default) + # + $paymentResponseStatus = (isset($XMLPaymentStatus['RESULTMSG']) ? $XMLPaymentStatus['RESULTMSG'] : ''); // SUCCESS, VOIDED, FAILED + $paymentResponseCode = (isset($XMLPaymentStatus['RESPONSECODE']) ? $XMLPaymentStatus['RESPONSECODE'] : ''); // 0000 (Success), Other is failed + } + if (!$doku_error) { + // Log payment-status + if ($Log_Enabled) { logTransaction($gatewayParams['paymentmethod'], $XMLPaymentStatus, "(#{$invoiceId}) " . 'Payment Status Array:' . (__LINE__)); } + /* + if ($checkCbTransID) { + $doku_error = true; + $doku_error_msg[] = "checkCbTransID() Return True: Maybe duplicated transaction."; + } + */ + } + //*********************************************************************** + } else { + header("HTTP/1.1 301 Moved Permanently"); + header("Location: {$Redirect_Url}"); + exit; + } + } else { + if (!$doku_error) { + // Make checking redirect-payment structured + # add transaction-words, transaction-status, transaction-code + $params_input['transaction_words'] = (isset($dokuparams['WORDS']) ? $dokuparams['WORDS'] : ''); + $params_input['transaction_status'] = (isset($dokuparams['STATUSCODE']) ? strval($dokuparams['STATUSCODE']) : ''); // 0000 = Success, Other = Failed + $params_input['transaction_channel'] = (isset($dokuparams['PAYMENTCHANNEL']) ? $dokuparams['PAYMENTCHANNEL'] : ''); + $CheckRedirectPaymentStructure = $DokuPayment->create_payment_structure('redirect', 0, $params_input, $dokuparams); + if (strtolower($CallbackPage) === strtolower('redirect')) { + //----------------------------------------- + // check if WORDS is match or not (On 'redirect' stage) + //----------------------------------------- + if (strtolower($params_input['transaction_words']) !== strtolower($CheckRedirectPaymentStructure['WORDS'])) { + $doku_error = true; + $doku_error_msg[] = "STOP : Words from Redirect-Structured not same with Dokuparams. (" . (__LINE__) . ")"; + } + } + } + if (!$doku_error) { + if (strtolower($order_status) !== strtolower('paid')) { + //--------------------------------- + // IMPORTANT GLOBAL VARS + //--------------------------------- + $invoiceId = (isset($invoiceId) ? $invoiceId : ''); + $transactionId = $invoiceId; + // + // Adding Unique generated Invoice-Id to Transaction-Id + // Got bugs: DOKU always send: + // Constant APPROVALCODE for first time Notify (DOKU Always send same Approval-code foe each invoice-id) + // Using @$merchant_transaction[0] + // + $transactionId .= "_"; + if (isset($dokuparams['TRANSIDMERCHANT'])) { + $explode_transid = explode("{$invoiceId}_", $dokuparams['TRANSIDMERCHANT']); + if (isset($explode_transid[1])) { + $transactionId .= sprintf("%s", $explode_transid[1]); + } + } + //$transactionId .= (isset($transaction_id_part) ? $transaction_id_part : ''); + //$transactionId .= (isset($dokuparams['APPROVALCODE']) ? $dokuparams['APPROVALCODE'] : ''); + $paymentAmount = (isset($dokuparams['AMOUNT']) ? $dokuparams['AMOUNT'] : 0); + $paymentFee = (isset($dokuparams['FEE']) ? $dokuparams['FEE'] : 0); + $paymentEDU = (isset($dokuparams['EDUSTATUS']) ? $dokuparams['EDUSTATUS'] : 'NA'); // NA (Default) + # + $paymentResponseStatus = (isset($dokuparams['RESULTMSG']) ? $dokuparams['RESULTMSG'] : ''); // SUCCESS, VOIDED, FAILED + $paymentResponseCode = (isset($dokuparams['RESPONSECODE']) ? $XMLPaymentStatus['RESPONSECODE'] : $params_input['transaction_status']); // 0000 (Success), Other is failed + } else { + header("HTTP/1.1 301 Moved Permanently"); + header("Location: {$Redirect_Url}"); + exit; + } + } + if (!$doku_error) { + // Log payment-status + if ($Log_Enabled) { logTransaction($gatewayParams['paymentmethod'], $dokuparams, "(#{$invoiceId}) " . 'Payment Status From Redirected:' . (__LINE__)); } + if (strtolower($order_status) !== strtolower('paid')) { + // Make Error if Redirected from Un-Success Payment + $doku_error = true; + $doku_error_msg[] = "STOP : Redirected from failed payment: Maybe WHMCS Payment-Gateway-Module not activate payment-check status."; + } + } + } + //------------------------------------------------------------------------------------------------------------- + break; +} +/* +** +* CONTINUE +** +*/ +switch (strtolower($CallbackPage)) { + case 'review': + case 'identify': + die(); + break; + case 'notify': + case 'redirect': + default: + if (!$doku_error) { + $transactionStatus = ($success ? 'Success' : 'Failure'); + //------------------------------------------------------------------------------------------------------------------- + // EDU Enabled? + //------------------------------------------------------------------------------------------------------------------- + $transactionEdu = "EDU:APPROVE"; // DEFAULT: For not-enabled EDU + if ($success) { + if ($EDU_Enabled > 0) { + switch (strtoupper($paymentEDU)) { + case 'APPROVE': + $success = TRUE; + $transactionEdu = 'EDU:APPROVE'; + // Status: Success + break; + case 'REJECT': + $success = FALSE; + $transactionEdu = 'EDU:REJECT'; + // Status: Failed + break; + case 'NA': + $success = FALSE; + $transactionEdu = "EDU:NA"; + // Status: Pending/Waiting + break; + default: + $success = FALSE; + $transactionEdu = "EDU:{$paymentEDU}"; + // Status: Un-Expected + break; + } + } + if ($transactionEdu == 'EDU:APPROVE') { + $transactionStatus = 'Success'; + } else { + $transactionStatus = 'Pending'; + } + } + } + ############################################################################################################# + break; +} +/* +** +* CONTINUE +** +*/ +switch (strtolower($CallbackPage)) { + case 'review': + case 'identify': + die(); + break; + case 'redirect': + case 'notify': + default: + if (!$doku_error) { + if (strtolower($order_status) !== strtolower('paid')) { + //--------------------------------- + /** + * Check Callback Transaction ID. + * + * Performs a check for any existing transactions with the same given + * transaction number. + * + * Performs a die upon encountering a duplicate. + * + * @param string $transactionId Unique Transaction ID + */ + checkCbTransID($transactionId); + } + } + break; +} +/* +** +* CONTINUE +** +*/ +switch (strtolower($CallbackPage)) { + case 'review': + case 'identify': + die(); + break; + case 'redirect': + ############################################################################################################# + # CALL VOID? + ############################################################################################################# + //------------------------------------------------------------------------------------------------------------------- + if ($Void_Enabled) { + if (!$doku_error) { + $VoidParams = array( + 'transaction_id' => (isset($XMLPaymentStatus['TRANSIDMERCHANT']) ? $XMLPaymentStatus['TRANSIDMERCHANT'] : ''), + 'transaction_session' => (isset($XMLPaymentStatus['SESSIONID']) ? $XMLPaymentStatus['SESSIONID'] : ''), + 'transaction_currency' => (isset($XMLPaymentStatus['CURRENCY']) ? $XMLPaymentStatus['CURRENCY'] : '360'), + 'transaction_channel' => (isset($XMLPaymentStatus['PAYMENTCHANNEL']) ? $XMLPaymentStatus['PAYMENTCHANNEL'] : ''), + ); + $createVoidStructure = $DokuPayment->create_payment_structure('void', 0, $VoidParams, $dokuparams); + if (isset($createVoidStructure['WORDS_STRING'])) { + unset($createVoidStructure['WORDS_STRING']); + } + $headers = $DokuPayment->create_curl_headers($DokuPayment->dokupayment_headers); + try { + $create_void = $DokuPayment->create_curl_request('POST', $DokuPayment->endpoint['void'], 'API.Context (http://whmcs.alumniparhata.org) - Change this as you wish.', $headers, $createVoidStructure, 30); + } catch (Exception $ex) { + $doku_error = true; + $doku_error_msg[] = "STOP : Error exception for create void: {$ex->getMessage()}."; + throw $ex; + } + } + if (!$doku_error) { + if (!isset($create_void['response']['body'])) { + $doku_error = true; + $doku_error_msg[] = "STOP : There is no body response from Void response."; + } + } + if (!$doku_error) { + $StringVoidStatus = trim($create_void['response']['body']); + switch (strtoupper($StringVoidStatus)) { + case 'FAILED': + // Do what to do if Failed VOID + if ($Log_Enabled) { logTransaction($gatewayParams['paymentmethod'], $create_void, "Payment Void: ". strtoupper($StringVoidStatus)); } + break; + case 'SUCCESS': + // Do what to do if Success VOID + if ($Log_Enabled) { logTransaction($gatewayParams['paymentmethod'], $create_void, "Payment Void: ". strtoupper($StringVoidStatus)); } + break; + default: + // DO what to do if Un-expected VOID + if ($Log_Enabled) { logTransaction($gatewayParams['paymentmethod'], $create_void, "Payment Void: UN-EXPECTED ({$StringVoidStatus})"); } + break; + } + } + } + ############################################################################################################# + //------------------------------------------------------------------------------------------------------------------- + if (!$doku_error) { + switch (strtoupper($paymentResponseStatus)) { + case 'SUCCESS': + $success = TRUE; + break; + case 'VOIDED': + if ($paymentResponseCode == '0000') { + $success = TRUE; + } else { + $success = FALSE; + $doku_error = true; + $doku_error_msg[] = "STOP : Payment Response Code is Not : 0000."; + } + break; + case 'FAILED': + $success = FALSE; + $doku_error = true; + $doku_error_msg[] = "STOP : Payment Response Status is not Success: {$paymentResponseStatus}."; + break; + default: + $success = FALSE; + $doku_error = true; + $doku_error_msg[] = "STOP : Un-Expected Payment-Response-Status on Line (" . (__LINE__) . "): {$paymentResponseStatus}"; + $doku_error_msg['XMLPaymentStatus'] = $XMLPaymentStatus; + break; + } + } + if (!$doku_error) { + if (strtolower($order_status) !== strtolower('paid')) { + $REQUEST_METHOD_MSG = "REDIRECT:Continue"; + } else { + header("HTTP/1.1 301 Moved Permanently"); + header("Location: {$Redirect_Url}"); + exit; + } + } + break; + case 'notify': + default: + $REQUEST_METHOD_MSG = "CONTINUE"; + break; +} +/* +** +* CONTINUE +** +*/ +switch (strtolower($CallbackPage)) { + case 'redirect': + case 'notify': + default: + if (!$doku_error) { + /** + * Log Transaction. + * + * Add an entry to the Gateway Log for debugging purposes. + * + * The debug data can be a string or an array. In the case of an + * array it will be + * + * @param string $gatewayName Display label + * @param string|array $debugData Data to log + * @param string $transactionStatus Status + */ + if ($Log_Enabled) { logTransaction($gatewayParams['paymentmethod'], $XMLPaymentStatus, $transactionStatus); } + if ($success) { + /** + * Add Invoice Payment. + * + * Applies a payment transaction entry to the given invoice ID. + * + * @param int $invoiceId Invoice ID + * @param string $transactionId Transaction ID + * @param float $paymentAmount Amount paid (defaults to full balance) + * @param float $paymentFee Payment fee (optional) + * @param string $gatewayModule Gateway module name + */ + addInvoicePayment( + $invoiceId, + $transactionId, + $paymentAmount, + $paymentFee, + $gatewayModuleName + ); + } + } else { + if ($Log_Enabled) { logTransaction($gatewayParams['paymentmethod'], array('STOP' => $doku_error_msg), "(doku_error): Failed"); } + } + break; + case 'review': + case 'identify': + die(); + break; +} +/* +** +* CONTINUE +** +*/ +switch (strtolower($CallbackPage)) { + case 'review': + case 'identify': + if (!$doku_error) { + echo $REQUEST_METHOD_MSG; + } else { + print_r($doku_error_msg); + } + case 'notify': + default: + if (!$doku_error) { + echo $REQUEST_METHOD_MSG; + } else { + echo "STOP\r\n"; + if (count($doku_error_msg) > 0) { + foreach ($doku_error_msg as $keval) { + echo $keval . "\n"; + } + } + } + break; + case 'redirect': + header("HTTP/1.1 301 Moved Permanently"); + header("Location: {$Redirect_Url}"); + exit; + break; +} + diff --git a/modules/gateways/callback/dokusubscription.php b/modules/gateways/callback/dokusubscription.php new file mode 100644 index 0000000..a3f786b --- /dev/null +++ b/modules/gateways/callback/dokusubscription.php @@ -0,0 +1,1507 @@ +setTimezone(new DateTimeZone("Asia/Bangkok")); +if (((int)$Datezone->format('His') >= 85959) && ((int)$Datezone->format('His') <= 225959)) { + $Void_Enabled = (isset($gatewayParams['Void-Enabled']) ? $gatewayParams['Void-Enabled'] : ''); + $Void_Enabled = (!is_array($Void_Enabled) ? trim($Void_Enabled) : ''); + $Void_Enabled = ((strtolower($Void_Enabled) === strtolower('on')) ? TRUE : FALSE); +} else { + $Void_Enabled = FALSE; +} +// Constant disabled VOID +$Void_Enabled = FALSE; +//------------------------------------------------------------------------------------------------ +$LocalApiAdminUsername = (isset($gatewayParams['Local-Api-Admin-Username']) ? $gatewayParams['Local-Api-Admin-Username'] : ''); +$Log_Enabled = FALSE; +if (isset($gatewayParams['Log-Enabled'])) { + $Log_Enabled = ((strtolower($gatewayParams['Log-Enabled']) == 'on') ? TRUE : FALSE); +} +/* +print_r($gatewayParams); +exit; +*/ +$PaymentCheck_Enabled = (isset($gatewayParams['PaymentCheck-Enabled']) ? $gatewayParams['PaymentCheck-Enabled'] : ''); +$PaymentCheck_Enabled = ((strtolower($PaymentCheck_Enabled) === strtolower('on')) ? TRUE : FALSE); +function redirecting_page_to_invoice($Redirect_Url) { + header("HTTP/1.1 301 Moved Permanently"); + header("Location: {$Redirect_Url}"); + exit; +} +// Die if module is not active. +if (!$gatewayParams['type']) { + die("Module Not Activated"); +} +$Environment = (isset($gatewayParams['Environment']) ? $gatewayParams['Environment'] : 'sandbox'); // Let sandbox as default +if (!is_string($Environment) && ((!is_array($Environment)) || (!is_object($Environment)))) { + if (strtolower($Environment) === strtolower('live')) { + // Gateway Configuration Parameters + $MallId = (isset($gatewayParams['MallId_Live']) ? $gatewayParams['MallId_Live'] : ''); + $ShopName = (isset($gatewayParams['ShopName_Live']) ? $gatewayParams['ShopName_Live'] : ''); + $ChainMerchant = (isset($gatewayParams['ChainMerchant_Live']) ? $gatewayParams['ChainMerchant_Live'] : 'NA'); + $SharedKey = (isset($gatewayParams['SharedKey_Live']) ? $gatewayParams['SharedKey_Live'] : ''); + } else { + // Gateway Configuration Parameters + $MallId = (isset($gatewayParams['MallId']) ? $gatewayParams['MallId'] : ''); + $ShopName = (isset($gatewayParams['ShopName']) ? $gatewayParams['ShopName'] : ''); + $ChainMerchant = (isset($gatewayParams['ChainMerchant']) ? $gatewayParams['ChainMerchant'] : 'NA'); + $SharedKey = (isset($gatewayParams['SharedKey']) ? $gatewayParams['SharedKey'] : ''); + } +} else { + // Gateway Configuration Parameters + $MallId = (isset($gatewayParams['MallId']) ? $gatewayParams['MallId'] : ''); + $ShopName = (isset($gatewayParams['ShopName']) ? $gatewayParams['ShopName'] : ''); + $ChainMerchant = (isset($gatewayParams['ChainMerchant']) ? $gatewayParams['ChainMerchant'] : 'NA'); + $SharedKey = (isset($gatewayParams['SharedKey']) ? $gatewayParams['SharedKey'] : ''); +} +$DokuConfigs = array( + 'isofile' => 'dokuhosted/assets/iso3166.json', + 'merchant' => array( + 'mallid' => $MallId, + 'shopname' => $ShopName, + 'chainmerchant' => $ChainMerchant, + 'sharedkey' => $SharedKey, + ), + 'endpoint' => (is_string($Environment) ? strtolower($Environment) : 'sandbox'), // sandbox as default +); +if (class_exists('dokusubscription_DokuPayment')) { + $DokuPayment = new dokusubscription_DokuPayment($DokuConfigs); +} else { + require_once($dokulib); + $DokuPayment = new dokusubscription_DokuPayment($DokuConfigs); +} +// Getting URL Querystring +$doku_get = dokusubscription_DokuPayment::_GET(); +// Make Global @CallbackPage +$CallbackPage = (isset($doku_get['page']) ? $doku_get['page'] : 'notify'); // notify as default-callback-page +$CallbackPage = (is_string($CallbackPage) ? strtolower($CallbackPage) : 'notify'); +/* +*************************************************************************** +* +* IF IPN : $doku_ipn_params +* IF Redirect : $doku_redirect_params +* +*************************************************************************** +*/ +$REQUEST_METHOD = (isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : 'HEAD'); +$REQUEST_METHOD_MSG = ""; +# Get Doku IPN Params: +$doku_ipn_params = $DokuPayment->doku_incoming_callback(); +if ($Log_Enabled) { + logTransaction($gatewayParams['paymentmethod'], $doku_ipn_params, "({$REQUEST_METHOD}) Incoming Callback Params"); +} +# Get Doku Redirect Params from Request-Uri +$doku_redirect_params = dokusubscription_DokuPayment::get_query_string(); +################################ +//------------------------------ +// Global Validation +$doku_error = FALSE; +$doku_error_msg = array(); +// Make GLOBAL @success +$success = FALSE; +//------------------------------ +// Make GLOBAL @checkCbTransID +$checkCbTransID = FALSE; +// Previously get 500 Internal Error for this transaction: checkCbTransID($transactionId); +// Make GLOBAL @XMLPaymentStatus +$XMLPaymentStatus = array(); +if ($EDU_Enabled > 0) { + $XMLPaymentStatus['edu-enabled'] = $EDU_Enabled; +} else { + $XMLPaymentStatus['edu-enabled'] = 0; +} +// Make GLOBAL @StringVoidStatus +$StringVoidStatus = ""; +/* +// Use localAPI to handle and redirect user +*/ +$localApi = array( + 'command' => 'GetOrders', + 'data' => array( + 'id' => '', // Later updated on review case + //'invoiceid' => '', # Later updated on review case + ), + 'username' => $LocalApiAdminUsername, // Optional for WHMCS 7.2 and later +); +//------------------------------ +################################ +switch (strtolower($CallbackPage)) { + //------------------ + // Debug Invoice + //------------------ + case 'debug': + $invoiceId = (isset($doku_redirect_params['id']) ? $doku_redirect_params['id'] : ''); + $invoiceId = (int)$invoiceId; + $cbInvoiceId = checkCbInvoiceID($invoiceId, $gatewayParams['paymentmethod']); + if ($invoiceId) { + echo "
";
+			echo "{$invoiceId}";
+			echo "
"; + echo $cbInvoiceId; + echo "
"; + $data = array( + //'id' => $invoiceId, + 'invoiceid' => $invoiceId, + ); + $InvoiceData = localAPI('GetInvoice', $data, 'whmcsdoku'); + print_r($InvoiceData); + + + } + exit; + break; + case 'identify': + if ($_SERVER['REQUEST_METHOD'] == 'POST') { + if (count($doku_ipn_params['body']) > 0) { + # DOKU Identify + $dokuparams = array( + 'TRANSIDMERCHANT' => (isset($doku_ipn_params['body']['TRANSIDMERCHANT']) ? $doku_ipn_params['body']['TRANSIDMERCHANT'] : ''), + 'PURCHASECURRENCY' => (isset($doku_ipn_params['body']['PURCHASECURRENCY']) ? $doku_ipn_params['body']['PURCHASECURRENCY'] : ''), + 'CURRENCY' => (isset($doku_ipn_params['body']['CURRENCY']) ? $doku_ipn_params['body']['CURRENCY'] : ''), + 'PAYMENTCHANNEL' => (isset($doku_ipn_params['body']['PAYMENTCHANNEL']) ? $doku_ipn_params['body']['PAYMENTCHANNEL'] : ''), + 'PAYMENTCODE' => (isset($doku_ipn_params['body']['PAYMENTCODE']) ? $doku_ipn_params['body']['PAYMENTCODE'] : ''), + 'AMOUNT' => (isset($doku_ipn_params['body']['AMOUNT']) ? $doku_ipn_params['body']['AMOUNT'] : ''), + 'SESSIONID' => (isset($doku_ipn_params['body']['SESSIONID']) ? $doku_ipn_params['body']['SESSIONID'] : ''), + ); + if ($Identify_Enabled) { + if ($Log_Enabled) { + logTransaction($gatewayParams['paymentmethod'], $dokuparams, "Payment Identify"); + } + } + $REQUEST_METHOD_MSG = "IDENTIFY:Continue"; + } else { + $REQUEST_METHOD_MSG = "STOP: BODY Have no content - Identify"; + } + } else { + $REQUEST_METHOD_MSG = "STOP: POST Method Required - Identify"; + } + break; + case 'review': + $dokuparams = array(); + $REQUEST_METHOD_MSG = "Review Page - Redirect to main-page"; + // Get from Querystring + $dokuparams['TRANSIDMERCHANT'] = (isset($doku_redirect_params['TRANSIDMERCHANT']) ? $doku_redirect_params['TRANSIDMERCHANT'] : ''); + // Get from Postbody + if (count($doku_ipn_params['body']) > 0) { + $dokuparams['TRANSIDMERCHANT'] = (isset($doku_ipn_params['body']['TRANSIDMERCHANT']) ? $doku_ipn_params['body']['TRANSIDMERCHANT'] : $dokuparams['TRANSIDMERCHANT']); + } + $transaction_id_part = substr($dokuparams['TRANSIDMERCHANT'], 0, 14); + if (!$doku_error) { + try { + $transaction_id_part = date_create_from_format('YmdHis', $transaction_id_part); + } catch (Exception $ex) { + $doku_error = true; + $doku_error_msg[] = "Exception error of date-created from formta: {$ex->getMessage()}."; + } + } + if (!$doku_error) { + if (!strtotime(date_format($transaction_id_part, 'Y-m-d H:i:s'))) { + $doku_error = true; + $doku_error_msg[] = "Transaction id part not in Dateformat structured."; + } + } + if (!$doku_error) { + $transaction_id_part = date_format($transaction_id_part, 'YmdHis'); + $merchant_transaction = explode("{$transaction_id_part}", $dokuparams['TRANSIDMERCHANT']); + if (!isset($merchant_transaction[1])) { + $doku_error = true; + $doku_error_msg[] = "There is no Transaction-id from IPN Callback as expected: #DATETIME#TRANSID."; + } + } + if (!$doku_error) { + $invoiceId = trim($merchant_transaction[1]); + /** + * Validate Callback Invoice ID. + * + * Checks invoice ID is a valid invoice number. Note it will count an + * invoice in any status as valid. + * + * Performs a die upon encountering an invalid Invoice ID. + * + * Returns a normalised invoice ID. + * + * @param int $invoiceId Invoice ID + * @param string $gatewayName Gateway Name + **/ + $invoiceId = checkCbInvoiceID($invoiceId, $gatewayParams['paymentmethod']); + if (!$invoiceId) { + $doku_error = true; + $doku_error_msg[] = "invoiceId is not found."; + if ($Log_Enabled) { + logTransaction($gatewayParams['paymentmethod'], $doku_error_msg, "InvoiceId Not Found"); + } + } + } + if (!$doku_error) { + $localApi['data']['id'] = $invoiceId; + $InvoiceData = localAPI($localApi['command'], $localApi['data'], $localApi['username']); + $Redirect_Url = ""; + if (isset($InvoiceData['totalresults'])) { + if (intval($InvoiceData['totalresults']) > 0) { + $GetConfigurationValue = localAPI('GetConfigurationValue', array('setting' => 'SystemURL'), $localApi['username']); + $Redirect_Url .= (isset($GetConfigurationValue['value']) ? $GetConfigurationValue['value'] : ''); + $Redirect_Url .= ((substr($systemUrl, -1) == '/') ? '' : '/'); + $Redirect_Url .= "viewinvoice.php?id={$invoiceId}"; + echo "redirect 01 -
\n"; + //redirecting_page_to_invoice($Redirect_Url) + exit; + } + } else { + $doku_error = true; + $doku_error_msg[] = "Local API Result not get totalresults of InvoiceData from GetOrders()."; + } + } + break; + case 'notify': + case 'updatenotify': + case 'regupdate': + case 'subscription': + default: + if ($_SERVER['REQUEST_METHOD'] == 'POST') { + if (count($doku_ipn_params['body']) > 0) { + # DOKU Notify + $dokuparams = array( + 'PAYMENTDATETIME' => (isset($doku_ipn_params['body']['PAYMENTDATETIME']) ? $doku_ipn_params['body']['PAYMENTDATETIME'] : ''), + 'PURCHASECURRENCY' => (isset($doku_ipn_params['body']['PURCHASECURRENCY']) ? $doku_ipn_params['body']['PURCHASECURRENCY'] : ''), + 'LIABILITY' => (isset($doku_ipn_params['body']['LIABILITY']) ? $doku_ipn_params['body']['LIABILITY'] : ''), + 'PAYMENTCHANNEL' => (isset($doku_ipn_params['body']['PAYMENTCHANNEL']) ? $doku_ipn_params['body']['PAYMENTCHANNEL'] : ''), + 'AMOUNT' => (isset($doku_ipn_params['body']['AMOUNT']) ? $doku_ipn_params['body']['AMOUNT'] : ''), + 'PAYMENTCODE' => (isset($doku_ipn_params['body']['PAYMENTCODE']) ? $doku_ipn_params['body']['PAYMENTCODE'] : ''), + 'MCN' => (isset($doku_ipn_params['body']['MCN']) ? $doku_ipn_params['body']['MCN'] : ''), + 'WORDS' => (isset($doku_ipn_params['body']['WORDS']) ? $doku_ipn_params['body']['WORDS'] : ''), + 'RESULTMSG' => (isset($doku_ipn_params['body']['RESULTMSG']) ? $doku_ipn_params['body']['RESULTMSG'] : ''), + 'VERIFYID' => (isset($doku_ipn_params['body']['VERIFYID']) ? $doku_ipn_params['body']['VERIFYID'] : ''), + 'TRANSIDMERCHANT' => (isset($doku_ipn_params['body']['TRANSIDMERCHANT']) ? $doku_ipn_params['body']['TRANSIDMERCHANT'] : ''), + 'BANK' => (isset($doku_ipn_params['body']['BANK']) ? $doku_ipn_params['body']['BANK'] : ''), + 'APPROVALCODE' => (isset($doku_ipn_params['body']['APPROVALCODE']) ? $doku_ipn_params['body']['APPROVALCODE'] : ''), + 'EDUSTATUS' => (isset($doku_ipn_params['body']['EDUSTATUS']) ? $doku_ipn_params['body']['EDUSTATUS'] : ''), + 'THREEDSECURESTATUS' => (isset($doku_ipn_params['body']['THREEDSECURESTATUS']) ? $doku_ipn_params['body']['THREEDSECURESTATUS'] : ''), + 'VERIFYSCORE' => (isset($doku_ipn_params['body']['VERIFYSCORE']) ? $doku_ipn_params['body']['VERIFYSCORE'] : ''), + 'CURRENCY' => (isset($doku_ipn_params['body']['CURRENCY']) ? $doku_ipn_params['body']['CURRENCY'] : ''), + 'RESPONSECODE' => (isset($doku_ipn_params['body']['RESPONSECODE']) ? $doku_ipn_params['body']['RESPONSECODE'] : ''), + 'CHNAME' => (isset($doku_ipn_params['body']['CHNAME']) ? $doku_ipn_params['body']['CHNAME'] : ''), + 'BRAND' => (isset($doku_ipn_params['body']['BRAND']) ? $doku_ipn_params['body']['BRAND'] : ''), + 'VERIFYSTATUS' => (isset($doku_ipn_params['body']['VERIFYSTATUS']) ? $doku_ipn_params['body']['VERIFYSTATUS'] : ''), + 'SESSIONID' => (isset($doku_ipn_params['body']['SESSIONID']) ? $doku_ipn_params['body']['SESSIONID'] : ''), + // -- Recurring POST + 'CHAINMERCHANT' => (isset($doku_ipn_params['body']['CHAINMERCHANT']) ? $doku_ipn_params['body']['CHAINMERCHANT'] : ''), + 'CUSTOMERID' => (isset($doku_ipn_params['body']['CUSTOMERID']) ? $doku_ipn_params['body']['CUSTOMERID'] : ''), + 'BILLNUMBER' => (isset($doku_ipn_params['body']['BILLNUMBER']) ? $doku_ipn_params['body']['BILLNUMBER'] : ''), + 'CARDNUMBER' => (isset($doku_ipn_params['body']['CARDNUMBER']) ? $doku_ipn_params['body']['CARDNUMBER'] : ''), + 'STATUS' => (isset($doku_ipn_params['body']['STATUS']) ? $doku_ipn_params['body']['STATUS'] : ''), + 'ERRORCODE' => (isset($doku_ipn_params['body']['ERRORCODE']) ? $doku_ipn_params['body']['ERRORCODE'] : ''), + 'MESSAGE' => (isset($doku_ipn_params['body']['MESSAGE']) ? $doku_ipn_params['body']['MESSAGE'] : ''), + 'STATUSTYPE' => (isset($doku_ipn_params['body']['STATUSTYPE']) ? $doku_ipn_params['body']['STATUSTYPE'] : ''), + 'TOKENID' => (isset($doku_ipn_params['body']['TOKENID']) ? $doku_ipn_params['body']['TOKENID'] : ''), + // -- Subscription Get Amount + 'CUSTOMERNAME' => (isset($doku_ipn_params['body']['CUSTOMERNAME']) ? $doku_ipn_params['body']['CUSTOMERNAME'] : ''), + 'CUSTOMEREMAIL' => (isset($doku_ipn_params['body']['CUSTOMEREMAIL']) ? $doku_ipn_params['body']['CUSTOMEREMAIL'] : ''), + 'CUSTOMERHOMEPHONE' => (isset($doku_ipn_params['body']['CUSTOMERHOMEPHONE']) ? $doku_ipn_params['body']['CUSTOMERHOMEPHONE'] : ''), + 'CUSTOMERMOBILEPHONE' => (isset($doku_ipn_params['body']['CUSTOMERMOBILEPHONE']) ? $doku_ipn_params['body']['CUSTOMERMOBILEPHONE'] : ''), + ); + $REQUEST_METHOD_MSG = "NOTIFY-REGISTER:Continue"; + } else { + $doku_error = true; + $REQUEST_METHOD_MSG = "STOP: BODY Have no content"; + $doku_error_msg[] = $REQUEST_METHOD_MSG; + } + } else { + $doku_error = true; + $REQUEST_METHOD_MSG = "STOP: POST Method Required"; + $doku_error_msg[] = $REQUEST_METHOD_MSG; + } + break; + case 'redirect': + # DOKU Params (GET) + $dokuparams = array( + 'PAYMENTDATETIME' => (isset($doku_redirect_params['PAYMENTDATETIME']) ? $doku_redirect_params['PAYMENTDATETIME'] : ''), + 'PURCHASECURRENCY' => (isset($doku_redirect_params['PURCHASECURRENCY']) ? $doku_redirect_params['PURCHASECURRENCY'] : ''), + 'LIABILITY' => (isset($doku_redirect_params['LIABILITY']) ? $doku_redirect_params['LIABILITY'] : ''), + 'PAYMENTCHANNEL' => (isset($doku_redirect_params['PAYMENTCHANNEL']) ? $doku_redirect_params['PAYMENTCHANNEL'] : ''), + 'AMOUNT' => (isset($doku_redirect_params['AMOUNT']) ? $doku_redirect_params['AMOUNT'] : ''), + 'PAYMENTCODE' => (isset($doku_redirect_params['PAYMENTCODE']) ? $doku_redirect_params['PAYMENTCODE'] : ''), + 'MCN' => (isset($doku_redirect_params['MCN']) ? $doku_redirect_params['MCN'] : ''), + 'WORDS' => (isset($doku_redirect_params['WORDS']) ? $doku_redirect_params['WORDS'] : ''), + 'RESULTMSG' => (isset($doku_redirect_params['RESULTMSG']) ? $doku_redirect_params['RESULTMSG'] : ''), + 'VERIFYID' => (isset($doku_redirect_params['VERIFYID']) ? $doku_redirect_params['VERIFYID'] : ''), + 'TRANSIDMERCHANT' => (isset($doku_redirect_params['TRANSIDMERCHANT']) ? $doku_redirect_params['TRANSIDMERCHANT'] : ''), + 'BANK' => (isset($doku_redirect_params['BANK']) ? $doku_redirect_params['BANK'] : ''), + 'STATUSTYPE' => (isset($doku_redirect_params['STATUSTYPE']) ? $doku_redirect_params['STATUSTYPE'] : ''), + 'APPROVALCODE' => (isset($doku_redirect_params['APPROVALCODE']) ? $doku_redirect_params['APPROVALCODE'] : ''), + 'EDUSTATUS' => (isset($doku_redirect_params['EDUSTATUS']) ? $doku_redirect_params['EDUSTATUS'] : ''), + 'THREEDSECURESTATUS' => (isset($doku_redirect_params['THREEDSECURESTATUS']) ? $doku_redirect_params['THREEDSECURESTATUS'] : ''), + 'VERIFYSCORE' => (isset($doku_redirect_params['VERIFYSCORE']) ? $doku_redirect_params['VERIFYSCORE'] : ''), + 'CURRENCY' => (isset($doku_redirect_params['CURRENCY']) ? $doku_redirect_params['CURRENCY'] : ''), + 'RESPONSECODE' => (isset($doku_redirect_params['RESPONSECODE']) ? $doku_redirect_params['RESPONSECODE'] : ''), + 'CHNAME' => (isset($doku_redirect_params['CHNAME']) ? $doku_redirect_params['CHNAME'] : ''), + 'BRAND' => (isset($doku_redirect_params['BRAND']) ? $doku_redirect_params['BRAND'] : ''), + 'VERIFYSTATUS' => (isset($doku_redirect_params['VERIFYSTATUS']) ? $doku_redirect_params['VERIFYSTATUS'] : ''), + 'SESSIONID' => (isset($doku_redirect_params['SESSIONID']) ? $doku_redirect_params['SESSIONID'] : ''), + 'STATUSCODE' => (isset($doku_redirect_params['STATUSCODE']) ? $doku_redirect_params['STATUSCODE'] : ''), + // -- Recurring Params + 'CHAINMERCHANT' => (isset($doku_redirect_params['CHAINMERCHANT']) ? $doku_redirect_params['CHAINMERCHANT'] : ''), + 'CUSTOMERID' => (isset($doku_redirect_params['CUSTOMERID']) ? $doku_redirect_params['CUSTOMERID'] : ''), + 'BILLNUMBER' => (isset($doku_redirect_params['BILLNUMBER']) ? $doku_redirect_params['BILLNUMBER'] : ''), + 'CARDNUMBER' => (isset($doku_redirect_params['CARDNUMBER']) ? $doku_redirect_params['CARDNUMBER'] : ''), + 'STATUS' => (isset($doku_redirect_params['STATUS']) ? $doku_redirect_params['STATUS'] : ''), + 'ERRORCODE' => (isset($doku_redirect_params['ERRORCODE']) ? $doku_redirect_params['ERRORCODE'] : ''), + 'MESSAGE' => (isset($doku_redirect_params['MESSAGE']) ? $doku_redirect_params['MESSAGE'] : ''), + 'STATUSTYPE' => (isset($doku_redirect_params['STATUSTYPE']) ? $doku_redirect_params['STATUSTYPE'] : ''), + 'TOKENID' => (isset($doku_redirect_params['TOKENID']) ? $doku_redirect_params['TOKENID'] : ''), + ); + # DOKU Params (POST) + if (count($doku_ipn_params['body']) > 0) { + foreach ($doku_ipn_params['body'] as $key => $val) { + if (!isset($dokuparams[$key])) { + $dokuparams[$key] = $val; + } else { + if ($dokuparams[$key] != $val) { + $dokuparams[$key] = $val; + } + } + } + } + if (count($doku_redirect_params) > 0) { + $REQUEST_METHOD_MSG = "REDIRECT:Continue"; + } else { + $REQUEST_METHOD_MSG = "STOP: QUERYSTRING Have no content"; + } + break; +} +/* +** +* CONTINUE +** +*/ +$Notify_Type = 0; +switch (strtolower($CallbackPage)) { + case 'notify': + case 'subscripton': + if (!$doku_error) { + if (!empty($dokuparams['STATUSTYPE'])) { + if (!is_string($dokuparams['STATUSTYPE'])) { + $doku_error = true; + $doku_error_msg[] = "STATUS TYPE should be in string format."; + } + } + } + if (!$doku_error) { + switch (strtoupper($dokuparams['STATUSTYPE'])) { + case 'G': + $Notify_Type = 1; // Notify Registration + break; + case 'T': + $Notify_Type = 2; // Notify Update + break; + } + } + break; + default: + // Nothing to do.... + break; +} +/* +** +* CONTINUE +** +*/ +switch (strtolower($CallbackPage)) { + case 'notify': + case 'updatenotify': + case 'regupdate': + default: + if (!$doku_error) { + if ($Log_Enabled) { + switch ($Notify_Type) { + case 0: logTransaction($gatewayParams['paymentmethod'], $dokuparams, 'Payment Notify Process'); break; + case 1: logTransaction($gatewayParams['paymentmethod'], $dokuparams, 'Payment Notify Register'); break; + case 2: logTransaction($gatewayParams['paymentmethod'], $dokuparams, 'Payment Notify Update'); break; + } + } + } + break; + case 'redirect': + if (!$doku_error) { + if ($Log_Enabled) { + switch ($Notify_Type) { + case 0: logTransaction($gatewayParams['paymentmethod'], $dokuparams, 'Payment Redirect Process'); break; + case 1: logTransaction($gatewayParams['paymentmethod'], $dokuparams, 'Payment Redirect Register'); break; + case 2: logTransaction($gatewayParams['paymentmethod'], $dokuparams, 'Payment Redirect Update'); break; + } + } + } + break; + case 'subscription': + if (!$doku_error) { + if ($Log_Enabled) { + logTransaction($gatewayParams['paymentmethod'], $dokuparams, 'Payment Subscription GetAmount'); + } + } + break; + case 'review': + case 'identify': + echo "{$REQUEST_METHOD_MSG}"; + exit; + break; +} +/* +** +* CONTINUE +** +*/ +switch (strtolower($CallbackPage)) { + case 'notify': + case 'updatenotify': + case 'regupdate': + case 'redirect': + case 'subscription': + default: + if (!$doku_error) { + if (is_array($dokuparams['BILLNUMBER']) || is_object($dokuparams['BILLNUMBER'])) { + $doku_error = true; + $doku_error_msg[] = "Array or Object return for BILLNUMBER."; + } + } + if (!$doku_error) { + $transaction_id = $dokuparams['BILLNUMBER']; + $transaction_id_part = substr($dokuparams['BILLNUMBER'], 0, 12); + try { + //$transaction_id_part = DateTime::createFromFormat('YmdHi', $transaction_id_part); + $transaction_id_part = date_create_from_format('YmdHi', $transaction_id_part); + } catch (Exception $ex) { + $doku_error = true; + $doku_error_msg[] = "Exception error of date-created from format: {$ex->getMessage()}."; + } + } + if (!$doku_error) { + if (!strtotime(date_format($transaction_id_part, 'Y-m-d H:i:s'))) { + $doku_error = true; + $doku_error_msg[] = "Transaction id part from billnumber not in Dateformat structured."; + } + } + if (!$doku_error) { + $transaction_id_part = date_format($transaction_id_part, 'YmdHi'); + $merchant_transaction = explode("{$transaction_id_part}", $dokuparams['BILLNUMBER']); + if (!isset($merchant_transaction[1])) { + $doku_error = true; + $doku_error_msg[] = "There is no Transaction-id from IPN Callback as expected: #DATETIME#TRANSID."; + } + } + if (!$doku_error) { + $invoiceId = trim($merchant_transaction[1]); + } + break; +} +/* +** +* CONTINUE +** +*/ +switch (strtolower($CallbackPage)) { + case 'notify': + case 'regupdate': + case 'redirect': + default: + ######################################### + if (!$doku_error) { + /** + * Validate Callback Invoice ID. + * + * Checks invoice ID is a valid invoice number. Note it will count an + * invoice in any status as valid. + * + * Performs a die upon encountering an invalid Invoice ID. + * + * Returns a normalised invoice ID. + * + * @param int $invoiceId Invoice ID + * @param string $gatewayName Gateway Name + **/ + $invoiceId = checkCbInvoiceID($invoiceId, $gatewayParams['paymentmethod']); + if (!$invoiceId) { + $doku_error = true; + $doku_error_msg[] = "invoiceId is not found."; + if ($Log_Enabled) { + logTransaction($gatewayParams['paymentmethod'], $doku_error_msg, "InvoiceId Not Found"); + } + } + } + ######################################## + break; + case 'subscription': + // do nothing.. + break; +} +/* +** +* CONTINUE +** +*/ +switch (strtolower($CallbackPage)) { + case 'notify': + case 'regupdate': + case 'redirect': + case 'subscription': + default: + //-------------------------------------------------------------------- + if (!$doku_error) { + $params_input = array(); + $params_input['mallid'] = (isset($dokuparams['MALLID']) ? $dokuparams['MALLID'] : ''); + $params_input['chainmerchant'] = (isset($dokuparams['CHAINMERCHANT']) ? $dokuparams['CHAINMERCHANT'] : ''); + $params_input['transaction_id'] = (isset($dokuparams['TRANSIDMERCHANT']) ? $dokuparams['TRANSIDMERCHANT'] : ''); + $params_input['transaction_customer'] = (isset($dokuparams['CUSTOMERID']) ? $dokuparams['CUSTOMERID'] : ''); + $params_input['transaction_card'] = (isset($dokuparams['CARDNUMBER']) ? $dokuparams['CARDNUMBER'] : ''); + $params_input['transaction_status'] = (isset($dokuparams['STATUS']) ? $dokuparams['STATUS'] : ''); + $params_input['transaction_error'] = (isset($dokuparams['ERRORCODE']) ? $dokuparams['ERRORCODE'] : ''); + $params_input['transaction_message'] = (isset($dokuparams['MESSAGE']) ? $dokuparams['MESSAGE'] : ''); + $params_input['transaction_type'] = (isset($dokuparams['STATUSTYPE']) ? $dokuparams['STATUSTYPE'] : ''); // G: Notify Registration T: Notify Update + $params_input['transaction_code'] = (isset($dokuparams['RESPONSECODE']) ? $dokuparams['RESPONSECODE'] : ''); + $params_input['transaction_currency'] = (isset($dokuparams['CURRENCY']) ? $dokuparams['CURRENCY'] : ''); + $params_input['transaction_approval'] = (isset($dokuparams['APPROVALCODE']) ? $dokuparams['APPROVALCODE'] : ''); + $params_input['transaction_bank'] = (isset($dokuparams['BANK']) ? $dokuparams['BANK'] : ''); + $params_input['transaction_datetime'] = (isset($dokuparams['PAYMENTDATETIME']) ? $dokuparams['PAYMENTDATETIME'] : ''); + $params_input['words'] = (isset($dokuparams['WORDS']) ? $dokuparams['WORDS'] : ''); + //--- + $params_input['subscription_amount'] = (isset($dokuparams['AMOUNT']) ? $dokuparams['AMOUNT'] : '0.00'); + $params_input['subscription_chainmerchant'] = (isset($dokuparams['CHAINMERCHANT']) ? $dokuparams['CHAINMERCHANT'] : 'NA'); + $params_input['subscription_transaction_id'] = (isset($dokuparams['TRANSIDMERCHANT']) ? $dokuparams['TRANSIDMERCHANT'] : 0); + $params_input['subscription_transaction_bill'] = (isset($dokuparams['BILLNUMBER']) ? $dokuparams['BILLNUMBER'] : 0); + $params_input['subscription_transaction_session'] = (isset($dokuparams['SESSIONID']) ? $dokuparams['SESSIONID'] : ''); + $params_input['subscription_transaction_currency'] = (isset($dokuparams['CURRENCY']) ? $dokuparams['CURRENCY'] : 'IDR'); + $params_input['subscription_transaction_currency'] = substr($params_input['subscription_transaction_currency'], 0, 2); + $params_input['subscription_transaction_status'] = (isset($dokuparams['STATUS']) ? $dokuparams['STATUS'] : ''); + $params_input['subscription_transaction_error'] = (isset($dokuparams['ERRORCODE']) ? $dokuparams['ERRORCODE'] : ''); + $params_input['subscription_transaction_message'] = (isset($dokuparams['MESSAGE']) ? $dokuparams['MESSAGE'] : ''); + $params_input['subscription_transaction_card'] = (isset($dokuparams['CARDNUMBER']) ? $dokuparams['CARDNUMBER'] : ''); + $params_input['subscription_transaction_type'] = (isset($dokuparams['STATUSTYPE']) ? $dokuparams['STATUSTYPE'] : ''); + $params_input['subscription_result_msg'] = (isset($dokuparams['RESULTMSG']) ? $dokuparams['RESULTMSG'] : ''); // SUCCESS | FAILED + $params_input['subscription_transaction_customer'] = (isset($dokuparams['CUSTOMERID']) ? $dokuparams['CUSTOMERID'] : ''); + $params_input['subscription_transaction_token'] = (isset($dokuparams['TOKENID']) ? $dokuparams['TOKENID'] : ''); + $params_input['subscription_transaction_channel'] = (isset($dokuparams['PAYMENTCHANNEL']) ? $dokuparams['PAYMENTCHANNEL'] : ''); + $params_input['subscription_verify_id'] = (isset($dokuparams['VERIFYID']) ? $dokuparams['VERIFYID'] : ''); + $params_input['subscription_verify_score'] = (isset($dokuparams['VERIFYSCORE']) ? $dokuparams['VERIFYSCORE'] : ''); + $params_input['subscription_verify_status'] = (isset($dokuparams['VERIFYSTATUS']) ? $dokuparams['VERIFYSTATUS'] : ''); // NA + $params_input['subscription_words'] = (isset($dokuparams['WORDS']) ? $dokuparams['WORDS'] : ''); + //-- + $params_input['subscription_transaction_customer_name'] = (isset($dokuparams['CUSTOMERNAME']) ? $dokuparams['CUSTOMERNAME'] : ''); + $params_input['subscription_transaction_customer_email'] = (isset($dokuparams['CUSTOMEREMAIL']) ? $dokuparams['CUSTOMEREMAIL'] : ''); + $params_input['subscription_transaction_customer_phone'] = (isset($dokuparams['CUSTOMERHOMEPHONE']) ? $dokuparams['CUSTOMERHOMEPHONE'] : ''); + $params_input['subscription_transaction_customer_mobile'] = (isset($dokuparams['CUSTOMERMOBILEPHONE']) ? $dokuparams['CUSTOMERMOBILEPHONE'] : ''); + } + break; +} +/* +** +* CONTINUE +** +*/ +switch (strtolower($CallbackPage)) { + case 'notify': + case 'regupdate': + if (!$doku_error) { + // Make subscription-notify structured + switch ($Notify_Type) { + case 0: + $CheckNotifyPaymentStructure = $DokuPayment->create_payment_structure('subscription-process', 0, $params_input, $dokuparams); + if ($Log_Enabled) { + logTransaction($gatewayParams['paymentmethod'], $CheckNotifyPaymentStructure, 'Subscription Process Structured'); + } + break; + case 1: + $CheckNotifyPaymentStructure = $DokuPayment->create_payment_structure('subscription-notify', 0, $params_input, $dokuparams); + if ($Log_Enabled) { logTransaction($gatewayParams['paymentmethod'], $CheckNotifyPaymentStructure, 'Subscription Register Structured'); } + break; + case 2: + $CheckNotifyPaymentStructure = $DokuPayment->create_payment_structure('subscription-update', 0, $params_input, $dokuparams); + if ($Log_Enabled) { logTransaction($gatewayParams['paymentmethod'], $CheckNotifyPaymentStructure, 'Subscription Update Structured'); } + break; + } + if (!isset($CheckNotifyPaymentStructure['WORDS'])) { + $doku_error = true; + $doku_error_msg[] = "Not get WORDS string from created notify structured."; + } + + } + break; + case 'redirect': + if (!$doku_error) { + // Make subscription-redirect structured + $CheckNotifyPaymentStructure = $DokuPayment->create_payment_structure('redirect', 0, $params_input, $dokuparams); + if ($Log_Enabled) { logTransaction($gatewayParams['paymentmethod'], $CheckNotifyPaymentStructure, 'Subscription Redirect Structured'); } + if (!isset($CheckNotifyPaymentStructure['WORDS'])) { + $doku_error = true; + $doku_error_msg[] = "Not get WORDS string from created notify structured."; + } + } + if (!$doku_error) { + if (!is_string($params_input['words'])) { + $doku_error = true; + $doku_error_msg[] = "Words should be a string."; + } + } + break; + case 'subscription': + if (!$doku_error) { + try { + $SubscriptionDataStructure = $DokuPayment->create_payment_structure('regsubscription', 0, $params_input, $dokuparams); + } catch (Exception $ex) { + $doku_error = true; + $doku_error_msg[] = "Exception error while get system structure for get subscription amount: {$ex->getMessage()}."; + } + } + if (!$doku_error) { + if ($Log_Enabled) { logTransaction($gatewayParams['paymentmethod'], $SubscriptionDataStructure, 'Get Subscription Amount'); } + if (!isset($SubscriptionDataStructure['WORDS'])) { + $doku_error = true; + $doku_error_msg[] = "Not get WORDS string from created get subscription amount."; + } + } + if (!$doku_error) { + if (!is_string($params_input['words'])) { + $doku_error = true; + $doku_error_msg[] = "Words should be a string."; + } + } + if (!$doku_error) { + if (strtolower($params_input['words']) !== strtolower($SubscriptionDataStructure['WORDS'])) { + $doku_error = true; + $doku_error_msg[] = "Words should be match to get subscription data."; + } + } + break; +} + + +/* +** +* CONTINUE +** +*/ +$order_id = 0; +$order_num = 0; +$order_status = ''; +switch (strtolower($CallbackPage)) { + case 'notify': + case 'regupdate': + case 'redirect': + // Make more @XMLPaymentStatus params + if (count($dokuparams) > 0) { + foreach ($dokuparams as $key => $val) { + $key = preg_replace("/[^a-zA-Z0-9]+/", "", $key); + if (!empty($key) || ($key != '')) { + $XMLPaymentStatus[$key] = $val; + } + } + } + //------------------------------------ + $Redirect_Url = "/"; + if (!$doku_error) { + If (isset($localApi['data']['id'])) { + unset($localApi['data']['id']); + } + $localApi['data']['invoiceid'] = $invoiceId; + // query localApi from invoiceid + $InvoiceData = localAPI('GetInvoice', $localApi['data'], $localApi['username']); + if (isset($InvoiceData['invoiceid'])) { + if (intval($InvoiceData['invoiceid']) > 0) { + $GetConfigurationValue = localAPI('GetConfigurationValue', array('setting' => 'SystemURL'), $localApi['username']); + $Redirect_Url = (isset($GetConfigurationValue['value']) ? $GetConfigurationValue['value'] : ''); + $Redirect_Url .= ((substr($systemUrl, -1) == '/') ? '' : '/'); + $Redirect_Url .= "viewinvoice.php?id={$invoiceId}"; + } + } else { + $doku_error = true; + $doku_error_msg[] = "Local API Result not get totalresults of InvoiceData from GetInvoice()."; + } + } + $orders_debug = array( + 'order_id' => 0, + 'order_num' => 0, + 'order_status' => '', + ); + if (!$doku_error) { + if (isset($InvoiceData['invoiceid']) && isset($InvoiceData['invoicenum']) && isset($InvoiceData['status'])) { + if (intval($InvoiceData['invoiceid']) > 0) { + $order_id = $InvoiceData['invoiceid']; + $orders_debug['order_id'] = $order_id; + } + if (intval($InvoiceData['invoicenum']) > 0) { + $order_num = $InvoiceData['invoicenum']; + $orders_debug['order_num'] = $order_num; + } + $order_status = (is_string($InvoiceData['status']) ? strtolower($InvoiceData['status']) : ''); + $orders_debug['order_status'] = $order_status; + } else { + $doku_error = true; + $doku_error_msg[] = "Local API Result for GetInvoice() not get proper data as expected."; + } + } + break; + case 'subscription': + if (!$doku_error) { + If (isset($localApi['data']['id'])) { + unset($localApi['data']['id']); + } + $localApi['data']['invoiceid'] = $invoiceId; + $InvoiceData = localAPI('GetInvoice', $localApi['data'], $localApi['username']); + if (isset($InvoiceData['invoiceid'])) { + if (intval($InvoiceData['invoiceid']) > 0) { + $GetConfigurationValue = localAPI('GetConfigurationValue', array('setting' => 'SystemURL'), $localApi['username']); + $Redirect_Url = (isset($GetConfigurationValue['value']) ? $GetConfigurationValue['value'] : ''); + $Redirect_Url .= ((substr($systemUrl, -1) == '/') ? '' : '/'); + $Redirect_Url .= "viewinvoice.php?id={$invoiceId}"; + } + } else { + $doku_error = true; + $doku_error_msg[] = "Local API Result not get totalresults of InvoiceData from GetOrders()."; + } + } + $invoceSubscriptionTotal = ""; + if (!$doku_error) { + if (isset($InvoiceData['total'])) { + $invoceSubscriptionTotal = sprintf("%.2f", floatval($InvoiceData['total'])); + } + } + if (!$doku_error) { + echo $invoceSubscriptionTotal; + } else { + print_r($doku_error_msg); + } + exit; + break; +} +/* +** +* CONTINUE +** +*/ +switch (strtolower($CallbackPage)) { + case 'notify': + case 'regupdate': + + break; +} + + + + + + +//-------------------------------------------------------------------------------------------------------------------- +//-------------------------------------------------------------------------------------------------------------------- +//-------------------------------------------------------------------------------------------------------------------- +//-------------------------------------------------------------------------------------------------------------------- +/* +$OrderData = FALSE; +if (isset($localApi['data']['id'])) { + unset($localApi['data']['id']); +} +$localApi['command'] = 'GetOrders'; +$localApi['data']['invoiceid'] = (isset($params['invoiceid']) ? $params['invoiceid'] : ''); +$OrdersData = localAPI($localApi['command'], $localApi['data'], $localApi['username']); +if (isset($OrdersData['orders']['order'])) { + if (count($OrdersData['orders']['order']) > 0) { + foreach ($OrdersData['orders']['order'] as $keval) { + if (isset($keval['invoiceid'])) { + if ((int)$keval['invoiceid'] === (int)$localApi['data']['invoiceid']) { + $OrderData = $keval; + } + } + } + } +} +if (!$error) { + if (!$OrderData) { + $error = true; + $error_msg[] = "No Invoice data from localApi: " . (__METHOD__); + } +} +if ($InvoiceData) { + if (!$doku_error) { + echo "
";
+		echo "{$invoiceId}";
+		echo "\r\n";
+		print_r($InvoiceData);
+		exit;
+		
+		
+		
+		echo "
";
+		print_r($localApi);
+		print_r($orders_debug);
+		print_r($InvoiceData);
+		$GetConfigurationValue = localAPI('GetConfigurationValue', array('setting' => 'SystemURL'), $localApi['username']);
+		print_r($GetConfigurationValue);
+		exit;
+	} else {
+		echo "
";
+		print_r($doku_error);
+		exit;
+	}
+} else {
+	exit("NO INVOICE DATA");
+}
+*/
+//--------------------------------------------------------------------------------------------------------------------
+//--------------------------------------------------------------------------------------------------------------------
+//--------------------------------------------------------------------------------------------------------------------
+//--------------------------------------------------------------------------------------------------------------------
+/*
+**
+* CONTINUE
+**
+*/
+switch (strtolower($CallbackPage)) {
+	case 'notify':
+	default:
+		// Only for Notify
+		//**************************************************************************
+		//**************************************************************************
+		if (strtolower($CallbackPage) === strtolower('notify')) {
+			if (!$doku_error) {
+				//-----------------------------------------
+				// check if WORDS is match or not
+				//-----------------------------------------
+				if (strtolower($CheckNotifyPaymentStructure['WORDS']) !== strtolower($params_input['words'])) {
+					$doku_error = true;
+					$doku_error_msg[] = "Words from Notify-Structured not same with Dokuparams";
+				}
+			}
+		}
+		//**************************************************************************
+		//**************************************************************************
+		//------------------------------------------------------------------------------------------
+		if (!$doku_error) {
+			//---------------------------------
+			// IMPORTANT GLOBAL VARS
+			//---------------------------------
+			$invoiceId = (isset($invoiceId) ? $invoiceId : '');
+			$transactionId = False;
+			/**
+			 * Adding Unique generated Invoice-Id to Transaction-Id
+			 * Got bugs: DOKU always send:
+			 * Constant $transactionId
+			 * Using @$transaction_id_part
+			*/
+			switch ($Notify_Type) {
+				case 0: // Notify process
+					$transactionId = (isset($CheckNotifyPaymentStructure['APPROVALCODE']) ? $CheckNotifyPaymentStructure['APPROVALCODE'] : '');
+				break;
+				case 1: // Notify register
+					$transactionId = (isset($CheckNotifyPaymentStructure['BILLNUMBER']) ? $CheckNotifyPaymentStructure['BILLNUMBER'] : '');
+				break;
+				case 2: // Notify update
+					$transactionId = (isset($CheckNotifyPaymentStructure['BILLNUMBER']) ? $CheckNotifyPaymentStructure['BILLNUMBER'] : '');
+				break;
+			}
+			$transactionId .= "_";
+			switch ($Notify_Type) {
+				case 0: // Notify process
+					$transactionId .= (isset($CheckNotifyPaymentStructure['TRANSIDMERCHANT']) ? $CheckNotifyPaymentStructure['TRANSIDMERCHANT'] : '');
+					$paymentAmount = (isset($CheckNotifyPaymentStructure['AMOUNT']) ? $CheckNotifyPaymentStructure['AMOUNT'] : 0);
+					$paymentFee = (isset($CheckNotifyPaymentStructure['FEE']) ? $CheckNotifyPaymentStructure['FEE'] : 0);
+					$paymentEDU = (isset($CheckNotifyPaymentStructure['EDUSTATUS']) ? $CheckNotifyPaymentStructure['EDUSTATUS'] : 'NA'); // NA (Default)
+				break;
+				case 1: // Notify register
+					$transactionId .= (isset($CheckNotifyPaymentStructure['STATUSTYPE']) ? $CheckNotifyPaymentStructure['STATUSTYPE'] : '');
+					$paymentAmount = (isset($InvoiceData['total']) ? $InvoiceData['total'] : 0);
+					$paymentFee = (isset($CheckNotifyPaymentStructure['FEE']) ? $CheckNotifyPaymentStructure['FEE'] : 0);
+					$paymentEDU = (isset($CheckNotifyPaymentStructure['EDUSTATUS']) ? $CheckNotifyPaymentStructure['EDUSTATUS'] : 'NA'); // NA (Default)
+				break;
+				case 2: // Notify update
+					$transactionId .= (isset($CheckNotifyPaymentStructure['STATUSTYPE']) ? $CheckNotifyPaymentStructure['STATUSTYPE'] : '');
+					$paymentAmount = (isset($InvoiceData['total']) ? $InvoiceData['total'] : 0);
+					$paymentFee = (isset($CheckNotifyPaymentStructure['FEE']) ? $CheckNotifyPaymentStructure['FEE'] : 0);
+					$paymentEDU = (isset($CheckNotifyPaymentStructure['EDUSTATUS']) ? $CheckNotifyPaymentStructure['EDUSTATUS'] : 'NA'); // NA (Default)
+				break;
+			}
+			#
+			switch ($Notify_Type) {
+				case 0:
+					$paymentResponseStatus = (isset($dokuparams['RESULTMSG']) ? $dokuparams['RESULTMSG'] : ''); // SUCCESS, FAILED
+					$paymentResponseCode = (isset($dokuparams['RESPONSECODE']) ? $dokuparams['RESPONSECODE'] : ''); // 00 (Success), Other is failed
+					$paymentResponseType = (isset($dokuparams['VERIFYSTATUS']) ? $dokuparams['VERIFYSTATUS'] : ''); //APPROVE / REJECT / REVIEW / HIGHRISK
+				break;
+				case 1:
+					$paymentResponseStatus = (isset($dokuparams['STATUS']) ? $dokuparams['STATUS'] : ''); // SUCCESS, FAILED
+					$paymentResponseCode = (isset($dokuparams['ERRORCODE']) ? $dokuparams['ERRORCODE'] : ''); // 00 (Success), Other is failed
+					$paymentResponseType = (isset($dokuparams['STATUSTYPE']) ? $dokuparams['STATUSTYPE'] : ''); // G or T
+				break;
+				case 2:
+					$paymentResponseStatus = (isset($dokuparams['STATUS']) ? $dokuparams['STATUS'] : ''); // SUCCESS, FAILED
+					$paymentResponseCode = (isset($dokuparams['ERRORCODE']) ? $dokuparams['ERRORCODE'] : ''); // 00 (Success), Other is failed
+					$paymentResponseType = (isset($dokuparams['STATUSTYPE']) ? $dokuparams['STATUSTYPE'] : ''); // G or T
+				break;
+			}
+			switch (strtoupper($paymentResponseStatus)) {
+				case 'SUCCESS':
+				case 'VOIDED':
+					$success = TRUE;
+					switch ($Notify_Type) {
+						case 0:
+							if ((int)$paymentResponseCode > 0) {
+								$success = FALSE;
+								$doku_error = true;
+								$doku_error_msg[] = "RESPONSECODE should be 0";
+							}
+						break;
+						case 1:
+							if (strtoupper($paymentResponseType) !== strtoupper('G')) {
+								$success = FALSE;
+								$doku_error = true;
+								$doku_error_msg[] = "Status Type should be G for Notify Registration";
+							}
+						break;
+						case 2:
+							if (strtoupper($paymentResponseType) !== strtoupper('T')) {
+								$success = FALSE;
+								$doku_error = true;
+								$doku_error_msg[] = "Status Type should be T for Notify Registration";
+							}
+						break;
+					}
+				break;
+				case 'FAILED':
+					$success = FALSE;
+					$doku_error = true;
+					$doku_error_msg[] = "Payment Response Status is not Success: {$paymentResponseStatus}.";
+				break;
+				default:
+					$success = FALSE;
+					$doku_error = true;
+					$doku_error_msg[] = "Un-Expected Payment-Response-Status: (" . (__LINE__) . ") {$paymentResponseStatus}";
+				break;
+			}
+		}
+		break;
+	case 'redirect':
+	case 'regupdate':
+		//-------------------------------------------------------------------------------------------------------------
+		/**
+		 * Check Status Payment: Call DOKU
+		 * Applied only for Redirect-Page not for First Time Notify
+		 * ********************************************************
+		*/
+		//-------------------------------------------------------------------------------------------------------------
+		if (!$doku_error) {
+			// Make checking redirect-payment structured
+			# add transaction-words, transaction-status, transaction-code
+			$params_input['transaction_words'] = (isset($dokuparams['WORDS']) ? $dokuparams['WORDS'] : '');
+			$params_input['transaction_status'] = (isset($dokuparams['STATUSCODE']) ? strval($dokuparams['STATUSCODE']) : ''); // 00 = Success, Other = Failed
+			$params_input['transaction_channel'] = (isset($dokuparams['PAYMENTCHANNEL']) ? $dokuparams['PAYMENTCHANNEL'] : '');
+			$CheckRedirectPaymentStructure = $DokuPayment->create_payment_structure('redirect', 0, $params_input, $dokuparams);
+			if ($Log_Enabled) { logTransaction($gatewayParams['paymentmethod'], $CheckRedirectPaymentStructure, 'Subsciption Chek Redirect Structured'); }
+			if (strtolower($CallbackPage) === strtolower('redirect')) {
+				//-----------------------------------------
+				// check if WORDS is match or not (On 'redirect' stage)
+				//-----------------------------------------
+				if (strtolower($params_input['transaction_words']) !== strtolower($CheckRedirectPaymentStructure['WORDS'])) {
+					$doku_error = true;
+					$doku_error_msg[] = "Words from Redirect-Structured not same with Dokuparams. (" . (__LINE__) . ")";
+					redirecting_page_to_invoice($Redirect_Url);
+					exit;
+				}
+			}
+		}
+		if (!$doku_error) {
+				/*
+				TRANSIDMERCHANT => 2017091216074812
+				PAYMENTCHANNEL => 17
+				BILLNUMBER => 20170912160712
+				AMOUNT => 2469305.00
+				WORDS => 6064d5cdc802395df1ffc7bc93c41bb22874322e
+				SESSIONID => 00dd18b360d7ed1f8c509a19b19be8d4
+				CUSTOMERID => 1
+				*/
+			if (!in_array(strtolower($order_status), array('paid', 'pending'))) {
+				//---------------------------------
+				// IMPORTANT GLOBAL VARS
+				//---------------------------------
+				$invoiceId = (isset($invoiceId) ? $invoiceId : '');
+				$transactionId = False;
+				//
+				// Adding Unique generated Invoice-Id to Transaction-Id
+				// Got bugs: DOKU always send:
+				// Constant APPROVALCODE for first time Notify (DOKU Always send same Approval-code foe each invoice-id)
+				// Using @$merchant_transaction[0]
+				//
+				switch ($Notify_Type) {
+					case 0:
+						$transactionId = (isset($CheckNotifyPaymentStructure['BILLNUMBER']) ? $CheckNotifyPaymentStructure['BILLNUMBER'] : '');
+						$paymentResponseStatus = (isset($dokuparams['RESULTMSG']) ? $dokuparams['RESULTMSG'] : ''); // SUCCESS, FAILED
+						$paymentResponseCode = (isset($dokuparams['RESPONSECODE']) ? $dokuparams['RESPONSECODE'] : ''); // 00 (Success), Other is failed
+						$paymentResponseType = (isset($dokuparams['VERIFYSTATUS']) ? $dokuparams['VERIFYSTATUS'] : ''); //APPROVE / REJECT / REVIEW / HIGHRISK
+					break;
+					case 1:
+						$transactionId = (isset($dokuparams['BILLNUMBER']) ? $dokuparams['BILLNUMBER'] : '');
+						$paymentResponseStatus = (isset($dokuparams['STATUS']) ? $dokuparams['STATUS'] : ''); // SUCCESS, FAILED
+						$paymentResponseCode = (isset($dokuparams['ERRORCODE']) ? $dokuparams['ERRORCODE'] : ''); // 00 (Success), Other is failed
+						$paymentResponseType = (isset($dokuparams['STATUSTYPE']) ? $dokuparams['STATUSTYPE'] : ''); // G or T
+					break;
+					case 2:
+						$transactionId = (isset($dokuparams['BILLNUMBER']) ? $dokuparams['BILLNUMBER'] : '');
+						$paymentResponseStatus = (isset($dokuparams['STATUS']) ? $dokuparams['STATUS'] : ''); // SUCCESS, FAILED
+						$paymentResponseCode = (isset($dokuparams['ERRORCODE']) ? $dokuparams['ERRORCODE'] : ''); // 00 (Success), Other is failed
+						$paymentResponseType = (isset($dokuparams['STATUSTYPE']) ? $dokuparams['STATUSTYPE'] : ''); // G or T
+					break;
+				}
+				$transactionId .= "_";
+				switch ($Notify_Type) {
+					case 0:
+						$transactionId .= (isset($CheckNotifyPaymentStructure['TRANSIDMERCHANT']) ? $CheckNotifyPaymentStructure['TRANSIDMERCHANT'] : '');
+						$paymentAmount = (isset($dokuparams['AMOUNT']) ? $dokuparams['AMOUNT'] : 0);
+						$paymentFee = (isset($dokuparams['FEE']) ? $dokuparams['FEE'] : 0);
+						$paymentEDU = (isset($dokuparams['EDUSTATUS']) ? $dokuparams['EDUSTATUS'] : 'NA'); // NA (Default)
+					break;
+					case 1:
+						$transactionId .= (isset($dokuparams['STATUSTYPE']) ? $dokuparams['STATUSTYPE'] : '');
+						$paymentAmount = (isset($InvoiceData['total']) ? $InvoiceData['total'] : 0);
+						$paymentFee = (isset($CheckRedirectPaymentStructure['FEE']) ? $CheckRedirectPaymentStructure['FEE'] : 0);
+						$paymentEDU = (isset($CheckRedirectPaymentStructure['EDUSTATUS']) ? $CheckRedirectPaymentStructure['EDUSTATUS'] : 'NA'); // NA (Default)
+					break;
+					case 2:
+						$transactionId .= (isset($dokuparams['STATUSTYPE']) ? $dokuparams['STATUSTYPE'] : '');
+						$paymentAmount = (isset($InvoiceData['total']) ? $InvoiceData['total'] : 0);
+						$paymentFee = (isset($CheckRedirectPaymentStructure['FEE']) ? $CheckRedirectPaymentStructure['FEE'] : 0);
+						$paymentEDU = (isset($CheckRedirectPaymentStructure['EDUSTATUS']) ? $CheckRedirectPaymentStructure['EDUSTATUS'] : 'NA'); // NA (Default)
+					break;
+				}
+			} else {
+				redirecting_page_to_invoice($Redirect_Url);
+				exit;
+			}
+		}
+		if (!$doku_error) {
+			// Log payment-status
+			if ($Log_Enabled) { logTransaction($gatewayParams['paymentmethod'], $dokuparams, "(#{$invoiceId}) " . 'Payment Status From Redirected (Not Paid)'); }
+			/*
+			if (strtolower($order_status) !== strtolower('paid')) {
+				// Make Error if Redirected from Un-Success Payment
+				$doku_error = true;
+				$doku_error_msg[] = "Redirected from failed payment: Maybe WHMCS Payment-Gateway-Module not activate payment-check status.";
+			}
+			*/
+		}
+		//-------------------------------------------------------------------------------------------------------------
+		break;
+}
+/*
+**
+* CONTINUE
+**
+*/
+switch (strtolower($CallbackPage)) {
+	case 'notify':
+	case 'regupdate':
+	default:
+		if (!$doku_error) {
+			//---------------------------------
+			/**
+			 * Check Callback Transaction ID.
+			 *
+			 * Performs a check for any existing transactions with the same given
+			 * transaction number.
+			 *
+			 * Performs a die upon encountering a duplicate.
+			 *
+			 * @param string $transactionId Unique Transaction ID
+			*/
+			if (strtolower($order_status) !== strtolower('paid')) {
+				switch ($Notify_Type) {
+					case 0:
+						if (!in_array(strtolower($order_status), array('paid', 'draft'))) {
+							checkCbTransID($transactionId);
+						}
+					break;
+					case 1:
+						if (!in_array(strtolower($order_status), array('paid', 'draft'))) {
+							checkCbTransID($transactionId);
+						}
+					break;
+					case 2:
+						if (!in_array(strtolower($order_status), array('paid', 'draft'))) {
+							checkCbTransID($transactionId);
+						}
+					break;
+				}
+			}
+		}
+	break;
+	case 'redirect':
+		if (!$doku_error) {
+			//---------------------------------
+			/**
+			 * Check Callback Transaction ID.
+			 *
+			 * Performs a check for any existing transactions with the same given
+			 * transaction number.
+			 *
+			 * Performs a die upon encountering a duplicate.
+			 *
+			 * @param string $transactionId Unique Transaction ID
+			*/
+			if (strtolower($order_status) !== strtolower('paid')) {
+				switch ($Notify_Type) {
+					case 0:
+						if (!in_array(strtolower($order_status), array('paid'))) {
+							checkCbTransID($transactionId);
+						}
+					break;
+					case 1:
+						if (!in_array(strtolower($order_status), array('paid', 'draft'))) {
+							checkCbTransID($transactionId);
+						}
+					break;
+					case 2:
+						if (!in_array(strtolower($order_status), array('paid', 'draft'))) {
+							checkCbTransID($transactionId);
+						}
+					break;
+				}
+			}
+		}
+	break;
+}
+/*
+**
+* CONTINUE
+**
+*/
+switch (strtolower($CallbackPage)) {
+	// allow only Doku IP Address for payment
+	case 'notify':
+	case 'regupdate':
+		if (!$doku_error) {
+			$doku_ip_address = '103.10.129.0/24';
+			$this_ip_address = (isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '0.0.0.0');
+			if (substr($DokuPayment->get_ip_address($this_ip_address), 0, 10) != substr($doku_ip_address, 0, 10)) {
+				$doku_error = true;
+				$doku_error_msg[] = "Invalid IP Address, Not from doku sandbox env: {$DokuPayment->get_ip_address()}";
+				$success = FALSE;
+			}
+		}
+	break;
+	default:
+		// do nothing
+	break;
+}
+
+/*
+**
+* CONTINUE
+**
+*/
+switch (strtolower($CallbackPage)) {
+	case 'notify':
+	case 'regupdate':
+	default:
+		if (!$doku_error) {
+			if ($success) {
+				/**
+				 * Add Invoice Payment.
+				 *
+				 * Applies a payment transaction entry to the given invoice ID.
+				 *
+				 * @param int $invoiceId         Invoice ID
+				 * @param string $transactionId  Transaction ID
+				 * @param float $paymentAmount   Amount paid (defaults to full balance)
+				 * @param float $paymentFee      Payment fee (optional)
+				 * @param string $gatewayModule  Gateway module name
+				 */
+				$localApi['command'] = 'UpdateInvoice';
+				$localApi['data'] = array(
+					'invoiceid'			=> $invoiceId,
+					'status'			=> 'Draft',
+				);
+				if (strtolower($order_status) !== strtolower('paid')) {
+					switch ($Notify_Type) {
+						case 0:
+							$REQUEST_METHOD_MSG = "CONTINUE";
+							if ($Log_Enabled) { logTransaction($gatewayParams['paymentmethod'], $XMLPaymentStatus, 'Success'); }
+							addInvoicePayment($invoiceId, $transactionId, $paymentAmount, $paymentFee, $gatewayModuleName);
+							if ($Log_Enabled) { logTransaction($gatewayParams['paymentmethod'], "Notify Process", "(#{$invoiceId}) Logger"); }
+						break;
+						case 1:
+							$REQUEST_METHOD_MSG = "CONTINUE";
+							if ($Log_Enabled) { logTransaction($gatewayParams['paymentmethod'], $XMLPaymentStatus, 'Pending: Subscription Register'); }
+							/*
+							try {
+								$InvoiceUpdate = localAPI($localApi['command'], $localApi['data'], $localApi['username']);
+								logTransaction($gatewayParams['paymentmethod'], $InvoiceUpdate, 'Pending: InvoiceUpdate - Register');
+							} catch (Exception $ex) {
+								$doku_error = true;
+								$doku_error_msg[] = "Cannot update Invoice Status On Notify: Subscription Register.";
+							}
+							*/
+							addInvoicePayment($invoiceId, $transactionId, $paymentAmount, $paymentFee, $gatewayModuleName);
+							if ($Log_Enabled) { logTransaction($gatewayParams['paymentmethod'], "Notify Register", "(#{$invoiceId}) Logger"); }
+						break;
+						case 2:
+							$REQUEST_METHOD_MSG = "CONTINUE";
+							if ($Log_Enabled) { logTransaction($gatewayParams['paymentmethod'], $XMLPaymentStatus, 'Pending: Subscription Update'); }
+							/*
+							try {
+								$InvoiceUpdate = localAPI($localApi['command'], $localApi['data'], $localApi['username']);
+								logTransaction($gatewayParams['paymentmethod'], $InvoiceUpdate, 'Pending: InvoiceUpdate - Update');
+							} catch (Exception $ex) {
+								$doku_error = true;
+								$doku_error_msg[] = "Cannot update Invoice Status On Notify: Subscription Update.";
+							}
+							*/
+							addInvoicePayment($invoiceId, $transactionId, $paymentAmount, $paymentFee, $gatewayModuleName);
+							if ($Log_Enabled) { logTransaction($gatewayParams['paymentmethod'], "Notify Update", "(#{$invoiceId}) Logger"); }
+						break;
+					}
+				}
+			}
+		} else {
+			if ($Log_Enabled) { logTransaction($gatewayParams['paymentmethod'], array('STOP' => $doku_error_msg), "(doku_error): Failed on Notify"); }
+		}
+	break;
+	case 'redirect':
+		if (!$doku_error) {
+			if ($success) {
+				/**
+				 * Add Invoice Payment.
+				 *
+				 * Applies a payment transaction entry to the given invoice ID.
+				 *
+				 * @param int $invoiceId         Invoice ID
+				 * @param string $transactionId  Transaction ID
+				 * @param float $paymentAmount   Amount paid (defaults to full balance)
+				 * @param float $paymentFee      Payment fee (optional)
+				 * @param string $gatewayModule  Gateway module name
+				 */
+				$localApi['command'] = 'UpdateInvoice';
+				$localApi['data'] = array(
+					'invoiceid'			=> $invoiceId,
+					'status'			=> 'Draft',
+				);
+				if (strtolower($order_status) !== strtolower('paid')) {
+					switch ($Notify_Type) {
+						case 0:
+							$REQUEST_METHOD_MSG = "Subscription Redirect Process";
+							if ($Log_Enabled) { logTransaction($gatewayParams['paymentmethod'], $XMLPaymentStatus, 'Success'); }
+							addInvoicePayment($invoiceId, $transactionId, $paymentAmount, $paymentFee, $gatewayModuleName);
+							if ($Log_Enabled) { logTransaction($gatewayParams['paymentmethod'], "Redirect Process", "(#{$invoiceId}) Logger"); }
+						break;
+						case 1:
+							$REQUEST_METHOD_MSG = "Subscription Redirect Register";
+							if ($Log_Enabled) { logTransaction($gatewayParams['paymentmethod'], $XMLPaymentStatus, 'Pending: Redirect Register'); }
+							/*
+							try {
+								$InvoiceUpdate = localAPI($localApi['command'], $localApi['data'], $localApi['username']);
+							} catch (Exception $ex) {
+								$doku_error = true;
+								$doku_error_msg[] = "Cannot update Invoice Status On Register: Subscription Register.";
+							}
+							*/
+							if ($Log_Enabled) { logTransaction($gatewayParams['paymentmethod'], "Redirect Register", "(#{$invoiceId}) Logger"); }
+						break;
+						case 2:
+							$REQUEST_METHOD_MSG = "Subscription Redirect Update";
+							if ($Log_Enabled) { logTransaction($gatewayParams['paymentmethod'], $XMLPaymentStatus, 'Pending: Redirect Update'); }
+							/*
+							try {
+								$InvoiceUpdate = localAPI($localApi['command'], $localApi['data'], $localApi['username']);
+							} catch (Exception $ex) {
+								$doku_error = true;
+								$doku_error_msg[] = "Cannot update Invoice Status On Register: Subscription Update.";
+							}
+							*/
+							if ($Log_Enabled) { logTransaction($gatewayParams['paymentmethod'], "Redirect Update", "(#{$invoiceId}) Logger"); }
+						break;
+					}
+				}
+			}
+		} else {
+			if ($Log_Enabled) { logTransaction($gatewayParams['paymentmethod'], $doku_error_msg, "(doku_error): Failed on Redirect"); }
+		}
+	break;
+}
+/*
+**
+* CONTINUE
+**
+*/
+switch (strtolower($CallbackPage)) {
+	case 'review':
+	case 'identify':
+		if (!$doku_error) {
+			echo $REQUEST_METHOD_MSG;
+		} else {
+			print_r($doku_error_msg);
+		}
+	case 'notify':
+	default:	
+		if (!$doku_error) {
+			echo $REQUEST_METHOD_MSG;
+		} else {
+			echo "STOP\r\n";
+			print_r($REQUEST_METHOD_MSG);
+			if ($Log_Enabled) { logTransaction($gatewayParams['paymentmethod'], array('STOP' => $REQUEST_METHOD_MSG), 'DOKU ERROR MSG'); }
+		}
+		break;
+	case 'redirect':
+		if (!$doku_error) {
+			if ($Log_Enabled) { logTransaction($gatewayParams['paymentmethod'], $REQUEST_METHOD_MSG, "(#{$invoiceId}) " . 'Echo From Redirect'); }
+			redirecting_page_to_invoice($Redirect_Url);
+		} else {
+			echo "
";
+			print_r($doku_error_msg);
+		}
+		break;
+}	
+
+
+
+/*
+**
+* CONTINUE
+**
+*/
+/*
+switch (strtolower($CallbackPage)) {
+	case 'review':
+	case 'identify':
+		die();
+		break;
+	case 'redirect':
+		#############################################################################################################
+		# CALL VOID?
+		#############################################################################################################
+		//-------------------------------------------------------------------------------------------------------------------
+		if ($Void_Enabled) {
+			if (!$doku_error) {
+				$VoidParams = array(
+					'transaction_id'		=> (isset($XMLPaymentStatus['TRANSIDMERCHANT']) ? $XMLPaymentStatus['TRANSIDMERCHANT'] : ''),
+					'transaction_session'	=> (isset($XMLPaymentStatus['SESSIONID']) ? $XMLPaymentStatus['SESSIONID'] : ''),
+					'transaction_currency'	=> (isset($XMLPaymentStatus['CURRENCY']) ? $XMLPaymentStatus['CURRENCY'] : '360'),
+					'transaction_channel'	=> (isset($XMLPaymentStatus['PAYMENTCHANNEL']) ? $XMLPaymentStatus['PAYMENTCHANNEL'] : ''),
+				);
+				$createVoidStructure = $DokuPayment->create_payment_structure('void', 0, $VoidParams, $dokuparams);
+				if (isset($createVoidStructure['WORDS_STRING'])) {
+					unset($createVoidStructure['WORDS_STRING']);
+				}
+				$headers = $DokuPayment->create_curl_headers($DokuPayment->dokupayment_headers);
+				try {
+					$create_void = $DokuPayment->create_curl_request('POST', $DokuPayment->endpoint['void'], 'API.Context (http://whmcs.alumniparhata.org) - Change this as you wish.', $headers, $createVoidStructure, 30);
+				} catch (Exception $ex) {
+					$doku_error = true;
+					$doku_error_msg[] = "Error exception for create void: {$ex->getMessage()}.";
+					throw $ex;
+				}
+			}
+			if (!$doku_error) {
+				if (!isset($create_void['response']['body'])) {
+					$doku_error = true;
+					$doku_error_msg[] = "There is no body response from Void response.";
+				}
+			}
+			if (!$doku_error) {
+				$StringVoidStatus = trim($create_void['response']['body']);
+				switch (strtoupper($StringVoidStatus)) {
+					case 'FAILED':
+						// Do what to do if Failed VOID
+						logTransaction($gatewayParams['paymentmethod'], $create_void, "Payment Void: ". strtoupper($StringVoidStatus));
+					break;
+					case 'SUCCESS':
+						// Do what to do if Success VOID
+						logTransaction($gatewayParams['paymentmethod'], $create_void, "Payment Void: ". strtoupper($StringVoidStatus));
+					break;
+					default:
+						// DO what to do if Un-expected VOID
+						logTransaction($gatewayParams['paymentmethod'], $create_void, "Payment Void: UN-EXPECTED ({$StringVoidStatus})");
+					break;
+				}
+			}
+		}
+		#############################################################################################################
+		//-------------------------------------------------------------------------------------------------------------------
+		if (!$doku_error) {
+			switch (strtoupper($paymentResponseStatus)) {
+				case 'SUCCESS':
+					$success = TRUE;
+				break;
+				case 'VOIDED':
+					if ($paymentResponseCode == '00') {
+						$success = TRUE;
+					} else {
+						$success = FALSE;
+						$doku_error = true;
+						$doku_error_msg[] = "Payment Response Code is Not : 00.";
+					}
+				break;
+				case 'FAILED':
+					$success = FALSE;
+					$doku_error = true;
+					$doku_error_msg[] = "Payment Response Status is not Success: {$paymentResponseStatus}.";
+				break;
+				default:
+					$success = FALSE;
+					$doku_error = true;
+					$doku_error_msg[] = "Un-Expected Payment-Response-Status on Line (" . (__LINE__) . "): {$paymentResponseStatus}";
+					$doku_error_msg['XMLPaymentStatus'] = $XMLPaymentStatus;
+				break;
+			}
+		}
+		if (!$doku_error) {
+			if (strtolower($order_status) !== strtolower('paid')) {
+				$REQUEST_METHOD_MSG = "REDIRECT:Continue";
+			} else {
+				echo "redirect - 3
\n"; + echo $Redirect_Url; + // redirecting_page_to_invoice($Redirect_Url); + exit; + } + } + break; + case 'notify': + default: + $REQUEST_METHOD_MSG = "CONTINUE"; + break; +} +*/ diff --git a/modules/gateways/dokuhosted.php b/modules/gateways/dokuhosted.php new file mode 100644 index 0000000..bb92af0 --- /dev/null +++ b/modules/gateways/dokuhosted.php @@ -0,0 +1,1568 @@ + 'DOKU Payment Gateway - Indonesia', + 'APIVersion' => '1.2', // Use API Version 1.1 + 'DisableLocalCredtCardInput' => true, + 'TokenisedStorage' => false, + ); +} + +//--------------- +// URL show to admin page +Class dokuhosted_DokuAdmin { + public static $notify = false; + public static $redirect = false; + public static $review = false; + public static $identify = false; + public static $DOKUCONFIGS; + public function __construct($configs = array()) { + $this->set_protocol(self::getDokuPaymentProtocol()); + $this->protocol = (isset($this->protocol) ? $this->protocol : $this->get_protocol()); + $this->set_hostname(self::getDokuPaymentHost()); + $this->hostname = (isset($this->hostname) ? $this->hostname : $this->get_hostname()); + $this->set_url('notify', "{$this->protocol}{$this->hostname}modules/gateways/callback/dokuhosted.php?page=notify"); + $this->set_url('redirect', "{$this->protocol}{$this->hostname}modules/gateways/callback/dokuhosted.php?page=redirect"); + $this->set_url('review', "{$this->protocol}{$this->hostname}modules/gateways/callback/dokuhosted.php?page=review"); + $this->set_url('identify', "{$this->protocol}{$this->hostname}modules/gateways/callback/dokuhosted.php?page=identify"); + // Set GLOBAL $DOKUCONFIGS + self::$DOKUCONFIGS = $configs; + } + public static function getDokuPaymentConfigs($Vars) { + $configs = array(); + if (!isset(self::$DOKUCONFIGS)) { + return false; + } + switch (strtolower($Vars)) { + case 'channels': + $configs = (isset(self::$DOKUCONFIGS['paymentchannels']) ? self::$DOKUCONFIGS['paymentchannels'] : NULL); + break; + case 'acquirers': + $configs = (isset(self::$DOKUCONFIGS['paymentacquirers']) ? self::$DOKUCONFIGS['paymentacquirers'] : NULL); + break; + case 'tenors': + $configs = (isset(self::$DOKUCONFIGS['paymenttenors']) ? self::$DOKUCONFIGS['paymenttenors'] : NULL); + break; + } + return $configs; + } + public static function getDokuPaymentProtocol() { + if (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) { + if ( $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' ) { + $_SERVER['HTTPS'] = 'on'; + $_SERVER['SERVER_PORT'] = 443; + } + } + $protocol = 'http://'; + if (isset($_SERVER['HTTPS'])) { + $protocol = (($_SERVER['HTTPS'] == 'on') ? 'https://' : 'http'); + } else { + $protocol = (isset($_SERVER["SERVER_PROTOCOL"]) ? $_SERVER["SERVER_PROTOCOL"] : 'http'); + $protocol = ((strtolower(substr($protocol, 0, 5)) =='https') ? 'https://': 'http://'); + } + return $protocol; + } + public static function getDokuPaymentHost() { + $currentPath = (isset($_SERVER['SCRIPT_NAME']) ? $_SERVER['SCRIPT_NAME'] : ''); + $pathInfo = pathinfo(dirname($currentPath)); + $hostName = (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ''); + $return = $hostName; + $return .= ((substr($hostName, -1) == '/') ? '' : '/'); + return $return; + } + public static function _GET(){ + $__GET = array(); + $request_uri = ((isset($_SERVER['REQUEST_URI']) && (!empty($_SERVER['REQUEST_URI']))) ? $_SERVER['REQUEST_URI'] : '/'); + $_get_str = explode('?', $request_uri); + if( !isset($_get_str[1]) ) return $__GET; + $params = explode('&', $_get_str[1]); + foreach ($params as $p) { + $parts = explode('=', $p); + $__GET[$parts[0]] = isset($parts[1]) ? $parts[1] : ''; + } + return $__GET; + } + public function set_hostname($hostname) { + $this->hostname = $hostname; + return $this; + } + public function get_hostname() { + return $this->hostname; + } + public function set_protocol($protocol) { + $this->protocol = $protocol; + return $this; + } + public function get_protocol() { + return $this->protocol; + } + public static function set_url($type, $url) { + switch (strtolower($type)) { + case 'notify': + default: + self::$notify = $url; + break; + case 'redirect': + self::$redirect = $url; + break; + case 'review': + self::$review = $url; + break; + case 'identify': + self::$identify = $url; + break; + } + } +} +// Start new DokuAdmin instance +/* +error_reporting(E_ALL); +ini_set('display_startup_errors', true); +ini_set('display_errors', true); +*/ +// Include @DOKUCONFIGS +$configfile = (dirname(__FILE__). '/dokuhosted/dokuhosted-config.php'); +if (!file_exists($configfile)) { + Exit("Required configs file does not exists."); +} +require($configfile); +if (!isset($DOKUCONFIGS)) { + Exit("There is no DOKUCONFIGS of included config file."); +} +$DokuAdmin = new dokuhosted_DokuAdmin($DOKUCONFIGS); +/** + * Define gateway configuration options. + * + * The fields you define here determine the configuration options that are + * presented to administrator users when activating and configuring your + * payment gateway module for use. + * + * Supported field types include: + * * text + * * password + * * yesno + * * dropdown + * * radio + * * textarea + * + * Examples of each field type and their possible configuration parameters are + * provided in the sample function below. + * + * @return array + */ +// Require doku-payment class instance +require('dokuhosted/dokuhosted-whmcs.php'); +function dokuhosted_config() { + $configs = array( + // the friendly display name for a payment gateway should be + // defined here for backwards compatibility + 'FriendlyName' => array( + 'Type' => 'System', + 'Value' => 'DOKU - Standard Payment', + 'Description' => 'DOKU is an online payment platform that processes payments through many different methods, including Credit Card, ATM Transfer and DOKU Wallet. Check us out on http://www.doku.com', + ), + 'Pembatas-Description-Payment-Gateway' => array( + 'FriendlyName' => '', + 'Type' => 'hidden', + 'Size' => '72', + 'Default' => '', + 'Description' => ' DOKU is an online payment platform that processes payments through many different methods, including Credit Card, ATM Transfer and DOKU Wallet. Check us out on http://www.doku.com', + ), + 'Description-Payment-Gateway' => array( + 'FriendlyName' => 'Description', + 'Type' => 'textarea', + 'Rows' => '8', + 'Cols' => '72', + 'Default' => 'DOKU is an online payment platform that processes payments through many different methods, including Credit Card, ATM Transfer and DOKU Wallet. Check us out on http://www.doku.com', + 'Description' => '', + ), + // a text field type allows for single line text input + # Development + //------------- + 'Pembatas-Sandbox' => array( + "FriendlyName" => "(*)", + "Type" => 'hidden', + "Size" => "64", + "Default" => '', + "Description" => 'Development Params', + ), + //------------- + 'MallId' => array( + 'FriendlyName' => 'Development: Mall ID', + 'Type' => 'text', + 'Size' => '25', + 'Default' => '', + 'Description' => 'Enter your Mall ID here', + ), + /* + 'ShopName' => array( + 'FriendlyName' => 'Sandbox: Shop Name', + 'Type' => 'text', + 'Size' => '25', + 'Default' => '', + 'Description' => 'Enter Shop Name here', + ), + */ + 'ChainMerchant' => array( + 'FriendlyName' => 'Development: Chain Merchant (Default is: NA)', + 'Type' => 'text', + 'Size' => '25', + 'Default' => 'NA', + 'Description' => 'Enter Chain Merchant (Default is: NA)', + ), + 'SharedKey' => array( + 'FriendlyName' => 'Development: Shared Key', + 'Type' => 'text', + 'Size' => '25', + 'Default' => '', + 'Description' => 'Enter Shared Key you got from DOKU Dashboard', + ), + //------------- + 'Pembatas-Live' => array( + "FriendlyName" => "(*)", + "Type" => 'hidden', + "Size" => "64", + "Default" => '', + "Description" => 'Production Params', + ), + //------------- + # Live + 'MallId_Live' => array( + 'FriendlyName' => '(*)Production: Mall ID', + 'Type' => 'text', + 'Size' => '25', + 'Default' => '', + 'Description' => 'Enter your Mall ID here', + ), + 'ChainMerchant_Live' => array( + 'FriendlyName' => '(*)Production: Chain Merchant Name (Default is: NA)', + 'Type' => 'text', + 'Size' => '25', + 'Default' => 'NA', + 'Description' => 'Enter Chain Merchant Name (Default is: NA)', + ), + 'SharedKey_Live' => array( + 'FriendlyName' => '(*)Production: Shared Key', + 'Type' => 'text', + 'Size' => '25', + 'Default' => '', + 'Description' => 'Enter Shared Key you got from DOKU Dashboard', + ), + //------------- + 'Pembatas-Global-Params' => array( + "FriendlyName" => "", + "Type" => 'hidden', + "Size" => "64", + "Default" => '', + "Description" => 'Global Params', + ), + //------------- + # GLOBAL + // the dropdown field type renders a select menu of options (LOGGER) + 'Log-Enabled' => array( + 'FriendlyName' => "Use Logger on Transaction Log? (Billing > Gateway Log)", + 'Type' => "yesno", + 'Description' => "Tick this box to enable Logging", + ), + // the dropdown field type renders a select menu of options + 'Environment' => array( + 'FriendlyName' => 'Environment Mode', + 'Type' => 'dropdown', + 'Options' => array( + 'sandbox' => 'Development', + 'live' => 'Production', + ), + 'Description' => 'Choose environment development or production', + ), + "EDU-Enabled" => array( + 'FriendlyName' => "Use EDU?", + 'Type' => "yesno", + 'Description' => "Tick this box to enable EDU", + ), + "Identify-Enabled" => array( + 'FriendlyName' => "Use Identify?", + 'Type' => "yesno", + 'Description' => "Tick this box to enable DOKU Identify", + ), + //"Void-Enabled" => array( + // 'FriendlyName' => "Use Void?", + // 'Type' => "yesno", + // 'Description' => "Tick this box to enable Payment Void", + // ), + # + "PaymentCheck-Enabled" => array( + 'FriendlyName' => "Enable Payment Check During Notify and Redirect", + 'Type' => "yesno", + 'Description' => "Tick this box to enable Payment Check (We recomended you enabled payment-check to verified payment)", + ), + 'URL-Notify' => array( + "FriendlyName" => "Enter your URL Notify to DOKU Dasboard", + "Type" => 'hidden', + "Size" => "64", + "Default" => dokuhosted_DokuAdmin::$notify, + "Description" => dokuhosted_DokuAdmin::$notify, + ), + 'URL-Redirect' => array( + "FriendlyName" => "Enter your URL Redirect to DOKU Dasboard", + "Type" => 'hidden', + "Size" => "64", + "Default" => dokuhosted_DokuAdmin::$redirect, + "Description" => dokuhosted_DokuAdmin::$redirect, + ), + 'URL-Review' => array( + "FriendlyName" => "Enter your URL Review to DOKU Dasboard", + "Type" => 'hidden', + "Size" => "64", + "Default" => dokuhosted_DokuAdmin::$review, + "Description" => dokuhosted_DokuAdmin::$review, + ), + 'URL-Identify' => array( + "FriendlyName" => "Enter your URL Identify to DOKU Dasboard", + "Type" => 'hidden', + "Size" => "64", + "Default" => dokuhosted_DokuAdmin::$identify, + "Description" => dokuhosted_DokuAdmin::$identify, + ), + // + 'Local-Api-Admin-Username' => array( + 'FriendlyName' => '(*) WHMCS Admin Username for using WHMCS::localAPI().', + 'Type' => 'text', + 'Size' => '22', + 'Default' => '', + 'Description' => 'Enter your WHMCS Admin Username for using WHMCS::localAPI().', + ), + //---------------------------------------------------------------------------- + 'Pembatas-Payment-Channel' => array( + "FriendlyName" => "(*) Select Enabled Payment Channel", + "Type" => 'hidden', + "Size" => "64", + "Default" => '', + "Description" => '
Please tick to enable payment channels
', + ), + //----------------------------------------------------------------------------- + + ); + // Add payment-channels + $getDokuPaymentChannels = dokuhosted_DokuAdmin::getDokuPaymentConfigs('channels'); + if (count($getDokuPaymentChannels) > 0) { + foreach ($getDokuPaymentChannels as $val) { + $payment_channel_key = "Payment-Channel-"; + $payment_channel_key .= (isset($val[0]) ? $val[0] : '00'); + $configs[$payment_channel_key] = array( + 'FriendlyName' => '', + 'Type' => 'yesno', + 'Default' => (isset($val[0]) ? $val[0] : '00'), + 'Description' => (isset($val[1]) ? $val[1] : 'All'), + ); + } + } + //------------------------------------------------------------------------------------ + // INSTALLMENT PAYMENT (Credit Card) + //------------------------------------------------------------------------------------ + $configs["Installment-Enabled"] = array( + 'FriendlyName' => 'Use Installment', + 'Type' => 'dropdown', + 'Options' => array( + 'SALE' => 'SALE', + 'ONUS' => 'ONUS INSTALLMENT', + 'OFFUS' => 'OFFUS INSTALLEMENT', + ), + ); + //------------------------------------------------------ + $configs['Pembatas-Payment-Acquirer-Bank'] = array( + "FriendlyName" => "::", + "Type" => 'hidden', + "Size" => "64", + "Default" => '', + "Description" => '
ACQUIRER BANK FOR INSTALLMENT
', + ); + //-------------- + // GLOBAL OBJECT FOR PROMO OF EACH BANK TENORS + $GLOBAL_ACQUIRER_BANKS = array( + 'onus' => [], + 'offus' => [], + ); + # Get Banks + $getDokuPaymentAcquirers = dokuhosted_DokuAdmin::getDokuPaymentConfigs('acquirers'); + //----------------------- + // ON US INSTALLMENT + //----------------------- + $configs['Pembatas-Payment-Acquirer-Bank-Onus'] = array( + "FriendlyName" => "(*) Payment Acquirer Banks (ON US)", + "Type" => 'hidden', + "Size" => "64", + "Default" => '', + "Description" => '
Please tick to enable payment acquirers bank
', + ); + if (isset($getDokuPaymentAcquirers['onus'])) { + if (count($getDokuPaymentAcquirers['onus']) > 0) { + foreach ($getDokuPaymentAcquirers['onus'] as $keval) { + $bank_acquirer_code = (isset($keval[0]) ? $keval[0] : '100'); // 100 (BNI as Default Bank) + $bank_acquirer_name = (isset($keval[1]) ? $keval[1] : 'Bank BNI'); // 100 (BNI as Default Bank) + $GLOBAL_ACQUIRER_BANKS['onus'][] = array( + 'code' => $bank_acquirer_code, + 'name' => $bank_acquirer_name, + 'tenor' => array(), + ); + } + } + } + if (count($GLOBAL_ACQUIRER_BANKS['onus']) > 0) { + foreach ($GLOBAL_ACQUIRER_BANKS['onus'] as $k => $val) { + # Get Tenors + $getDokuPaymentTenors = dokuhosted_DokuAdmin::getDokuPaymentConfigs('tenors'); + if (count($getDokuPaymentTenors) > 0) { + foreach ($getDokuPaymentTenors as $keval) { + $tenor_acquirer_code = (isset($keval[0]) ? $keval[0] : '03'); // (03 Months as Default Tenor) + $tenor_acquirer_name = (isset($keval[1]) ? $keval[1] : '03 Bulan'); // (03 Months as Default Tenor) + $val_tenor = array( + 'code' => $tenor_acquirer_code, + 'name' => $tenor_acquirer_name, + 'promo' => '', + ); + $GLOBAL_ACQUIRER_BANKS['onus'][$k]['tenor'][] = $val_tenor; + } + } + } + } + # Build into @configs + if (count($GLOBAL_ACQUIRER_BANKS['onus']) > 0) { + foreach ($GLOBAL_ACQUIRER_BANKS['onus'] as $key => $val) { + // Bank installment key + $bank_installment_key = "Bank-Installment-Acquirer-Onus-"; + $bank_installment_key .= (isset($val['code']) ? $val['code'] : '100'); // 100 = BNI + # add to configs + $configs[$bank_installment_key] = array( + 'FriendlyName' => '', + 'Type' => 'yesno', + 'Default' => (isset($val['code']) ? $val['code'] : '100'), // 100 = BNI + 'Description' => "" . (isset($val['name']) ? $val['name'] : 'Bank BNI..?') . "", // BNI as Default + ); + $bank_installment_code = (isset($val['code']) ? (string)$val['code'] : ''); + if (strtolower($bank_installment_code) === strtolower('100')) { + $configs["{$bank_installment_key}-00"] = array( + 'FriendlyName' => 'Installment Promo Code For ' . (isset($val['name']) ? $val['name'] : 'Bank BNI..?'), + 'Type' => 'text', + 'Size' => '22', + 'Default' => '', + 'Description' => 'Insert Promo Code For ' . (isset($val['name']) ? $val['name'] : 'Bank BNI..?'), + ); + } + // Bank promo for each available tenors + if (isset($val['tenor'])) { + if (count($val['tenor']) > 0) { + foreach ($val['tenor'] as $keval) { + $bank_installment_tenor = $bank_installment_key; + $bank_installment_tenor .= "-"; + $bank_installment_tenor .= (isset($keval['code']) ? $keval['code'] : '03'); // 03 Months as default + # add to configs (tenor) + $configs[$bank_installment_tenor] = array( + 'FriendlyName' => '', + 'Type' => 'yesno', + 'Default' => (isset($keval['code']) ? $keval['code'] : '03'), + 'Description' => (isset($keval['name']) ? $keval['name'] : '03 Bulan'), + ); + $bank_installment_tenor_promo = "{$bank_installment_tenor}-PromoId"; + # add to configs (promo) + // except BNI + if (strtolower($bank_installment_code) !== strtolower('100')) { + $configs[$bank_installment_tenor_promo] = array( + 'FriendlyName' => 'Installment Promo Code For ' . (isset($keval['name']) ? $keval['name'] : '03 Bulan'), + 'Type' => 'text', + 'Size' => '22', + 'Default' => '', + 'Description' => 'Insert Promo Code For ' . (isset($keval['name']) ? $keval['name'] : '03 Bulan') . ' On ' . (isset($val['name']) ? $val['name'] : 'Bank BNI..?'), + ); + } else { + $configs[$bank_installment_tenor_promo] = array( + 'FriendlyName' => '', + 'Type' => 'hidden', + 'Size' => '22', + 'Default' => '001', + 'Description' => '', + ); + } + } + } + } + } + } + //----------------------- + // OFF US INSTALLMENT + //----------------------- + $configs['Pembatas-Payment-Acquirer-Bank-Offus'] = array( + "FriendlyName" => "(*) Payment Acquirer Banks (OFF US)", + "Type" => 'hidden', + "Size" => "64", + "Value" => '', + "Description" => '
Please tick to enable payment acquirers bank
', + ); + if (isset($getDokuPaymentAcquirers['offus'])) { + if (count($getDokuPaymentAcquirers['offus']) > 0) { + foreach ($getDokuPaymentAcquirers['offus'] as $keval) { + $bank_acquirer_code = (isset($keval[0]) ? $keval[0] : '100'); // 100 (BNI as Default Bank) + $bank_acquirer_name = (isset($keval[1]) ? $keval[1] : 'Bank BNI'); // 100 (BNI as Default Bank) + $GLOBAL_ACQUIRER_BANKS['offus'][] = array( + 'code' => $bank_acquirer_code, + 'name' => $bank_acquirer_name, + 'tenor' => array(), + ); + } + } + } + if (count($GLOBAL_ACQUIRER_BANKS['offus']) > 0) { + foreach ($GLOBAL_ACQUIRER_BANKS['offus'] as $k => $val) { + # Get Tenors + $getDokuPaymentTenors = dokuhosted_DokuAdmin::getDokuPaymentConfigs('tenors'); + if (count($getDokuPaymentTenors) > 0) { + foreach ($getDokuPaymentTenors as $keval) { + $tenor_acquirer_code = (isset($keval[0]) ? $keval[0] : '03'); // (03 Months as Default Tenor) + $tenor_acquirer_name = (isset($keval[1]) ? $keval[1] : '03 Bulan'); // (03 Months as Default Tenor) + $val_tenor = array( + 'code' => $tenor_acquirer_code, + 'name' => $tenor_acquirer_name, + 'promo' => '', + ); + $GLOBAL_ACQUIRER_BANKS['offus'][$k]['tenor'][] = $val_tenor; + } + } + } + } + # Build into @configs + if (count($GLOBAL_ACQUIRER_BANKS['offus']) > 0) { + foreach ($GLOBAL_ACQUIRER_BANKS['offus'] as $key => $val) { + // Bank installment key + $bank_installment_key = "Bank-Installment-Acquirer-Offus-"; + $bank_installment_key .= (isset($val['code']) ? $val['code'] : '100'); // 100 = BNI + // For OFFUS because same $val['code'] create unique identify by index loop + $bank_installment_key .= "-{$key}"; + # add to configs + $configs[$bank_installment_key] = array( + 'FriendlyName' => '', + 'Type' => 'yesno', + 'Default' => (isset($val['code']) ? $val['code'] : '100'), // 100 = BNI + 'Description' => "" . (isset($val['name']) ? $val['name'] : 'Bank BNI..?') . "", // BNI as Default + ); + $bank_installment_code = (isset($val['code']) ? (string)$val['code'] : ''); + if (strtolower($bank_installment_code) === strtolower('000')) { + $configs["{$bank_installment_key}-00"] = array( + 'FriendlyName' => 'Installment Promo Code For ' . (isset($val['name']) ? $val['name'] : 'Bank BNI..?'), + 'Type' => 'text', + 'Size' => '22', + 'Default' => '', + 'Description' => 'Insert Promo Code For ' . (isset($val['name']) ? $val['name'] : 'Bank BNI..?'), + ); + } + // Bank promo for each available tenors + if (isset($val['tenor'])) { + if (count($val['tenor']) > 0) { + foreach ($val['tenor'] as $keval) { + $bank_installment_tenor = $bank_installment_key; + $bank_installment_tenor .= "-"; + $bank_installment_tenor .= (isset($keval['code']) ? $keval['code'] : '03'); // 03 Months as default + # add to configs (tenor) + $configs[$bank_installment_tenor] = array( + 'FriendlyName' => '', + 'Type' => 'yesno', + 'Default' => (isset($keval['code']) ? $keval['code'] : '03'), + 'Description' => (isset($keval['name']) ? $keval['name'] : '03 Bulan'), + ); + $bank_installment_tenor_promo = "{$bank_installment_tenor}-PromoId"; + # add to configs (promo) + // except BNI + if (strtolower($bank_installment_code) !== strtolower('000')) { + $configs[$bank_installment_tenor_promo] = array( + 'FriendlyName' => 'Installment Promo Code For ' . (isset($keval['name']) ? $keval['name'] : '03 Bulan'), + 'Type' => 'text', + 'Size' => '22', + 'Default' => '', + 'Description' => 'Insert Promo Code For ' . (isset($keval['name']) ? $keval['name'] : '03 Bulan') . ' On ' . (isset($val['name']) ? $val['name'] : 'Bank BNI..?'), + ); + } else { + $configs[$bank_installment_tenor_promo] = array( + 'FriendlyName' => '', + 'Type' => 'hidden', + 'Size' => '22', + 'Default' => '001', + 'Description' => '', + ); + } + } + } + } + } + } + //---------------------------------------------------------------------------------------------- + /* + $configs['Custom-Data-To-Showing'] = array( + 'FriendlyName' => 'Textarea Field', + 'Type' => 'textarea', + 'Rows' => '3', + 'Cols' => '60', + 'Default' => print_r(array('g' => $GLOBAL_ACQUIRER_BANKS, 'b' => $getDokuPaymentAcquirers), true), + 'Description' => 'Freeform multi-line text input field', + ); + */ + //------------------------------------------------------------------------------------ + return $configs; +} + +/** + * Payment link. + * + * Required by third party payment gateway modules only. + * + * Defines the HTML output displayed on an invoice. Typically consists of an + * HTML form that will take the user to the payment gateway endpoint. + * + * @param array $params Payment Gateway Module Parameters + * + * @see https://developers.whmcs.com/payment-gateways/third-party-gateway/ + * + * @return string + */ +function dokuhosted_link($params) { + $Log_Enabled = FALSE; + if (isset($params['Log-Enabled'])) { + $Log_Enabled = ((strtolower($params['Log-Enabled']) == 'on') ? TRUE : FALSE); + } + /* + echo "
";
+	print_r($params);
+	exit;
+	*/
+	$Environment = (isset($params['Environment']) ? $params['Environment'] : 'sandbox'); // Sandbox as Default-Environment
+	if (!is_string($Environment) && ((!is_array($Environment)) || (!is_object($Environment)))) {
+		if (strtolower($Environment) === strtolower('live')) {
+			// Gateway Configuration Parameters
+			$MallId = (isset($params['MallId_Live']) ? $params['MallId_Live'] : '');
+			$ShopName = (isset($params['ShopName_Live']) ? $params['ShopName_Live'] : '');
+			$ChainMerchant = (isset($params['ChainMerchant_Live']) ? $params['ChainMerchant_Live'] : 'NA');
+			$SharedKey = (isset($params['SharedKey_Live']) ? $params['SharedKey_Live'] : '');
+		} else {
+			// Gateway Configuration Parameters
+			$MallId = (isset($params['MallId']) ? $params['MallId'] : '');
+			$ShopName = (isset($params['ShopName']) ? $params['ShopName'] : '');
+			$ChainMerchant = (isset($params['ChainMerchant']) ? $params['ChainMerchant'] : 'NA');
+			$SharedKey = (isset($params['SharedKey']) ? $params['SharedKey'] : '');
+		}
+	} else {
+		// Gateway Configuration Parameters
+		$MallId = (isset($params['MallId']) ? $params['MallId'] : '');
+		$ShopName = (isset($params['ShopName']) ? $params['ShopName'] : '');
+		$ChainMerchant = (isset($params['ChainMerchant']) ? $params['ChainMerchant'] : 'NA');
+		$SharedKey = (isset($params['SharedKey']) ? $params['SharedKey'] : '');
+	}
+	$LocalApiAdminUsername = (isset($params['Local-Api-Admin-Username']) ? $params['Local-Api-Admin-Username'] : '');
+    //$ExchangeCurrency = (isset($params['ExchangeCurrency']) ? $params['ExchangeCurrency'] : '');
+	//---------
+	// Create DokuPayment Instance
+	//---------
+	$DokuConfigs = array(
+		'isofile'		=> 'dokuhosted/assets/iso3166.json',
+		'merchant'		=> array(
+			'mallid'			=> $MallId,
+			'shopname'			=> $ShopName,
+			'chainmerchant'		=> $ChainMerchant,
+			'sharedkey'			=> $SharedKey,
+		),
+		'endpoint'		=> (is_string($Environment) ? strtolower($Environment) : 'sandbox'), // sandbox as default
+	);
+	##
+	# DokuPayment Instance
+	##
+	$DokuPayment = new dokuhosted_DokuPayment($DokuConfigs);
+	//-----------------------------------------------------
+    // Invoice Parameters
+    $invoiceId = $params['invoiceid'];
+    $description = $params["description"];
+    $amount = $params['amount'];
+    $currencyCode = $params['currency'];
+    // Client Parameters
+    $firstname = $params['clientdetails']['firstname'];
+    $lastname = $params['clientdetails']['lastname'];
+	$fullname = $params['clientdetails']['fullname'];
+    $email = $params['clientdetails']['email'];
+    $address1 = $params['clientdetails']['address1'];
+    $address2 = $params['clientdetails']['address2'];
+    $city = $params['clientdetails']['city'];
+    $state = $params['clientdetails']['state'];
+    $postcode = $params['clientdetails']['postcode'];
+    $country = $params['clientdetails']['country'];
+    $phone = $params['clientdetails']['phonenumber'];
+    // System Parameters
+    $companyName = $params['companyname'];
+    $systemUrl = $params['systemurl'];
+    $returnUrl = $params['returnurl'];
+    $langPayNow = $params['langpaynow'];
+    $moduleDisplayName = $params['name'];
+    $moduleName = $params['paymentmethod'];
+    $whmcsVersion = $params['whmcsVersion'];
+	// POSTFIELDS
+	$postfields = array();
+    $postfields['username'] = $email;
+    $postfields['invoice_id'] = $invoiceId;
+    $postfields['description'] = $description;
+    $postfields['amount'] = $amount;
+    $postfields['currency'] = $currencyCode;
+    $postfields['first_name'] = $firstname;
+    $postfields['last_name'] = $lastname;
+	$postfields['fullname'] = $fullname;
+    $postfields['email'] = $email;
+    $postfields['address1'] = $address1;
+    $postfields['address2'] = $address2;
+    $postfields['city'] = $city;
+    $postfields['state'] = $state;
+    $postfields['postcode'] = $postcode;
+    $postfields['country'] = $country;
+    $postfields['phone'] = $phone;
+    $postfields['callback_url'] = $systemUrl . ((substr($systemUrl, -1) == '/') ? '' : '/') . 'modules/gateways/callback/' . $moduleName . '.php';
+    $postfields['return_url'] = $returnUrl;
+	// Create Unique invoice_id
+	$postfields['invoice_id'] = $postfields['invoice_id'] . '_' . (date('YmdHis', time()));
+	####postfields['invoice_id'] = $postfields['invoice_id'];
+	// AVAILABLE PAYMENT CHANNELS
+	$PaymentChannels = array();
+	$getDokuPaymentChannels = dokuhosted_DokuAdmin::getDokuPaymentConfigs('channels');
+	if (count($getDokuPaymentChannels) > 0) {
+		foreach ($getDokuPaymentChannels as $keval) {
+			if (isset($keval[0])) {
+				if (isset($params["Payment-Channel-{$keval[0]}"])) {
+					if ($params["Payment-Channel-{$keval[0]}"] == 'on') {
+						$channel_code = $keval[0];
+						$channel_name = (isset($keval[1]) ? $keval[1] : '--Un-Named Payment Channel--');
+						$PaymentChannels[] = array(
+							'code'				=> $channel_code,
+							'name'				=> $channel_name,
+						);
+					}
+				}
+			}
+		}
+	}
+	// AVAILABLE INSTALLMENT BANKS
+	//--------------
+	// MAKE GLOBAL_ACQUIRER_BANKS
+	// GLOBAL OBJECT FOR PROMO OF EACH BANK TENORS
+	$GLOBAL_ACQUIRER_BANKS = array(
+		'onus'		=> [],
+		'offus'		=> [],
+	);
+	//$GLOBAL_ACQUIRER_BANKS = array();
+	# Get Banks
+	$getDokuPaymentAcquirers = dokuhosted_DokuAdmin::getDokuPaymentConfigs('acquirers');
+	//-----------------------
+	// ON US INSTALLMENT
+	//-----------------------
+	if (isset($getDokuPaymentAcquirers['onus'])) {
+		if (count($getDokuPaymentAcquirers['onus']) > 0) {
+			foreach ($getDokuPaymentAcquirers['onus'] as $key => $keval) {
+				if (isset($keval[0])) {
+					if (isset($params["Bank-Installment-Acquirer-Onus-{$keval[0]}"])) {
+						if ($params["Bank-Installment-Acquirer-Onus-{$keval[0]}"] == 'on') {
+							$bank_code = (isset($keval[0]) ? $keval[0] : '100'); // 100 (BNI as Default Bank)
+							$bank_name = (isset($keval[1]) ? $keval[1] : 'Bank BNI'); // 100 (BNI as Default Bank)
+							$GLOBAL_ACQUIRER_BANKS['onus'][] = array(
+								'index'			=> "Bank-Installment-Acquirer-Onus-{$keval[0]}",
+								'code'			=> $bank_code,
+								'name'			=> $bank_name,
+								'tenor'			=> array(),
+							);
+						}
+					}
+				}
+			}
+		}
+	}
+	if (count($GLOBAL_ACQUIRER_BANKS['onus']) > 0) {
+		foreach ($GLOBAL_ACQUIRER_BANKS['onus'] as $k => $val) {
+			# Get Tenors
+			$getDokuPaymentTenors = dokuhosted_DokuAdmin::getDokuPaymentConfigs('tenors');
+			if ((string)$val['code'] !== strval('100')) { // If NOT BNI
+				if (count($getDokuPaymentTenors) > 0) {
+					foreach ($getDokuPaymentTenors as $keval) {
+						$tenor_code = (isset($keval[0]) ? $keval[0] : '03'); // (03 Months as Default Tenor)
+						$tenor_name = (isset($keval[1]) ? $keval[1] : '03 Bulan'); // (03 Months as Default Tenor)
+						if (isset($params["{$val['index']}-{$tenor_code}"])) {
+							if ($params["{$val['index']}-{$tenor_code}"] == 'on') {
+								$val_tenor = array(
+									'code'		=> $tenor_code,
+									'name'		=> $tenor_name,
+									'promo'		=> false,
+								);
+								if (isset($params["{$val['index']}-{$tenor_code}-PromoId"])) {
+									if (!empty($params["{$val['index']}-{$tenor_code}-PromoId"]) && (strlen($params["{$val['index']}-{$tenor_code}-PromoId"]) > 0)) {
+										$val_tenor['promo'] = (string)$params["{$val['index']}-{$tenor_code}-PromoId"];
+									}
+								}
+								// Add to GLOBAL_ACQUIRER_BANKS
+								if ($val_tenor['promo'] && ($val_tenor['promo'] != '')) {
+									$GLOBAL_ACQUIRER_BANKS['onus'][$k]['tenor'][] = $val_tenor;
+								}
+							}
+						}
+					}
+				}
+			} else {
+				if (count($getDokuPaymentTenors) > 0) {
+					foreach ($getDokuPaymentTenors as $keval) {
+						$tenor_code = (isset($keval[0]) ? $keval[0] : '03'); // (03 Months as Default Tenor)
+						$tenor_name = (isset($keval[1]) ? $keval[1] : '03 Bulan'); // (03 Months as Default Tenor)
+						if (isset($params["{$val['index']}-{$tenor_code}"])) {
+							if ($params["{$val['index']}-{$tenor_code}"] == 'on') {
+								$val_tenor = array(
+									'code'		=> $tenor_code,
+									'name'		=> $tenor_name,
+									'promo'		=> false,
+								);
+								if (isset($params["{$val['index']}-00"])) { // Only BNI using 00 as Tenor_Code
+									if (!empty($params["{$val['index']}-00"]) && (strlen($params["{$val['index']}-00"]) > 0)) {
+										$val_tenor['promo'] = (string)$params["{$val['index']}-00"];
+									}
+								}
+								// Add to GLOBAL_ACQUIRER_BANKS
+								if ($val_tenor['promo'] && ($val_tenor['promo'] != '')) {
+									$GLOBAL_ACQUIRER_BANKS['onus'][$k]['tenor'][] = $val_tenor;
+								}
+							}
+						}
+					}
+				}
+			}
+		}
+	}
+	//-----------------------
+	// OFF US INSTALLMENT
+	//-----------------------
+	if (isset($getDokuPaymentAcquirers['offus'])) {
+		if (count($getDokuPaymentAcquirers['offus']) > 0) {
+			foreach ($getDokuPaymentAcquirers['offus'] as $key => $keval) {
+				if (isset($keval[0])) {
+					if (isset($params["Bank-Installment-Acquirer-Offus-{$keval[0]}-{$key}"])) {
+						if ($params["Bank-Installment-Acquirer-Offus-{$keval[0]}-{$key}"] == 'on') {
+							$bank_code = (isset($keval[0]) ? $keval[0] : '100'); // 100 (BNI as Default Bank)
+							$bank_name = (isset($keval[1]) ? $keval[1] : 'Bank BNI'); // 100 (BNI as Default Bank)
+							$GLOBAL_ACQUIRER_BANKS['offus'][] = array(
+								'index'			=> "Bank-Installment-Acquirer-Offus-{$keval[0]}-{$key}",
+								'code'			=> $bank_code,
+								'name'			=> $bank_name,
+								'tenor'			=> array(),
+							);
+						}
+					}
+				}
+			}
+		}
+	}
+	if (count($GLOBAL_ACQUIRER_BANKS['offus']) > 0) {
+		foreach ($GLOBAL_ACQUIRER_BANKS['offus'] as $k => $val) {
+			# Get Tenors
+			$getDokuPaymentTenors = dokuhosted_DokuAdmin::getDokuPaymentConfigs('tenors');
+			if ((string)$val['code'] !== strval('000')) { // If NOT BNI
+				if (count($getDokuPaymentTenors) > 0) {
+					foreach ($getDokuPaymentTenors as $keval) {
+						$tenor_code = (isset($keval[0]) ? $keval[0] : '03'); // (03 Months as Default Tenor)
+						$tenor_name = (isset($keval[1]) ? $keval[1] : '03 Bulan'); // (03 Months as Default Tenor)
+						if (isset($params["{$val['index']}-{$tenor_code}"])) {
+							if ($params["{$val['index']}-{$tenor_code}"] == 'on') {
+								$val_tenor = array(
+									'code'		=> $tenor_code,
+									'name'		=> $tenor_name,
+									'promo'		=> false,
+								);
+								if (isset($params["{$val['index']}-{$tenor_code}-PromoId"])) {
+									if (!empty($params["{$val['index']}-{$tenor_code}-PromoId"]) && (strlen($params["{$val['index']}-{$tenor_code}-PromoId"]) > 0)) {
+										$val_tenor['promo'] = (string)$params["{$val['index']}-{$tenor_code}-PromoId"];
+									}
+								}
+								// Add to GLOBAL_ACQUIRER_BANKS
+								if ($val_tenor['promo'] && ($val_tenor['promo'] != '')) {
+									$GLOBAL_ACQUIRER_BANKS['offus'][$k]['tenor'][] = $val_tenor;
+								}
+							}
+						}
+					}
+				}
+			} else {
+				if (count($getDokuPaymentTenors) > 0) {
+					foreach ($getDokuPaymentTenors as $keval) {
+						$tenor_code = (isset($keval[0]) ? $keval[0] : '03'); // (03 Months as Default Tenor)
+						$tenor_name = (isset($keval[1]) ? $keval[1] : '03 Bulan'); // (03 Months as Default Tenor)
+						if (isset($params["{$val['index']}-{$tenor_code}"])) {
+							if ($params["{$val['index']}-{$tenor_code}"] == 'on') {
+								$val_tenor = array(
+									'code'		=> $tenor_code,
+									'name'		=> $tenor_name,
+									'promo'		=> false,
+								);
+								if (isset($params["{$val['index']}-00"])) { // Only BNI using 00 as Tenor_Code
+									if (!empty($params["{$val['index']}-00"]) && (strlen($params["{$val['index']}-00"]) > 0)) {
+										$val_tenor['promo'] = (string)$params["{$val['index']}-00"];
+									}
+								}
+								// Add to GLOBAL_ACQUIRER_BANKS
+								if ($val_tenor['promo'] && ($val_tenor['promo'] != '')) {
+									$GLOBAL_ACQUIRER_BANKS['offus'][$k]['tenor'][] = $val_tenor;
+								}
+							}
+						}
+					}
+				}
+			}
+		}
+	}
+	//---------------------------------------------
+	# Make Front-End of available installment banks
+	$BankInstallmentActive = array(
+		'onus'				=> array(),
+		'offus'				=> array(),
+	);
+	$InstallmentBanks = array();
+	// From On-us
+	if (count($GLOBAL_ACQUIRER_BANKS['onus']) > 0) {
+		foreach ($GLOBAL_ACQUIRER_BANKS['onus'] as $k => $keval) {
+			/**
+			 * @string index
+			 * @string code
+			 * @string name
+			 * @array tenor
+			 **** @string code
+				* @string name
+			 **** @string promo
+			*/
+			if (isset($keval['tenor']) && (isset($keval['code']))) {
+				$installment_code = $keval['code'];
+				if (count($keval['tenor']) > 0) {
+					array_push($BankInstallmentActive['onus'], $keval);
+					//$InstallmentBanks[] = $keval;
+				}
+			}
+		}
+	}
+	// From Off-us
+	if (count($GLOBAL_ACQUIRER_BANKS['offus']) > 0) {
+		foreach ($GLOBAL_ACQUIRER_BANKS['offus'] as $k => $keval) {
+			/**
+			 * @string index
+			 * @string code
+			 * @string name
+			 * @array tenor
+			 **** @string code
+				* @string name
+			 **** @string promo
+			*/
+			if (isset($keval['tenor']) && (isset($keval['code']))) {
+				$installment_code = $keval['code'];
+				if (count($keval['tenor']) > 0) {
+					array_push($BankInstallmentActive['offus'], $keval);
+					//$InstallmentBanks[] = $keval;
+				}
+			}
+		}
+	}
+	//-------------------------
+	// Get Active
+	//----
+	if (strtoupper($params['Installment-Enabled']) === strtoupper('ONUS')) {
+		if (count($BankInstallmentActive['onus']) > 0) {
+			foreach ($BankInstallmentActive['onus'] as $keval) {
+				$InstallmentBanks[] = $keval;
+			}
+		}
+	} else if (strtoupper($params['Installment-Enabled']) === strtoupper('OFFUS')) {
+		if (count($BankInstallmentActive['offus']) > 0) {
+			foreach ($BankInstallmentActive['offus'] as $keval) {
+				$InstallmentBanks[] = $keval;
+			}
+		}
+	}
+	//-------------------------
+	/*
+	echo "
";
+	ksort($params);
+	print_r($params);
+	echo "
"; + print_r($InstallmentBanks); + + + echo "
"; + echo "
"; + echo "
"; + print_r($getDokuPaymentAcquirers); + print_r($GLOBAL_ACQUIRER_BANKS); + + exit; + */ + //------------------------------------------------------------------------------------------------ + /* + $InstallmentBanks = array(); + $getDokuPaymentAcquirers = dokuhosted_DokuAdmin::getDokuPaymentConfigs('acquirers'); + if (count($getDokuPaymentAcquirers) > 0) { + foreach ($getDokuPaymentAcquirers as $keval) { + if (isset($keval[0])) { + if (isset($params["Bank-Installment-Acquirer-{$keval[0]}"])) { + if ($params["Bank-Installment-Acquirer-{$keval[0]}"] == 'on') { + $bank_code = $keval[0]; + $bank_name = (isset($keval[1]) ? $keval[1] : '--Un-Named Acquirer Bank Name--'); + $bank_promo = ""; + if (isset($params["Payment-Installment-Promoid-{$keval[0]}"])) { + $bank_promo = $params["Payment-Installment-Promoid-{$keval[0]}"]; + } + $InstallmentBanks[] = array( + 'code' => $bank_code, + 'name' => $bank_name, + 'promo' => $bank_promo, + ); + } + } + } + } + } + // Available Tenors + $InstallmentTenors = array(); + $getDokuPaymentTenors = dokuhosted_DokuAdmin::getDokuPaymentConfigs('tenors'); + if (count($getDokuPaymentTenors) > 0) { + foreach ($getDokuPaymentTenors as $keval) { + if (isset($keval[0])) { + if (isset($params["Payment-Installment-Tenor-{$keval[0]}"])) { + if ($params["Payment-Installment-Tenor-{$keval[0]}"] == 'on') { + $tenor_code = (string)$keval[0]; + $tenor_name = (isset($keval[1]) ? $keval[1] : '--Un-Named Tenor Installment Name--'); + $InstallmentTenors[] = array( + 'code' => (string)$tenor_code, + 'name' => $tenor_name, + ); + } + } + } + } + } + */ + //------------------------------------------------------------------------------------------------ + + + //Log for orders + if ($Log_Enabled) { + logTransaction($moduleName, $params, "(WHMCS-params)"); + } + + ########################### + # HTML Output + ########################### + $returnHtml = ""; + # URL Of Payment-Request + //--------------------------------------------------- + // Start Of Form + $returnHtml .= '
'; + // Create input to DokuPayment Instance + $params_input = array( + 'transaction_id' => $postfields['invoice_id'], // Create unique request_id + 'transaction_currency' => strtoupper(substr($postfields['currency'], 0, 2)), + 'transaction_datetime' => date('YmdHis', time()), + 'transaction_session' => (isset($params['clientdetails']['uuid']) ? $params['clientdetails']['uuid'] : ''), + 'amount_total' => 0, + ); + $params_input['transaction_session'] = md5($params_input['transaction_session']); + # Temporary for fees items, nex from $logsync['item_lists'] + ########################################################### + $params_input['items'] = Array(); + $item_invoices = array( + 'item_id' => (isset($params['invoicenum']) ? $params['invoicenum'] : 1), + 'order_price' => (isset($params['amount']) ? $params['amount'] : 0), + 'order_unit' => 1, + 'order_item_name' => $postfields['description'], + ); + array_push($params_input['items'], $item_invoices); + foreach ($params_input['items'] as $val) { + $params_input['amount_total'] += ($val['order_price'] * $val['order_unit']); + } + $user_input = array( + 'name' => $postfields['fullname'], // Should be an user input tmn account + 'email' => $postfields['email'], // Should be an user input tmn email or myarena email + 'shipping_address' => array( // Input or generate randomly or API to MyArena Account? + 'forename' => $postfields['first_name'], + 'surname' => $postfields['last_name'], + 'fullname' => $postfields['fullname'], + 'email' => $postfields['email'], + 'phone' => $postfields['phone'], + 'SHIPPING_ADDRESS' => '', + 'SHIPPING_CITY' => $postfields['city'], + 'SHIPPING_STATE' => $postfields['state'], + 'SHIPPING_COUNTRY' => $postfields['country'], + 'SHIPPING_ZIPCODE' => $postfields['postcode'], + 'ADDITIONALDATA' => $postfields['description'], + ), + ); + $user_input['shipping_address']['SHIPPING_ADDRESS'] .= (isset($postfields['address1']) ? $postfields['address1'] : ''); + $user_input['shipping_address']['SHIPPING_ADDRESS'] .= (isset($postfields['address2']) ? ((strlen($postfields['address2']) > 0) ? " {$postfields['address2']}" : '') : ''); + # Create Verify Payment Structure + $createPaymentStructure = $DokuPayment->create_payment_structure('create', 0, $params_input, $user_input, $params_input['items'], $user_input['shipping_address']); + $PaymentStructure = array( + 'words_sha1' => (isset($createPaymentStructure['WORDS']) ? $createPaymentStructure['WORDS'] : ""), + 'words_string' => (isset($createPaymentStructure['WORDS_STRING']) ? $createPaymentStructure['WORDS_STRING'] : ""), + 'session_id' => (isset($createPaymentStructure['SESSIONID']) ? $createPaymentStructure['SESSIONID'] : ""), + ); + // Generate Unique SESSIONID Every single payment + $PaymentStructure['session_id'] = sha1("{$PaymentStructure['session_id']}{$DokuPayment->generate_transaction_id()}"); + if ((isset($createPaymentStructure['WORDS_STRING'])) && (isset($createPaymentStructure['SESSIONID']))) { + unset($createPaymentStructure['WORDS_STRING']); + $PaymentStructureJson = json_encode($createPaymentStructure, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT); + // do any log .... + $makepayment_data = json_decode($PaymentStructureJson, true, 512, JSON_BIGINT_AS_STRING); + ksort($makepayment_data); + // Sanitize URL + $makepayment_data = $DokuPayment->sanitize_url_parameter($makepayment_data); + if ($Log_Enabled) { + logTransaction($moduleName, $makepayment_data, "(WHMCS) REQUEST-PAYMENT"); + } + //------------------ + // return HTML + if (count($makepayment_data) > 0) { + foreach ($makepayment_data as $key => $val) { + $returnHtml .= ""; + } + } + } + // payment-channel selections + if (count($PaymentChannels) > 0) { + $returnHtml .= '
Select Payment Channel
'; + $returnHtml .= '
'; + $returnHtml .= ''; + $returnHtml .= '
'; + // Another params for payment-channel selected + $add_html = ""; + $add_html .= ''; + // ADD TO @$returnHtml + $returnHtml .= $add_html; + } + // payment installment acquirer banks, promo, and tenor + //-------------- + $returnHtml .= ''; + //-------------------------------------------------------------------------------------------------------------------- + + //echo "
";
+	//print_r($tenor_printout);
+	//exit;
+	
+	
+	//---------------------------------------------------
+	// End of Form
+	$returnHtml .= '';
+	// Create padding
+	$returnHtml .= '
'; + $returnHtml .= '
 
'; + $returnHtml .= '
'; + // DOKU Description + $dokuDesc = (isset($params['Description-Payment-Gateway']) ? $params['Description-Payment-Gateway'] : ''); + $dokuDesc = filter_var($dokuDesc, FILTER_SANITIZE_STRING); + $returnHtml .= '
'; + $returnHtml .= '
doku' . $dokuDesc . '
'; + $returnHtml .= '
'; + + //Javascript for payment-channel-placeholder + $js = ""; + $js .= ''; + /* + for(var k in result) { + console.log(k, result[k]); + } + --Create an input type dynamically. + var element = document.createElement("input"); + --Assign different attributes to the element. + element.setAttribute("type", "hidden"); + element.setAttribute("name", "TENOR"); + element.setAttribute("id", "TENOR"); + element.setAttribute("value", "TENOR-VALUE"); + */ + // Submit button + $returnHtml .= ''.$params['langpaynow'].''; + + // Javascript for submit + $returnHtml .= $js; + $js_submit = ''; + + $returnHtml .= $js_submit; + + + // Show @params values + //$returnHtml .= '
';
+	//$returnHtml .= print_r($params, true);
+	//$returnHtml .= '
'; + + + + + // Debug all params values + /* + $returnHtml .= '
'; + $returnHtml .= '
';
+	//$returnHtml .= "\n\n";
+	$returnHtml .= '
'; + $returnHtml .= '
'; + */ + /* + + + + $returnHtml .= "
"; + */ + return $returnHtml; +} + +/** + * Refund transaction. + * + * Called when a refund is requested for a previously successful transaction. + * + * @param array $params Payment Gateway Module Parameters + * + * @see https://developers.whmcs.com/payment-gateways/refunds/ + * + * @return array Transaction response status + */ +function dokuhosted_refund($params) { + // Gateway Configuration Parameters + $accountId = $params['accountID']; + $secretKey = $params['secretKey']; + $testMode = $params['testMode']; + $dropdownField = $params['dropdownField']; + $radioField = $params['radioField']; + $textareaField = $params['textareaField']; + + // Transaction Parameters + $transactionIdToRefund = $params['transid']; + $refundAmount = $params['amount']; + $currencyCode = $params['currency']; + + // Client Parameters + $firstname = $params['clientdetails']['firstname']; + $lastname = $params['clientdetails']['lastname']; + $email = $params['clientdetails']['email']; + $address1 = $params['clientdetails']['address1']; + $address2 = $params['clientdetails']['address2']; + $city = $params['clientdetails']['city']; + $state = $params['clientdetails']['state']; + $postcode = $params['clientdetails']['postcode']; + $country = $params['clientdetails']['country']; + $phone = $params['clientdetails']['phonenumber']; + + // System Parameters + $companyName = $params['companyname']; + $systemUrl = $params['systemurl']; + $langPayNow = $params['langpaynow']; + $moduleDisplayName = $params['name']; + $moduleName = $params['paymentmethod']; + $whmcsVersion = $params['whmcsVersion']; + + // perform API call to initiate refund and interpret result + + return array( + // 'success' if successful, otherwise 'declined', 'error' for failure + 'status' => 'success', + // Data to be recorded in the gateway log - can be a string or array + 'rawdata' => $responseData, + // Unique Transaction ID for the refund transaction + 'transid' => $refundTransactionId, + // Optional fee amount for the fee value refunded + 'fees' => $feeAmount, + ); +} + +/** + * Cancel subscription. + * + * If the payment gateway creates subscriptions and stores the subscription + * ID in tblhosting.subscriptionid, this function is called upon cancellation + * or request by an admin user. + * + * @param array $params Payment Gateway Module Parameters + * + * @see https://developers.whmcs.com/payment-gateways/subscription-management/ + * + * @return array Transaction response status + */ +function dokuhosted_cancelSubscription($params) +{ + // Gateway Configuration Parameters + $accountId = $params['accountID']; + $secretKey = $params['secretKey']; + $testMode = $params['testMode']; + $dropdownField = $params['dropdownField']; + $radioField = $params['radioField']; + $textareaField = $params['textareaField']; + + // Subscription Parameters + $subscriptionIdToCancel = $params['subscriptionID']; + + // System Parameters + $companyName = $params['companyname']; + $systemUrl = $params['systemurl']; + $langPayNow = $params['langpaynow']; + $moduleDisplayName = $params['name']; + $moduleName = $params['paymentmethod']; + $whmcsVersion = $params['whmcsVersion']; + + // perform API call to cancel subscription and interpret result + + return array( + // 'success' if successful, any other value for failure + 'status' => 'success', + // Data to be recorded in the gateway log - can be a string or array + 'rawdata' => $responseData, + ); +} + + + diff --git a/modules/gateways/dokuhosted/assets/doku-banner.png b/modules/gateways/dokuhosted/assets/doku-banner.png new file mode 100644 index 0000000..87367f4 Binary files /dev/null and b/modules/gateways/dokuhosted/assets/doku-banner.png differ diff --git a/modules/gateways/dokuhosted/assets/doku-button.png b/modules/gateways/dokuhosted/assets/doku-button.png new file mode 100644 index 0000000..c5c8803 Binary files /dev/null and b/modules/gateways/dokuhosted/assets/doku-button.png differ diff --git a/modules/gateways/dokuhosted/assets/iso3166.json b/modules/gateways/dokuhosted/assets/iso3166.json new file mode 100644 index 0000000..72c60a4 --- /dev/null +++ b/modules/gateways/dokuhosted/assets/iso3166.json @@ -0,0 +1 @@ +{"AF":{"alpha-2":"AF","alpha-3":"AFG","numeric":"004","country":"Afghanistan"},"AL":{"alpha-2":"AL","alpha-3":"ALB","numeric":"008","country":"Albania, People's Socialist Republic of"},"DZ":{"alpha-2":"DZ","alpha-3":"DZA","numeric":"012","country":"Algeria, People's Democratic Republic of"},"AS":{"alpha-2":"AS","alpha-3":"ASM","numeric":"016","country":"American Samoa"},"AD":{"alpha-2":"AD","alpha-3":"AND","numeric":"020","country":"Andorra, Principality of"},"AO":{"alpha-2":"AO","alpha-3":"AGO","numeric":"024","country":"Angola, Republic of"},"AI":{"alpha-2":"AI","alpha-3":"AIA","numeric":"660","country":"Anguilla"},"AQ":{"alpha-2":"AQ","alpha-3":"ATA","numeric":"010","country":"Antarctica (the territory South of 60 deg S)"},"AG":{"alpha-2":"AG","alpha-3":"ATG","numeric":"028","country":"Antigua and Barbuda"},"AR":{"alpha-2":"AR","alpha-3":"ARG","numeric":"032","country":"Argentina, Argentine Republic"},"AM":{"alpha-2":"AM","alpha-3":"ARM","numeric":"051","country":"Armenia"},"AW":{"alpha-2":"AW","alpha-3":"ABW","numeric":"533","country":"Aruba"},"AU":{"alpha-2":"AU","alpha-3":"AUS","numeric":"036","country":"Australia, Commonwealth of"},"AT":{"alpha-2":"AT","alpha-3":"AUT","numeric":"040","country":"Austria, Republic of"},"AZ":{"alpha-2":"AZ","alpha-3":"AZE","numeric":"031","country":"Azerbaijan, Republic of"},"BS":{"alpha-2":"BS","alpha-3":"BHS","numeric":"044","country":"Bahamas, Commonwealth of the"},"BH":{"alpha-2":"BH","alpha-3":"BHR","numeric":"048","country":"Bahrain, Kingdom of"},"BD":{"alpha-2":"BD","alpha-3":"BGD","numeric":"050","country":"Bangladesh, People's Republic of"},"BB":{"alpha-2":"BB","alpha-3":"BRB","numeric":"052","country":"Barbados"},"BY":{"alpha-2":"BY","alpha-3":"BLR","numeric":"112","country":"Belarus"},"BE":{"alpha-2":"BE","alpha-3":"BEL","numeric":"056","country":"Belgium, Kingdom of"},"BZ":{"alpha-2":"BZ","alpha-3":"BLZ","numeric":"084","country":"Belize"},"BJ":{"alpha-2":"BJ","alpha-3":"BEN","numeric":"204","country":"Benin, People's Republic of"},"BM":{"alpha-2":"BM","alpha-3":"BMU","numeric":"060","country":"Bermuda"},"BT":{"alpha-2":"BT","alpha-3":"BTN","numeric":"064","country":"Bhutan, Kingdom of"},"BO":{"alpha-2":"BO","alpha-3":"BOL","numeric":"068","country":"Bolivia, Republic of"},"BA":{"alpha-2":"BA","alpha-3":"BIH","numeric":"070","country":"Bosnia and Herzegovina"},"BW":{"alpha-2":"BW","alpha-3":"BWA","numeric":"072","country":"Botswana, Republic of"},"BV":{"alpha-2":"BV","alpha-3":"BVT","numeric":"074","country":"Bouvet Island (Bouvetoya)"},"BR":{"alpha-2":"BR","alpha-3":"BRA","numeric":"076","country":"Brazil, Federative Republic of"},"IO":{"alpha-2":"IO","alpha-3":"IOT","numeric":"086","country":"British Indian Ocean Territory (Chagos Archipelago)"},"VG":{"alpha-2":"VG","alpha-3":"VGB","numeric":"092","country":"British Virgin Islands"},"BN":{"alpha-2":"BN","alpha-3":"BRN","numeric":"096","country":"Brunei Darussalam"},"BG":{"alpha-2":"BG","alpha-3":"BGR","numeric":"100","country":"Bulgaria, People's Republic of"},"BF":{"alpha-2":"BF","alpha-3":"BFA","numeric":"854","country":"Burkina Faso"},"BI":{"alpha-2":"BI","alpha-3":"BDI","numeric":"108","country":"Burundi, Republic of"},"KH":{"alpha-2":"KH","alpha-3":"KHM","numeric":"116","country":"Cambodia, Kingdom of"},"CM":{"alpha-2":"CM","alpha-3":"CMR","numeric":"120","country":"Cameroon, United Republic of"},"CA":{"alpha-2":"CA","alpha-3":"CAN","numeric":"124","country":"Canada"},"CV":{"alpha-2":"CV","alpha-3":"CPV","numeric":"132","country":"Cape Verde, Republic of"},"KY":{"alpha-2":"KY","alpha-3":"CYM","numeric":"136","country":"Cayman Islands"},"CF":{"alpha-2":"CF","alpha-3":"CAF","numeric":"140","country":"Central African Republic"},"TD":{"alpha-2":"TD","alpha-3":"TCD","numeric":"148","country":"Chad, Republic of"},"CL":{"alpha-2":"CL","alpha-3":"CHL","numeric":"152","country":"Chile, Republic of"},"CN":{"alpha-2":"CN","alpha-3":"CHN","numeric":"156","country":"China, People's Republic of"},"CX":{"alpha-2":"CX","alpha-3":"CXR","numeric":"162","country":"Christmas Island"},"CC":{"alpha-2":"CC","alpha-3":"CCK","numeric":"166","country":"Cocos (Keeling) Islands"},"CO":{"alpha-2":"CO","alpha-3":"COL","numeric":"170","country":"Colombia, Republic of"},"KM":{"alpha-2":"KM","alpha-3":"COM","numeric":"174","country":"Comoros, Union of the"},"CD":{"alpha-2":"CD","alpha-3":"COD","numeric":"180","country":"Congo, Democratic Republic of"},"CG":{"alpha-2":"CG","alpha-3":"COG","numeric":"178","country":"Congo, People's Republic of"},"CK":{"alpha-2":"CK","alpha-3":"COK","numeric":"184","country":"Cook Islands"},"CR":{"alpha-2":"CR","alpha-3":"CRI","numeric":"188","country":"Costa Rica, Republic of"},"CI":{"alpha-2":"CI","alpha-3":"CIV","numeric":"384","country":"Cote D'Ivoire, Ivory Coast, Republic of the"},"CU":{"alpha-2":"CU","alpha-3":"CUB","numeric":"192","country":"Cuba, Republic of"},"CY":{"alpha-2":"CY","alpha-3":"CYP","numeric":"196","country":"Cyprus, Republic of"},"CZ":{"alpha-2":"CZ","alpha-3":"CZE","numeric":"203","country":"Czech Republic"},"DK":{"alpha-2":"DK","alpha-3":"DNK","numeric":"208","country":"Denmark, Kingdom of"},"DJ":{"alpha-2":"DJ","alpha-3":"DJI","numeric":"262","country":"Djibouti, Republic of"},"DM":{"alpha-2":"DM","alpha-3":"DMA","numeric":"212","country":"Dominica, Commonwealth of"},"DO":{"alpha-2":"DO","alpha-3":"DOM","numeric":"214","country":"Dominican Republic"},"EC":{"alpha-2":"EC","alpha-3":"ECU","numeric":"218","country":"Ecuador, Republic of"},"EG":{"alpha-2":"EG","alpha-3":"EGY","numeric":"818","country":"Egypt, Arab Republic of"},"SV":{"alpha-2":"SV","alpha-3":"SLV","numeric":"222","country":"El Salvador, Republic of"},"GQ":{"alpha-2":"GQ","alpha-3":"GNQ","numeric":"226","country":"Equatorial Guinea, Republic of"},"ER":{"alpha-2":"ER","alpha-3":"ERI","numeric":"232","country":"Eritrea"},"EE":{"alpha-2":"EE","alpha-3":"EST","numeric":"233","country":"Estonia"},"ET":{"alpha-2":"ET","alpha-3":"ETH","numeric":"231","country":"Ethiopia"},"FO":{"alpha-2":"FO","alpha-3":"FRO","numeric":"234","country":"Faeroe Islands"},"FK":{"alpha-2":"FK","alpha-3":"FLK","numeric":"238","country":"Falkland Islands (Malvinas)"},"FJ":{"alpha-2":"FJ","alpha-3":"FJI","numeric":"242","country":"Fiji, Republic of the Fiji Islands"},"FI":{"alpha-2":"FI","alpha-3":"FIN","numeric":"246","country":"Finland, Republic of"},"FR":{"alpha-2":"FR","alpha-3":"FRA","numeric":"250","country":"France, French Republic"},"GF":{"alpha-2":"GF","alpha-3":"GUF","numeric":"254","country":"French Guiana"},"PF":{"alpha-2":"PF","alpha-3":"PYF","numeric":"258","country":"French Polynesia"},"TF":{"alpha-2":"TF","alpha-3":"ATF","numeric":"260","country":"French Southern Territories"},"GA":{"alpha-2":"GA","alpha-3":"GAB","numeric":"266","country":"Gabon, Gabonese Republic"},"GM":{"alpha-2":"GM","alpha-3":"GMB","numeric":"270","country":"Gambia, Republic of the"},"GE":{"alpha-2":"GE","alpha-3":"GEO","numeric":"268","country":"Georgia"},"DE":{"alpha-2":"DE","alpha-3":"DEU","numeric":"276","country":"Germany"},"GH":{"alpha-2":"GH","alpha-3":"GHA","numeric":"288","country":"Ghana, Republic of"},"GI":{"alpha-2":"GI","alpha-3":"GIB","numeric":"292","country":"Gibraltar"},"GR":{"alpha-2":"GR","alpha-3":"GRC","numeric":"300","country":"Greece, Hellenic Republic"},"GL":{"alpha-2":"GL","alpha-3":"GRL","numeric":"304","country":"Greenland"},"GD":{"alpha-2":"GD","alpha-3":"GRD","numeric":"308","country":"Grenada"},"GP":{"alpha-2":"GP","alpha-3":"GLP","numeric":"312","country":"Guadaloupe"},"GU":{"alpha-2":"GU","alpha-3":"GUM","numeric":"316","country":"Guam"},"GT":{"alpha-2":"GT","alpha-3":"GTM","numeric":"320","country":"Guatemala, Republic of"},"GN":{"alpha-2":"GN","alpha-3":"GIN","numeric":"324","country":"Guinea, Revolutionary People's Rep'c of"},"GW":{"alpha-2":"GW","alpha-3":"GNB","numeric":"624","country":"Guinea-Bissau, Republic of"},"GY":{"alpha-2":"GY","alpha-3":"GUY","numeric":"328","country":"Guyana, Republic of"},"HT":{"alpha-2":"HT","alpha-3":"HTI","numeric":"332","country":"Haiti, Republic of"},"HM":{"alpha-2":"HM","alpha-3":"HMD","numeric":"334","country":"Heard and McDonald Islands"},"VA":{"alpha-2":"VA","alpha-3":"VAT","numeric":"336","country":"Holy See (Vatican City State)"},"HN":{"alpha-2":"HN","alpha-3":"HND","numeric":"340","country":"Honduras, Republic of"},"HK":{"alpha-2":"HK","alpha-3":"HKG","numeric":"344","country":"Hong Kong, Special Administrative Region of China"},"HR":{"alpha-2":"HR","alpha-3":"HRV","numeric":"191","country":"Hrvatska (Croatia)"},"HU":{"alpha-2":"HU","alpha-3":"HUN","numeric":"348","country":"Hungary, Hungarian People's Republic"},"IS":{"alpha-2":"IS","alpha-3":"ISL","numeric":"352","country":"Iceland, Republic of"},"IN":{"alpha-2":"IN","alpha-3":"IND","numeric":"356","country":"India, Republic of"},"ID":{"alpha-2":"ID","alpha-3":"IDN","numeric":"360","country":"Indonesia, Republic of"},"IR":{"alpha-2":"IR","alpha-3":"IRN","numeric":"364","country":"Iran, Islamic Republic of"},"IQ":{"alpha-2":"IQ","alpha-3":"IRQ","numeric":"368","country":"Iraq, Republic of"},"IE":{"alpha-2":"IE","alpha-3":"IRL","numeric":"372","country":"Ireland"},"IL":{"alpha-2":"IL","alpha-3":"ISR","numeric":"376","country":"Israel, State of"},"IT":{"alpha-2":"IT","alpha-3":"ITA","numeric":"380","country":"Italy, Italian Republic"},"JM":{"alpha-2":"JM","alpha-3":"JAM","numeric":"388","country":"Jamaica"},"JP":{"alpha-2":"JP","alpha-3":"JPN","numeric":"392","country":"Japan"},"JO":{"alpha-2":"JO","alpha-3":"JOR","numeric":"400","country":"Jordan, Hashemite Kingdom of"},"KZ":{"alpha-2":"KZ","alpha-3":"KAZ","numeric":"398","country":"Kazakhstan, Republic of"},"KE":{"alpha-2":"KE","alpha-3":"KEN","numeric":"404","country":"Kenya, Republic of"},"KI":{"alpha-2":"KI","alpha-3":"KIR","numeric":"296","country":"Kiribati, Republic of"},"KP":{"alpha-2":"KP","alpha-3":"PRK","numeric":"408","country":"Korea, Democratic People's Republic of"},"KR":{"alpha-2":"KR","alpha-3":"KOR","numeric":"410","country":"Korea, Republic of"},"KW":{"alpha-2":"KW","alpha-3":"KWT","numeric":"414","country":"Kuwait, State of"},"KG":{"alpha-2":"KG","alpha-3":"KGZ","numeric":"417","country":"Kyrgyz Republic"},"LA":{"alpha-2":"LA","alpha-3":"LAO","numeric":"418","country":"Lao People's Democratic Republic"},"LV":{"alpha-2":"LV","alpha-3":"LVA","numeric":"428","country":"Latvia"},"LB":{"alpha-2":"LB","alpha-3":"LBN","numeric":"422","country":"Lebanon, Lebanese Republic"},"LS":{"alpha-2":"LS","alpha-3":"LSO","numeric":"426","country":"Lesotho, Kingdom of"},"LR":{"alpha-2":"LR","alpha-3":"LBR","numeric":"430","country":"Liberia, Republic of"},"LY":{"alpha-2":"LY","alpha-3":"LBY","numeric":"434","country":"Libyan Arab Jamahiriya"},"LI":{"alpha-2":"LI","alpha-3":"LIE","numeric":"438","country":"Liechtenstein, Principality of"},"LT":{"alpha-2":"LT","alpha-3":"LTU","numeric":"440","country":"Lithuania"},"LU":{"alpha-2":"LU","alpha-3":"LUX","numeric":"442","country":"Luxembourg, Grand Duchy of"},"MO":{"alpha-2":"MO","alpha-3":"MAC","numeric":"446","country":"Macao, Special Administrative Region of China"},"MK":{"alpha-2":"MK","alpha-3":"MKD","numeric":"807","country":"Macedonia, the former Yugoslav Republic of"},"MG":{"alpha-2":"MG","alpha-3":"MDG","numeric":"450","country":"Madagascar, Republic of"},"MW":{"alpha-2":"MW","alpha-3":"MWI","numeric":"454","country":"Malawi, Republic of"},"MY":{"alpha-2":"MY","alpha-3":"MYS","numeric":"458","country":"Malaysia"},"MV":{"alpha-2":"MV","alpha-3":"MDV","numeric":"462","country":"Maldives, Republic of"},"ML":{"alpha-2":"ML","alpha-3":"MLI","numeric":"466","country":"Mali, Republic of"},"MT":{"alpha-2":"MT","alpha-3":"MLT","numeric":"470","country":"Malta, Republic of"},"MH":{"alpha-2":"MH","alpha-3":"MHL","numeric":"584","country":"Marshall Islands"},"MQ":{"alpha-2":"MQ","alpha-3":"MTQ","numeric":"474","country":"Martinique"},"MR":{"alpha-2":"MR","alpha-3":"MRT","numeric":"478","country":"Mauritania, Islamic Republic of"},"MU":{"alpha-2":"MU","alpha-3":"MUS","numeric":"480","country":"Mauritius"},"YT":{"alpha-2":"YT","alpha-3":"MYT","numeric":"175","country":"Mayotte"},"MX":{"alpha-2":"MX","alpha-3":"MEX","numeric":"484","country":"Mexico, United Mexican States"},"FM":{"alpha-2":"FM","alpha-3":"FSM","numeric":"583","country":"Micronesia, Federated States of"},"MD":{"alpha-2":"MD","alpha-3":"MDA","numeric":"498","country":"Moldova, Republic of"},"MC":{"alpha-2":"MC","alpha-3":"MCO","numeric":"492","country":"Monaco, Principality of"},"MN":{"alpha-2":"MN","alpha-3":"MNG","numeric":"496","country":"Mongolia, Mongolian People's Republic"},"MS":{"alpha-2":"MS","alpha-3":"MSR","numeric":"500","country":"Montserrat"},"MA":{"alpha-2":"MA","alpha-3":"MAR","numeric":"504","country":"Morocco, Kingdom of"},"MZ":{"alpha-2":"MZ","alpha-3":"MOZ","numeric":"508","country":"Mozambique, People's Republic of"},"MM":{"alpha-2":"MM","alpha-3":"MMR","numeric":"104","country":"Myanmar"},"NA":{"alpha-2":"NA","alpha-3":"NAM","numeric":"516","country":"Namibia"},"NR":{"alpha-2":"NR","alpha-3":"NRU","numeric":"520","country":"Nauru, Republic of"},"NP":{"alpha-2":"NP","alpha-3":"NPL","numeric":"524","country":"Nepal, Kingdom of"},"AN":{"alpha-2":"AN","alpha-3":"ANT","numeric":"530","country":"Netherlands Antilles"},"NL":{"alpha-2":"NL","alpha-3":"NLD","numeric":"528","country":"Netherlands, Kingdom of the"},"NC":{"alpha-2":"NC","alpha-3":"NCL","numeric":"540","country":"New Caledonia"},"NZ":{"alpha-2":"NZ","alpha-3":"NZL","numeric":"554","country":"New Zealand"},"NI":{"alpha-2":"NI","alpha-3":"NIC","numeric":"558","country":"Nicaragua, Republic of"},"NE":{"alpha-2":"NE","alpha-3":"NER","numeric":"562","country":"Niger, Republic of the"},"NG":{"alpha-2":"NG","alpha-3":"NGA","numeric":"566","country":"Nigeria, Federal Republic of"},"NU":{"alpha-2":"NU","alpha-3":"NIU","numeric":"570","country":"Niue, Republic of"},"NF":{"alpha-2":"NF","alpha-3":"NFK","numeric":"574","country":"Norfolk Island"},"MP":{"alpha-2":"MP","alpha-3":"MNP","numeric":"580","country":"Northern Mariana Islands"},"NO":{"alpha-2":"NO","alpha-3":"NOR","numeric":"578","country":"Norway, Kingdom of"},"OM":{"alpha-2":"OM","alpha-3":"OMN","numeric":"512","country":"Oman, Sultanate of"},"PK":{"alpha-2":"PK","alpha-3":"PAK","numeric":"586","country":"Pakistan, Islamic Republic of"},"PW":{"alpha-2":"PW","alpha-3":"PLW","numeric":"585","country":"Palau"},"PS":{"alpha-2":"PS","alpha-3":"PSE","numeric":"275","country":"Palestinian Territory, Occupied"},"PA":{"alpha-2":"PA","alpha-3":"PAN","numeric":"591","country":"Panama, Republic of"},"PG":{"alpha-2":"PG","alpha-3":"PNG","numeric":"598","country":"Papua New Guinea"},"PY":{"alpha-2":"PY","alpha-3":"PRY","numeric":"600","country":"Paraguay, Republic of"},"PE":{"alpha-2":"PE","alpha-3":"PER","numeric":"604","country":"Peru, Republic of"},"PH":{"alpha-2":"PH","alpha-3":"PHL","numeric":"608","country":"Philippines, Republic of the"},"PN":{"alpha-2":"PN","alpha-3":"PCN","numeric":"612","country":"Pitcairn Island"},"PL":{"alpha-2":"PL","alpha-3":"POL","numeric":"616","country":"Poland, Polish People's Republic"},"PT":{"alpha-2":"PT","alpha-3":"PRT","numeric":"620","country":"Portugal, Portuguese Republic"},"PR":{"alpha-2":"PR","alpha-3":"PRI","numeric":"630","country":"Puerto Rico"},"QA":{"alpha-2":"QA","alpha-3":"QAT","numeric":"634","country":"Qatar, State of"},"RE":{"alpha-2":"RE","alpha-3":"REU","numeric":"638","country":"Reunion"},"RO":{"alpha-2":"RO","alpha-3":"ROU","numeric":"642","country":"Romania, Socialist Republic of"},"RU":{"alpha-2":"RU","alpha-3":"RUS","numeric":"643","country":"Russian Federation"},"RW":{"alpha-2":"RW","alpha-3":"RWA","numeric":"646","country":"Rwanda, Rwandese Republic"},"SH":{"alpha-2":"SH","alpha-3":"SHN","numeric":"654","country":"St. Helena"},"KN":{"alpha-2":"KN","alpha-3":"KNA","numeric":"659","country":"St. Kitts and Nevis"},"LC":{"alpha-2":"LC","alpha-3":"LCA","numeric":"662","country":"St. Lucia"},"PM":{"alpha-2":"PM","alpha-3":"SPM","numeric":"666","country":"St. Pierre and Miquelon"},"VC":{"alpha-2":"VC","alpha-3":"VCT","numeric":"670","country":"St. Vincent and the Grenadines"},"WS":{"alpha-2":"WS","alpha-3":"WSM","numeric":"882","country":"Samoa, Independent State of"},"SM":{"alpha-2":"SM","alpha-3":"SMR","numeric":"674","country":"San Marino, Republic of"},"ST":{"alpha-2":"ST","alpha-3":"STP","numeric":"678","country":"Sao Tome and Principe, Democratic Republic of"},"SA":{"alpha-2":"SA","alpha-3":"SAU","numeric":"682","country":"Saudi Arabia, Kingdom of"},"SN":{"alpha-2":"SN","alpha-3":"SEN","numeric":"686","country":"Senegal, Republic of"},"CS":{"alpha-2":"CS","alpha-3":"SCG","numeric":"891","country":"Serbia and Montenegro"},"SC":{"alpha-2":"SC","alpha-3":"SYC","numeric":"690","country":"Seychelles, Republic of"},"SL":{"alpha-2":"SL","alpha-3":"SLE","numeric":"694","country":"Sierra Leone, Republic of"},"SG":{"alpha-2":"SG","alpha-3":"SGP","numeric":"702","country":"Singapore, Republic of"},"SK":{"alpha-2":"SK","alpha-3":"SVK","numeric":"703","country":"Slovakia (Slovak Republic)"},"SI":{"alpha-2":"SI","alpha-3":"SVN","numeric":"705","country":"Slovenia"},"SB":{"alpha-2":"SB","alpha-3":"SLB","numeric":"090","country":"Solomon Islands"},"SO":{"alpha-2":"SO","alpha-3":"SOM","numeric":"706","country":"Somalia, Somali Republic"},"ZA":{"alpha-2":"ZA","alpha-3":"ZAF","numeric":"710","country":"South Africa, Republic of"},"GS":{"alpha-2":"GS","alpha-3":"SGS","numeric":"239","country":"South Georgia and the South Sandwich Islands"},"ES":{"alpha-2":"ES","alpha-3":"ESP","numeric":"724","country":"Spain, Spanish State"},"LK":{"alpha-2":"LK","alpha-3":"LKA","numeric":"144","country":"Sri Lanka, Democratic Socialist Republic of"},"SD":{"alpha-2":"SD","alpha-3":"SDN","numeric":"736","country":"Sudan, Democratic Republic of the"},"SR":{"alpha-2":"SR","alpha-3":"SUR","numeric":"740","country":"Suriname, Republic of"},"SJ":{"alpha-2":"SJ","alpha-3":"SJM","numeric":"744","country":"Svalbard & Jan Mayen Islands"},"SZ":{"alpha-2":"SZ","alpha-3":"SWZ","numeric":"748","country":"Swaziland, Kingdom of"},"SE":{"alpha-2":"SE","alpha-3":"SWE","numeric":"752","country":"Sweden, Kingdom of"},"CH":{"alpha-2":"CH","alpha-3":"CHE","numeric":"756","country":"Switzerland, Swiss Confederation"},"SY":{"alpha-2":"SY","alpha-3":"SYR","numeric":"760","country":"Syrian Arab Republic"},"TW":{"alpha-2":"TW","alpha-3":"TWN","numeric":"158","country":"Taiwan, Province of China"},"TJ":{"alpha-2":"TJ","alpha-3":"TJK","numeric":"762","country":"Tajikistan"},"TZ":{"alpha-2":"TZ","alpha-3":"TZA","numeric":"834","country":"Tanzania, United Republic of"},"TH":{"alpha-2":"TH","alpha-3":"THA","numeric":"764","country":"Thailand, Kingdom of"},"TL":{"alpha-2":"TL","alpha-3":"TLS","numeric":"626","country":"Timor-Leste, Democratic Republic of"},"TG":{"alpha-2":"TG","alpha-3":"TGO","numeric":"768","country":"Togo, Togolese Republic"},"TK":{"alpha-2":"TK","alpha-3":"TKL","numeric":"772","country":"Tokelau (Tokelau Islands)"},"TO":{"alpha-2":"TO","alpha-3":"TON","numeric":"776","country":"Tonga, Kingdom of"},"TT":{"alpha-2":"TT","alpha-3":"TTO","numeric":"780","country":"Trinidad and Tobago, Republic of"},"TN":{"alpha-2":"TN","alpha-3":"TUN","numeric":"788","country":"Tunisia, Republic of"},"TR":{"alpha-2":"TR","alpha-3":"TUR","numeric":"792","country":"Turkey, Republic of"},"TM":{"alpha-2":"TM","alpha-3":"TKM","numeric":"795","country":"Turkmenistan"},"TC":{"alpha-2":"TC","alpha-3":"TCA","numeric":"796","country":"Turks and Caicos Islands"},"TV":{"alpha-2":"TV","alpha-3":"TUV","numeric":"798","country":"Tuvalu"},"VI":{"alpha-2":"VI","alpha-3":"VIR","numeric":"850","country":"US Virgin Islands"},"UG":{"alpha-2":"UG","alpha-3":"UGA","numeric":"800","country":"Uganda, Republic of"},"UA":{"alpha-2":"UA","alpha-3":"UKR","numeric":"804","country":"Ukraine"},"AE":{"alpha-2":"AE","alpha-3":"ARE","numeric":"784","country":"United Arab Emirates"},"GB":{"alpha-2":"GB","alpha-3":"GBR","numeric":"826","country":"United Kingdom of Great Britain & N. Ireland"},"UM":{"alpha-2":"UM","alpha-3":"UMI","numeric":"581","country":"United States Minor Outlying Islands"},"US":{"alpha-2":"US","alpha-3":"USA","numeric":"840","country":"United States of America"},"UY":{"alpha-2":"UY","alpha-3":"URY","numeric":"858","country":"Uruguay, Eastern Republic of"},"UZ":{"alpha-2":"UZ","alpha-3":"UZB","numeric":"860","country":"Uzbekistan"},"VU":{"alpha-2":"VU","alpha-3":"VUT","numeric":"548","country":"Vanuatu"},"VE":{"alpha-2":"VE","alpha-3":"VEN","numeric":"862","country":"Venezuela, Bolivarian Republic of"},"VN":{"alpha-2":"VN","alpha-3":"VNM","numeric":"704","country":"Viet Nam, Socialist Republic of"},"WF":{"alpha-2":"WF","alpha-3":"WLF","numeric":"876","country":"Wallis and Futuna Islands"},"EH":{"alpha-2":"EH","alpha-3":"ESH","numeric":"732","country":"Western Sahara"},"YE":{"alpha-2":"YE","alpha-3":"YEM","numeric":"887","country":"Yemen"},"ZM":{"alpha-2":"ZM","alpha-3":"ZMB","numeric":"894","country":"Zambia, Republic of"},"ZW":{"alpha-2":"ZW","alpha-3":"ZWE","numeric":"716","country":"Zimbabwe"}} \ No newline at end of file diff --git a/modules/gateways/dokuhosted/dokuhosted-config.php b/modules/gateways/dokuhosted/dokuhosted-config.php new file mode 100644 index 0000000..20604c0 --- /dev/null +++ b/modules/gateways/dokuhosted/dokuhosted-config.php @@ -0,0 +1,47 @@ + array( + array('00', 'All Available Payment'), + array('04', 'DOKU Wallet'), + array('01', 'Installment'), + array('15', 'Credit Card'), + array('36', 'ATM Transfer via Permata VA'), + array('41', 'ATM Transfer via Mandiri VA'), + array('29', 'ATM Transfer via BCA VA'), + array('34', 'ATM Transfer via BRI VA'), + array('32', 'ATM Transfer via CIMB VA'), + array('33', 'ATM Transfer via Danamon VA'), + array('35', 'Convenience Store via Alfa Group'), + array('31', 'Convenience Store via Indomaret'), + array('02', 'Mandiri Clickpay'), + array('06', 'e-Pay BRI'), + array('19', 'CIMB Clicks'), + array('25', 'Muamalat Internet Banking'), + array('26', 'Danamon Online Banking'), + array('28', 'PermataNet'), + array('37', 'Kredivo'), + array('16', 'Tokenization'), + ), + 'paymentacquirers' => array( + 'onus' => array( + array('100', 'Bank BNI'), + array('400', 'Bank BCA'), + array('300', 'Bank Mandiri'), + ), + 'offus' => array( + array('100','Bukopin'), + array('100','Permata'), + array('100','UOB'), + array('100','BRI'), + array('100','OCBC'), + array('100','HSBC'), + array('100','Danamon'), + array('100','Standard Chartered'), + ), + ), + 'paymenttenors' => array( + array('03', '03 Bulan'), + array('06', '06 Bulan'), + array('12', '12 Bulan'), + ), +); \ No newline at end of file diff --git a/modules/gateways/dokuhosted/dokuhosted-whmcs.php b/modules/gateways/dokuhosted/dokuhosted-whmcs.php new file mode 100644 index 0000000..b05fdb6 --- /dev/null +++ b/modules/gateways/dokuhosted/dokuhosted-whmcs.php @@ -0,0 +1,858 @@ + array( + 'request' => 'https://staging.doku.com/Suite/Receive', + 'checkstatus' => 'https://staging.doku.com/Suite/CheckStatus', + 'void' => 'https://staging.doku.com/Suite/VoidRequest', + ), + 'live' => array( + 'request' => 'https://pay.doku.com/Suite/Receive', + 'checkstatus' => 'https://pay.doku.com/Suite/CheckStatus', + 'void' => 'https://pay.doku.com/Suite/VoidRequest', + ), + ); + $this->isofile = (isset($configs['isofile']) ? $configs['isofile'] : ''); + if (file_exists($this->isofile)) { + $this->isofile = realpath($this->isofile); + } else { + $this->isofile = (dirname(__FILE__) . '/assets/iso3166.json'); + } + $this->endpoint = (isset($dokupayment_enpoint[$configs['endpoint']]) ? $dokupayment_enpoint[$configs['endpoint']] : false); + $this->mallid = (isset($configs['merchant']['mallid']) ? $configs['merchant']['mallid'] : ''); + $this->shopname = (isset($configs['merchant']['shopname']) ? $configs['merchant']['shopname'] : ''); + $this->chainmerchant = (isset($configs['merchant']['chainmerchant']) ? $configs['merchant']['chainmerchant'] : ''); + $this->sharedkey = (isset($configs['merchant']['sharedkey']) ? $configs['merchant']['sharedkey'] : ''); + # Headers + $this->set_dokupayment_headers(); + $this->add_dokupayment_headers('Content-type', 'application/x-www-form-urlencoded'); + //$this->add_dokupayment_headers('Authorization', "Basic {$this->authorization['authorize']}"); + } + public static function init($configs) { + if (!self::$instance) { + self::$instance = new dokuhosted_DokuPayment($configs); + } + return self::$instance; + } + //--------------------- + function get_paymentchannel($code = 4) { + $code = (int)$code; + $paymentchannels = array( + array('00', 'All Available Payment'), + array('01', 'Credit Card Visa/Master IDR'), + array('02', 'Mandiri ClickPay'), + array('03', 'KlikBCA'), + array('04', 'DOKU Wallet'), + array('05', 'ATM Permata VA LITE'), + array('06', 'BRI e-Pay'), + array('07', 'ATM Permata VA'), + array('08', 'Mandiri Multipayment LITE'), + array('09', 'Mandiri Multipayment'), + array('10', 'ATM Mandiri VA LITE'), + array('11', 'ATM Mandiri VA'), + array('12', 'PayPal'), + array('13', 'BNI Debit Online (VCN)'), + array('14', 'Alfamart'), + array('15', 'Credit Card Visa/Master Multi Currency'), + array('16', 'Tokenization'), + array('18', 'KlikPayBCA'), + array('19', 'CIMB Clicks'), + array('20', 'PTPOS'), + array('21', 'Sinarmas VA Full'), + array('22', 'Sinarmas VA Lite'), + array('23', 'MOTO'), + array('24', 'Klikpay BCA Debit'), + array('25', 'Bank Muamalat Indonesia'), + array('26', 'Danamon Online Banking'), + ); + if (isset($paymentchannels[$code])) { + return $paymentchannels[$code][0]; + } + return $paymentchannels[0][0]; + } + private function read_isofile($file) { + $contents = ''; + if (!$handle = fopen($file, 'r')) { + exit("Cannot read file"); + } + while (!feof($handle)) { + $contents .= fread($handle, 8192); + } + fclose($handle); + return $contents; + } + public function get_countrycode($isoFile, $isoCountry = "ID", $index = 'numeric') { + $countryData = json_decode($this->read_isofile($isoFile), true); + if (isset($countryData[$isoCountry][$index])) { + return $countryData[$isoCountry][$index]; + } + return false; + } + //--------------------------- + # Example : $this->create_payment_structure('create', 0, $params_input = array(), $user_input = array(), $item_data = array(), $shipping_data = array()); + function create_payment_structure($method, $paymentcode, $params_input, $user_input = array(), $item_data = array(), $shipping_data = null) { + $PaymentStructure = array(); + switch(strtolower($method)) { + case 'create': + default: + $items = array( + 'purchase' => 0, + 'currency' => (isset($params_input['transaction_currency']) ? $params_input['transaction_currency'] : 'ID'), + ); + $create_words = array( + 'amount' => (isset($params_input['amount_total']) ? $params_input['amount_total'] : 0), + 'mallid' => $this->mallid, + 'sharedkey' => $this->sharedkey, + 'transaction_id' => (isset($params_input['transaction_id']) ? $params_input['transaction_id'] : 0), + 'currency' => $items['currency'], + ); + if (count($item_data) > 0) { + foreach ($item_data as $val) { + $items['purchase'] += (isset($val['order_price']) ? $val['order_price'] : 0); + } + } + $PaymentStructure = array( + 'MALLID' => $this->mallid, + 'CHAINMERCHANT' => $this->chainmerchant, + 'AMOUNT' => sprintf("%.2f", floatval($create_words['amount'])), + 'PURCHASEAMOUNT' => sprintf("%.2f", floatval($items['purchase'])), + 'TRANSIDMERCHANT' => $create_words['transaction_id'], + 'PAYMENTTYPE' => 'SALE', // DEFAULT is "SALE" + 'WORDS_STRING' => $this->create_words($method, $create_words), + 'WORDS' => sha1($this->create_words($method, $create_words)), + 'REQUESTDATETIME' => (isset($params_input['transaction_datetime']) ? $params_input['transaction_datetime'] : date('YmdHis')), + 'CURRENCY' => $this->get_countrycode($this->isofile, $create_words['currency']), + 'PURCHASECURRENCY' => $this->get_countrycode($this->isofile, $create_words['currency']), + 'SESSIONID' => (isset($params_input['transaction_session']) ? $params_input['transaction_session'] : ''), + 'NAME' => $user_input['name'], + 'EMAIL' => $user_input['email'], + 'BASKET' => $this->create_basket($method, $item_data), + 'PAYMENTCHANNEL' => $this->get_paymentchannel($paymentcode), + ); + if (isset($shipping_data)) { + $PaymentStructure['ADDITIONALDATA'] = (isset($user_input['shipping_address']['ADDITIONALDATA']) ? $user_input['shipping_address']['ADDITIONALDATA']: ""); + $PaymentStructure['SHIPPING_ADDRESS'] = (isset($user_input['shipping_address']['SHIPPING_ADDRESS']) ? $user_input['shipping_address']['SHIPPING_ADDRESS'] : ""); + $PaymentStructure['SHIPPING_CITY'] = (isset($user_input['shipping_address']['SHIPPING_CITY']) ? $user_input['shipping_address']['SHIPPING_CITY'] : ""); + $PaymentStructure['SHIPPING_STATE'] = (isset($user_input['shipping_address']['SHIPPING_STATE']) ? $user_input['shipping_address']['SHIPPING_STATE'] : ""); + $PaymentStructure['SHIPPING_COUNTRY'] = (isset($user_input['shipping_address']['SHIPPING_COUNTRY']) ? $user_input['shipping_address']['SHIPPING_COUNTRY'] : ""); + $PaymentStructure['SHIPPING_ZIPCODE'] = (isset($user_input['shipping_address']['SHIPPING_ZIPCODE']) ? $user_input['shipping_address']['SHIPPING_ZIPCODE'] : ""); + # New: + $PaymentStructure['ADDRESS'] = $PaymentStructure['SHIPPING_ADDRESS']; + $PaymentStructure['CITY'] = $PaymentStructure['SHIPPING_CITY']; + $PaymentStructure['STATE'] = $PaymentStructure['SHIPPING_STATE']; + $PaymentStructure['COUNTRY'] = $PaymentStructure['SHIPPING_COUNTRY']; + $PaymentStructure['ZIPCODE'] = $PaymentStructure['SHIPPING_ZIPCODE']; + # + $PaymentStructure['HOMEPHONE'] = (isset($user_input['shipping_address']['phone']) ? $user_input['shipping_address']['phone'] : ""); + $PaymentStructure['MOBILEPHONE'] = (isset($user_input['shipping_address']['phone']) ? $user_input['shipping_address']['phone'] : ""); + $PaymentStructure['WORKPHONE'] = (isset($user_input['shipping_address']['phone']) ? $user_input['shipping_address']['phone'] : ""); + } + ## Remove specific payment channel if < 1 + if ((int)$paymentcode < 1) { + unset($PaymentStructure['PAYMENTCHANNEL']); + } + $PaymentStructure['SESSIONID'] = substr($PaymentStructure['SESSIONID'], 0, 48); + $PaymentStructure['MOBILEPHONE'] = substr($PaymentStructure['MOBILEPHONE'], 0, 12); + $PaymentStructure['WORKPHONE'] = substr($PaymentStructure['WORKPHONE'], 0, 13); + break; + case 'check': + $create_words = array( + 'mallid' => $this->mallid, + 'sharedkey' => $this->sharedkey, + 'transaction_id' => (isset($params_input['transaction_id']) ? $params_input['transaction_id'] : 0), + 'session_id' => (isset($params_input['transaction_session']) ? $params_input['transaction_session'] : ''), + 'currency' => (isset($params_input['transaction_currency']) ? $params_input['transaction_currency'] : '360'), + 'currency_purchase' => (isset($params_input['transaction_currency_purchase']) ? $params_input['transaction_currency_purchase'] : '360'), + ); + $PaymentStructure = array( + 'MALLID' => $this->mallid, + 'CHAINMERCHANT' => $this->chainmerchant, + 'TRANSIDMERCHANT' => $create_words['transaction_id'], + 'SESSIONID' => $create_words['session_id'], + 'WORDS_STRING' => $this->create_words($method, $create_words), + 'WORDS' => sha1($this->create_words($method, $create_words)), + 'PAYMENTCHANNEL' => $this->get_paymentchannel($paymentcode), + 'CURRENCY' => $create_words['currency'], + 'PURCHASECURRENCY' => $create_words['currency_purchase'], + ); + if ((int)$paymentcode < 1) { + unset($PaymentStructure['PAYMENTCHANNEL']); + } else { + // Not using payment-channel anymore + unset($PaymentStructure['PAYMENTCHANNEL']); + } + break; + case 'void': + $create_words = array( + 'mallid' => $this->mallid, + 'sharedkey' => $this->sharedkey, + 'transaction_id' => (isset($params_input['transaction_id']) ? $params_input['transaction_id'] : 0), + 'session_id' => (isset($params_input['transaction_session']) ? $params_input['transaction_session'] : ''), + 'currency' => (isset($params_input['transaction_currency']) ? $params_input['transaction_currency'] : '360'), + 'payment_channel' => (isset($params_input['transaction_channel']) ? $params_input['transaction_channel'] : ''), + ); + + ## + $PaymentStructure = array( + 'MALLID' => $this->mallid, + 'CHAINMERCHANT' => $this->chainmerchant, + 'TRANSIDMERCHANT' => $create_words['transaction_id'], + 'SESSIONID' => $create_words['session_id'], + 'WORDS_STRING' => $this->create_words($method, $create_words), + 'WORDS' => sha1($this->create_words($method, $create_words)), + 'PAYMENTCHANNEL' => $create_words['payment_channel'], + ); + break; + //------- + case 'notify': + case 'notify-checking': + $create_words = array( + 'amount' => (isset($params_input['amount']) ? sprintf("%.2f", floatval($params_input['amount'])) : '0.00'), + 'mallid' => $this->mallid, + 'sharedkey' => $this->sharedkey, + 'transaction_id' => (isset($params_input['transaction_id']) ? $params_input['transaction_id'] : 0), + 'result_msg' => (isset($params_input['result_msg']) ? $params_input['result_msg'] : ''), // SUCCESS + 'verify_status' => (isset($params_input['verify_status']) ? $params_input['verify_status'] : ''), // SUCCESS + 'currency' => (isset($params_input['transaction_currency']) ? $params_input['transaction_currency'] : '360'), + ); + ## + $PaymentStructure = array( + 'MALLID' => $this->mallid, + 'CHAINMERCHANT' => $this->chainmerchant, + 'TRANSIDMERCHANT' => $create_words['transaction_id'], + 'SESSIONID' => $create_words['session_id'], + 'WORDS_STRING' => $this->create_words($method, $create_words), + 'WORDS' => sha1($this->create_words($method, $create_words)), + 'RESULTMSG' => $create_words['result_msg'], + 'VERIFYSTATUS' => $create_words['verify_status'], + ); + break; + //------ + case 'redirect': + case 'redirect-checking': + $create_words = array( + 'mallid' => $this->mallid, + 'sharedkey' => $this->sharedkey, + 'amount' => (isset($params_input['amount']) ? sprintf("%.2f", floatval($params_input['amount'])) : '0.00'), + 'transaction_id' => (isset($params_input['transaction_id']) ? $params_input['transaction_id'] : 0), + 'transaction_words' => (isset($params_input['transaction_words']) ? $params_input['transaction_words'] : ''), + 'trans_status' => (isset($params_input['transaction_status']) ? (string)$params_input['transaction_status'] : ''), // 0000 + 'payment_channel' => (isset($params_input['transaction_channel']) ? $params_input['transaction_channel'] : ''), + 'session_id' => (isset($params_input['transaction_session']) ? $params_input['transaction_session'] : ''), + 'payment_code' => (isset($params_input['transaction_code']) ? $params_input['transaction_code'] : ''), + 'currency' => (isset($params_input['transaction_currency']) ? $params_input['transaction_currency'] : '360'), + 'currency_purchase' => (isset($params_input['transaction_currency_purchase']) ? $params_input['transaction_currency_purchase'] : '360'), + ); + ## + $PaymentStructure = array( + 'AMOUNT' => $create_words['amount'], + 'TRANSIDMERCHANT' => $create_words['transaction_id'], + 'WORDS_STRING' => $this->create_words($method, $create_words), + 'WORDS' => sha1($this->create_words($method, $create_words)), + 'WORDS_DOKU' => $create_words['transaction_words'], + 'STATUSCODE' => $create_words['trans_status'], + 'PAYMENTCHANNEL' => $create_words['payment_channel'], + 'SESSIONID' => $create_words['session_id'], + 'PAYMENTCODE' => $create_words['payment_code'], + 'CURRENCY' => $create_words['currency'], + 'PURCHASECURRENCY' => $create_words['currency_purchase'], + ); + break; + ####################################################### + # RECURRING + ####################################################### + case 'recurring-create': + $items = array( + 'purchase' => 0, + 'currency' => (isset($params_input['transaction_currency']) ? $params_input['transaction_currency'] : 'ID'), + ); + $create_words = array( + 'amount' => (isset($params_input['amount_total']) ? $params_input['amount_total'] : 0), + 'mallid' => $this->mallid, + 'sharedkey' => $this->sharedkey, + 'transaction_id' => (isset($params_input['transaction_id']) ? $params_input['transaction_id'] : 0), + 'currency' => $items['currency'], + ); + if (count($item_data) > 0) { + foreach ($item_data as $val) { + $items['purchase'] += (isset($val['order_price']) ? $val['order_price'] : 0); + } + } + $PaymentStructure = array( + 'MALLID' => $this->mallid, + 'CHAINMERCHANT' => $this->chainmerchant, + 'AMOUNT' => sprintf("%.2f", floatval($create_words['amount'])), + 'PURCHASEAMOUNT' => sprintf("%.2f", floatval($items['purchase'])), + 'TRANSIDMERCHANT' => $create_words['transaction_id'], + //'PAYMENTTYPE' => 'SALE', // DEFAULT is "SALE" + 'WORDS_STRING' => $this->create_words($method, $create_words), + 'WORDS' => sha1($this->create_words($method, $create_words)), + 'REQUESTDATETIME' => (isset($params_input['transaction_datetime']) ? $params_input['transaction_datetime'] : date('YmdHis')), + 'CURRENCY' => $this->get_countrycode($this->isofile, $create_words['currency']), + 'PURCHASECURRENCY' => $this->get_countrycode($this->isofile, $create_words['currency']), + 'SESSIONID' => (isset($params_input['transaction_session']) ? $params_input['transaction_session'] : ''), + 'NAME' => $user_input['name'], + 'EMAIL' => $user_input['email'], + 'ADDITIONALDATA' => '', + 'BASKET' => $this->create_basket($method, $item_data), + 'CUSTOMERID' => '', + 'PAYMENTCHANNEL' => '', + ); + if (isset($shipping_data)) { + $PaymentStructure['ADDITIONALDATA'] = (isset($user_input['shipping_address']['ADDITIONALDATA']) ? $user_input['shipping_address']['ADDITIONALDATA']: ""); + $PaymentStructure['SHIPPING_ADDRESS'] = (isset($user_input['shipping_address']['SHIPPING_ADDRESS']) ? $user_input['shipping_address']['SHIPPING_ADDRESS'] : ""); + $PaymentStructure['SHIPPING_CITY'] = (isset($user_input['shipping_address']['SHIPPING_CITY']) ? $user_input['shipping_address']['SHIPPING_CITY'] : ""); + $PaymentStructure['SHIPPING_STATE'] = (isset($user_input['shipping_address']['SHIPPING_STATE']) ? $user_input['shipping_address']['SHIPPING_STATE'] : ""); + $PaymentStructure['SHIPPING_COUNTRY'] = (isset($user_input['shipping_address']['SHIPPING_COUNTRY']) ? $user_input['shipping_address']['SHIPPING_COUNTRY'] : ""); + $PaymentStructure['SHIPPING_ZIPCODE'] = (isset($user_input['shipping_address']['SHIPPING_ZIPCODE']) ? $user_input['shipping_address']['SHIPPING_ZIPCODE'] : ""); + # New: + $PaymentStructure['ADDRESS'] = $PaymentStructure['SHIPPING_ADDRESS']; + $PaymentStructure['CITY'] = $PaymentStructure['SHIPPING_CITY']; + $PaymentStructure['STATE'] = $PaymentStructure['SHIPPING_STATE']; + $PaymentStructure['COUNTRY'] = $PaymentStructure['SHIPPING_COUNTRY']; + $PaymentStructure['ZIPCODE'] = $PaymentStructure['SHIPPING_ZIPCODE']; + $PaymentStructure['HOMEPHONE'] = (isset($user_input['shipping_address']['phone']) ? $user_input['shipping_address']['phone'] : ""); + $PaymentStructure['MOBILEPHONE'] = (isset($user_input['shipping_address']['phone']) ? $user_input['shipping_address']['phone'] : ""); + $PaymentStructure['WORKPHONE'] = (isset($user_input['shipping_address']['phone']) ? $user_input['shipping_address']['phone'] : ""); + # + $PaymentStructure['BIRTHDATE'] = (isset($user_input['shipping_address']['birthdate']) ? $user_input['shipping_address']['birthdate'] : ''); + # Recurring Billing + $PaymentStructure['BILLNUMBER'] = (isset($params_input['transaction_billnumber']) ? $params_input['transaction_billnumber'] : ''); + $PaymentStructure['BILLDETAIL'] = $PaymentStructure['ADDITIONALDATA']; // Details of payment + $PaymentStructure['BILLTYPE'] = ''; // S = Shopping, I = Installment, D = Donation, P = Payment, B = Billing + $PaymentStructure['STARTDATE'] = ''; // Format: YYYYMMDD + $PaymentStructure['ENDDATE'] = ''; // Format: YYYYMMDD + $PaymentStructure['EXECUTETYPE'] = ''; # DAY / DATE / FULLDATE + $PaymentStructure['EXECUTEDATE'] = ''; # If EXECUTETYPE = DAY (SUN / MON / TUE / WED / THU / FRI / SAT), If EXECUTETYPE = DATE (1 / 2 / 3 / ... / 28), If EXECUTETYPE = FULLDATE (Use format: YYYYMMDD) + $PaymentStructure['EXECUTEMONTH'] = ''; # Please select one (JAN / FEB / MAR / APR / MAY / JUN / JUL / AUG / SEP / OCT / NOV / DEC) + $PaymentStructure['FLATSTATUS'] = ''; // Dinamyc AMOUNT = FALSE, Static (Fix) AMOUNT = TRUE + # AMOUNT + $PaymentStructure['REGISTERAMOUNT'] = ''; + + } + break; + } + return $PaymentStructure; + } + //------------------------------------------------------------ + private function create_words_string($create_words = array()) { + $string_words = array(); + if (count($create_words) > 0) { + foreach ($create_words as $keval) { + $string_words[] = (string)$keval; + } + } + $string = ""; + if (count($string_words) > 0) { + foreach($string_words as $keval) { + $string .= (string)$keval; + } + } + //$string = implode("", $string_words); + $string = trim((string)$string); + return $string; + } + private function create_words_string_alter($create_words = array()) { + $string_words = array(); + if (count($create_words) > 0) { + foreach ($create_words as $keval) { + $string_words[] = strval($keval); + } + } + $string = ""; + if (count($string_words) > 0) { + foreach($string_words as $keval) { + $string .= strval($keval); + } + } + //$string = implode("", $string_words); + $string = trim(strval($string)); + return $string; + } + private function create_words($method, $params_input) { + $return_create_words = ""; + $create_words = array(); + switch(strtolower($method)) { + case 'create': + default: + $create_words = array( + 'amount' => (isset($params_input['amount']) ? sprintf("%.2f", floatval($params_input['amount'])) : '1.00'), + 'mallid' => (isset($params_input['mallid']) ? $params_input['mallid'] : $this->config['MALLID']), + 'sharedkey' => (isset($params_input['sharedkey']) ? $params_input['sharedkey'] : $this->config['SHAREDKEY']), + 'transaction_id' => (isset($params_input['transaction_id']) ? $params_input['transaction_id'] : 0), + 'currency' => (isset($params_input['currency']) ? $this->get_countrycode($this->isofile, $params_input['currency']) : '360'), + ); + if ((int)$create_words['currency'] === 360) { // using IDR (indonesia) + unset($create_words['currency']); + } + break; + case 'check': + $create_words = array( + 'mallid' => (isset($params_input['mallid']) ? $params_input['mallid'] : $this->mallid), + 'sharedkey' => (isset($params_input['sharedkey']) ? $params_input['sharedkey'] : $this->sharedkey), + 'transaction_id' => (isset($params_input['transaction_id']) ? $params_input['transaction_id'] : 0), + 'currency' => (isset($params_input['currency']) ? $params_input['currency'] : '360'), + ); + if ((int)$create_words['currency'] === 360) { // using IDR (indonesia) + unset($create_words['currency']); + } + break; + case 'void': + $create_words = array( + 'mallid' => (isset($params_input['mallid']) ? $params_input['mallid'] : $this->mallid), + 'sharedkey' => (isset($params_input['sharedkey']) ? $params_input['sharedkey'] : $this->sharedkey), + 'transaction_id' => (isset($params_input['transaction_id']) ? $params_input['transaction_id'] : 0), + 'session_id' => (isset($params_input['session_id']) ? $params_input['session_id'] : ''), + 'currency' => (isset($params_input['currency']) ? $params_input['currency'] : '360'), + ); + unset($create_words['currency']); // There is no currency on void WORDS + break; + //----------------------- + case 'notify': + case 'notify-checking': + $create_words = array( + 'amount' => (isset($params_input['amount']) ? sprintf("%.2f", floatval($params_input['amount'])) : '0.00'), + 'mallid' => (isset($params_input['mallid']) ? $params_input['mallid'] : $this->mallid), + 'sharedkey' => (isset($params_input['sharedkey']) ? $params_input['sharedkey'] : $this->sharedkey), + 'transaction_id' => (isset($params_input['transaction_id']) ? $params_input['transaction_id'] : 0), + 'result_msg' => (isset($params_input['result_msg']) ? $params_input['result_msg'] : ''), // SUCCESS + 'verify_status' => (isset($params_input['verify_status']) ? $params_input['verify_status'] : ''), // SUCCESS + 'currency' => (isset($params_input['currency']) ? $params_input['currency'] : '360'), + ); + if ((int)$create_words['currency'] === 360) { // using IDR (indonesia) + unset($create_words['currency']); + } + break; + case 'redirect': + case 'redirect-checking': + $create_words = array( + 'amount' => (isset($params_input['amount']) ? sprintf("%.2f", floatval($params_input['amount'])) : '0.00'), + 'sharedkey' => (isset($params_input['sharedkey']) ? $params_input['sharedkey'] : $this->sharedkey), + 'transaction_id' => (isset($params_input['transaction_id']) ? $params_input['transaction_id'] : 0), + 'trans_status' => (isset($params_input['trans_status']) ? (string)$params_input['trans_status'] : ''), + 'currency' => (isset($params_input['currency']) ? $params_input['currency'] : '360'), + ); + if ((int)$create_words['currency'] === 360) { // using IDR (indonesia) + unset($create_words['currency']); + } + break; + } + return $this->create_words_string($create_words); + } + //---------------------------------------------- + public function check_status_payment($method, $params_input) { + $CheckStructure = array(); + switch (strtolower($method)) { + case 'check': + $CheckStructure = $this->create_payment_structure('check', 0, $params_input); + unset($CheckStructure['WORDS_STRING']); + ksort($CheckStructure); + break; + } + return $this->create_curl_request('POST', $this->client['checkstatus'], 'TDP/Api.Context', $this->create_curl_headers(), $CheckStructure, 30); + } + //---------------------------------------------- + private function create_basket($method, $item_data) { + $create_item_details = array(); + $string_return = array(); + foreach ($item_data as $val) { + $create_item_details[] = array( + 'item_name' => (isset($val['order_item_name']) ? $val['order_item_name'] : ""), + 'item_price' => (isset($val['order_price']) ? $val['order_price'] : 0), + 'item_unit' => (isset($val['order_unit']) ? $val['order_unit'] : 1), + 'item_price_total' => ((isset($val['order_price']) && isset($val['order_unit'])) ? ($val['order_price'] * $val['order_unit']) : 0), + ); + } + if (count($create_item_details) > 0) { + foreach ($create_item_details as &$val) { + $val['item_price'] = sprintf("%.2f", floatval($val['item_price'])); + $val['item_price_total'] = sprintf("%.2f", floatval($val['item_price_total'])); + $string_return[] = implode(",", $val); + } + } + if (count($string_return) > 0) { + return implode(";", $string_return); + } else { + return ""; + } + } + //----------------------------------------------------------------------------- + public static function doku_incoming_callback() { + ############################### + # Request Input + $RequestInputParams = array(); + $RequestInput = file_get_contents("php://input"); + $incomingHeaders = self::apache_headers(); + if (isset($incomingHeaders['Content-Type'])) { + if ((!is_array($incomingHeaders['Content-Type'])) && (!is_object($incomingHeaders['Content-Type']))) { + if (0 === strpos($incomingHeaders['Content-Type'], 'application/json')) { + if (!$RequestInputJson = json_decode($RequestInput, true)) { + parse_str($RequestInput, $RequestInputParams); + } else { + $RequestInputParams = $RequestInputJson; + } + } else if (0 === strpos($incomingHeaders['Content-Type'], 'application/xml')) { + $RequestInputParams = $RequestInput; + } else { + parse_str($RequestInput, $RequestInputParams); + } + } + } else { + parse_str($RequestInput, $RequestInputParams); + } + $params['input'] = $RequestInput; + $params['header'] = $incomingHeaders; + $params['body'] = $RequestInputParams; + return $params; + } + public static function _GET(){ + $__GET = (isset($_GET) ? $_GET : array()); + $request_uri = ((isset($_SERVER['REQUEST_URI']) && (!empty($_SERVER['REQUEST_URI']))) ? $_SERVER['REQUEST_URI'] : ''); + $_get_str = explode('?', $request_uri); + if( !isset($_get_str[1]) ) return $__GET; + $params = explode('&', $_get_str[1]); + foreach ($params as $p) { + $parts = explode('=', $p); + $parts[0] = (is_string($parts[0]) ? strtolower($parts[0]) : $parts[0]); + $__GET[$parts[0]] = isset($parts[1]) ? $parts[1] : ''; + } + return $__GET; + } + public static function get_query_string() { + $__GET = (isset($_GET) ? $_GET : array()); + $request_uri = ((isset($_SERVER['REQUEST_URI']) && (!empty($_SERVER['REQUEST_URI']))) ? $_SERVER['REQUEST_URI'] : ''); + $query_string = (isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : ''); + parse_str(parse_url(html_entity_decode($request_uri), PHP_URL_QUERY), $array); + if (count($array) > 0) { + foreach ($array as $key => $val) { + $__GET[$key] = $val; + } + } + return $__GET; + } + //----------------------------------------------------------------------------- + function set_dokupayment_headers($headers = array()) { + $this->dokupayment_headers = $headers; + return $this; + } + function reset_dokupayment_headers() { + $this->dokupayment_headers = null; + return $this; + } + function add_dokupayment_headers($key, $val) { + if (!isset($this->dokupayment_headers)) { + $this->dokupayment_headers = $this->get_dokupayment_headers(); + } + $add_header = array($key => $val); + $this->dokupayment_headers = array_merge($add_header, $this->dokupayment_headers); + } + function get_dokupayment_headers() { + return $this->dokupayment_headers; + } + //------------------------------------------------------------------------------------------------------ + function create_curl_request($action, $url, $UA, $headers = null, $params = array(), $timeout = 30) { + $cookie_file = (dirname(__FILE__).'/cookies.txt'); + $url = str_replace( "&", "&", urldecode(trim($url)) ); + $ch = curl_init(); + switch (strtolower($action)) { + case 'get': + if ((is_array($params)) && (count($params) > 0)) { + $Querystring = http_build_query($params); + $url .= "?"; + $url .= $Querystring; + } + break; + case 'post': + default: + $url .= ""; + break; + } + curl_setopt($ch, CURLOPT_URL, $url); + curl_setopt($ch, CURLOPT_VERBOSE, true); + if ($headers != null) { + curl_setopt($ch, CURLOPT_HEADER, true); + curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); + } else { + curl_setopt($ch, CURLOPT_HEADER, false); + } + curl_setopt($ch, CURLOPT_USERAGENT, $UA); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + //curl_setopt($ch, CURLOPT_COOKIE, $cookie_file); + //curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file); + curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); + curl_setopt($ch, CURLOPT_ENCODING, ""); + curl_setopt($ch, CURLOPT_AUTOREFERER, true); + curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); + curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); + curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); + curl_setopt($ch, CURLOPT_MAXREDIRS, 10); + $post_fields = NULL; + switch (strtolower($action)) { + case 'get': + curl_setopt($ch, CURLOPT_POST, false); + curl_setopt($ch, CURLOPT_POSTFIELDS, null); + curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET'); + break; + case 'post': + default: + if ((is_array($params)) && (count($params) > 0) && (is_array($headers) && count($headers) > 0)) { + foreach ($headers as $heval) { + $getContentType = explode(":", $heval); + if (strtolower($getContentType[0]) !== 'content-type') { + continue; + } + switch (strtolower(trim($getContentType[0]))) { + case 'content-type': + if (isset($getContentType[1])) { + switch (strtolower(trim($getContentType[1]))) { + case 'application/xml': + $post_fields = $post_fields; + break; + case 'application/json': + $post_fields = json_encode($params, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); + break; + case 'application/x-www-form-urlencoded': + $post_fields = http_build_query($params); + break; + default: + $post_fields = http_build_query($params); + break; + } + } + break; + default: + $post_fields = http_build_query($params); + break; + } + } + } else if ((!empty($params)) || ($params != '')) { + $post_fields = $params; + } + curl_setopt($ch, CURLOPT_POST, true); + curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields); + break; + } + // Get Response + $response = curl_exec($ch); + $mixed_info = curl_getinfo($ch); + $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE); + $header_string = substr($response, 0, $header_size); + $header_content = $this->get_headers_from_curl_response($header_string); + $header_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); + if (count($header_content) > 1) { + $header_content = end($header_content); + } + $body = substr($response, $header_size); + curl_close ($ch); + $return = array( + 'request' => array( + 'method' => $action, + 'host' => $url, + 'header' => $headers, + 'body' => $post_fields, + ), + 'response' => array(), + ); + if (!empty($response) || $response != '') { + $return['response']['code'] = (int)$header_code; + $return['response']['header'] = array( + 'size' => $header_size, + 'string' => $header_string, + 'content' => $header_content, + ); + $return['response']['body'] = $body; + return $return; + } + return false; + } + private static function get_headers_from_curl_response($headerContent) { + $headers = array(); + // Split the string on every "double" new line. + $arrRequests = explode("\r\n\r\n", $headerContent); + // Loop of response headers. The "count($arrRequests) - 1" is to + // avoid an empty row for the extra line break before the body of the response. + for ($index = 0; $index < (count($arrRequests) - 1); $index++) { + foreach (explode("\r\n", $arrRequests[$index]) as $i => $line) { + if ($i === 0) { + $headers[$index]['http_code'] = $line; + } else { + list ($key, $value) = explode(': ', $line); + $headers[$index][$key] = $value; + } + } + } + return $headers; + } + public function create_curl_headers($headers = array()) { + $curlheaders = array(); + foreach ($headers as $ke => $val) { + $curlheaders[] = "{$ke}: {$val}"; + } + return $curlheaders; + } + public static function apache_headers() { + if (function_exists('apache_request_headers')) { + $headers = apache_request_headers(); + $out = array(); + foreach ($headers AS $key => $value) { + $key = str_replace(" ", "-", ucwords(strtolower(str_replace("-", " ", $key)))); + $out[$key] = $value; + } + } else { + $out = array(); + if (isset($_SERVER['CONTENT_TYPE'])) { + $out['Content-Type'] = $_SERVER['CONTENT_TYPE']; + } + if (isset($_ENV['CONTENT_TYPE'])) { + $out['Content-Type'] = $_ENV['CONTENT_TYPE']; + foreach ($_SERVER as $key => $value) { + if (substr($key, 0, 5) == "HTTP_") { + $key = str_replace(" ", "-", ucwords(strtolower(str_replace("_", " ", substr($key, 5))))); + $out[$key] = $value; + } + } + } + } + return $out; + } + // --------------------------------- + // Utilities + // --------------------------------- + function create_custom_arraytoxml($root, $params = array()) { + # Create XML (return object) + $obj_xml = new SimpleXMLElement($root); + $this->custom_arraytoxml($params, $obj_xml); + return $obj_xml; + } + function render_custom_arraytoxml($obj_xml) { + $xml_formatted = $obj_xml->asXML(); + //$xml_formatted = str_replace('', '', $xml_formatted); + //$xml_formatted = str_replace('', '', $xml_formatted); + $domXML = new DOMDocument('1.0'); + $domXML->preserveWhiteSpace = false; + $domXML->formatOutput = true; + $domXML->loadXML($xml_formatted); + $xml_formatted = $domXML->saveXML(); + return $xml_formatted; + } + // Create Unique Billno by Datetime + function generate_transaction_id($timezone = "Asia/Bangkok") { + $microtime = microtime(true); + $micro = sprintf("%06d",($microtime - floor($microtime)) * 1000000); + $DateObject = new DateTime(date("Y-m-d H:i:s.{$micro}", $microtime)); + $DateObject->setTimezone(new DateTimeZone($timezone)); + return $DateObject->format('YmdHisu'); + } + //---------------------------------------------- + function custom_arraytoxml($array, &$xml){ + foreach ($array as $key => $value) { + if(is_array($value)){ + if(is_int($key)) { + $key = "e"; + } + $label = $xml->addChild($key); + $this->custom_arraytoxml($value, $label); + } else { + $xml->addChild($key, $value); + } + } + } + function xmltoarray($contents, $get_attributes=1) { + if(!$contents) return array(); + if(!function_exists('xml_parser_create')) { + return array(); + } + $parser = xml_parser_create(); + xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, 0 ); + xml_parser_set_option( $parser, XML_OPTION_SKIP_WHITE, 1 ); + xml_parse_into_struct( $parser, $contents, $xml_values ); + xml_parser_free( $parser ); + if(!$xml_values) return; + $xml_array = array(); + $parents = array(); + $opened_tags = array(); + $arr = array(); + $current = &$xml_array; + foreach($xml_values as $data) { + unset($attributes,$value); + extract($data); + $result = ''; + if($get_attributes) { + $result = array(); + if(isset($value)) $result['value'] = $value; + if(isset($attributes)) { + foreach($attributes as $attr => $val) { + if($get_attributes == 1) $result['attr'][$attr] = $val; + } + } + } elseif(isset($value)) { + $result = $value; + } + if($type == "open") { + $parent[$level-1] = &$current; + if(!is_array($current) or (!in_array($tag, array_keys($current)))) { + $current[$tag] = $result; + $current = &$current[$tag]; + } else { + if(isset($current[$tag][0])) { + array_push($current[$tag], $result); + } else { + $current[$tag] = array($current[$tag],$result); + } + $last = count($current[$tag]) - 1; + $current = &$current[$tag][$last]; + } + } elseif($type == "complete") { + if(!isset($current[$tag])) { + $current[$tag] = $result; + } else { + if((is_array($current[$tag]) and $get_attributes == 0) + or (isset($current[$tag][0]) and is_array($current[$tag][0]) and $get_attributes == 1)) { + array_push($current[$tag],$result); + } else { + $current[$tag] = array($current[$tag],$result); + } + } + } elseif($type == 'close') { + $current = &$parent[$level-1]; + } + } + return($xml_array); + } + // Utils + //------------------------------------ + # Create by Wordpress + function sanitize_file_name( $filename ) { + $filename_raw = $filename; + $special_chars = array("?", "[", "]", "/", "\\", "=", "<", ">", ":", ";", ",", "'", "\"", "&", "$", "#", "*", "(", ")", "|", "~", "`", "!", "{", "}"); + foreach ($special_chars as $chr) { + $filename = str_replace($chr, '', $filename); + } + $filename = preg_replace('/[\s-]+/', '-', $filename); + $filename = trim($filename, '.-_'); + $filename; + } + function sanitize_url_parameter($params_input = array()) { + $sanitized = []; + if (count($params_input) > 0) { + foreach ($params_input as $key => $keval) { + if (!is_array($keval) || (!is_object($keval))) { + //$keval = filter_var($keval, FILTER_SANITIZE_STRING); + $keval = filter_var($keval, FILTER_SANITIZE_URL); + } + $sanitized[$key] = $keval; + } + } + return $sanitized; + } + +} \ No newline at end of file diff --git a/modules/gateways/dokuhosted/dokusubscription-config.php b/modules/gateways/dokuhosted/dokusubscription-config.php new file mode 100644 index 0000000..3fcbbd6 --- /dev/null +++ b/modules/gateways/dokuhosted/dokusubscription-config.php @@ -0,0 +1,11 @@ + array( + array('00', 'Subscription Payment'), + ), + 'paymenttenors' => array( + array('03', '03 Bulan'), + array('06', '06 Bulan'), + array('12', '12 Bulan'), + ), +); \ No newline at end of file diff --git a/modules/gateways/dokuhosted/dokusubscription-whmcs.php b/modules/gateways/dokuhosted/dokusubscription-whmcs.php new file mode 100644 index 0000000..466a02b --- /dev/null +++ b/modules/gateways/dokuhosted/dokusubscription-whmcs.php @@ -0,0 +1,1167 @@ + array( + 'request' => 'https://staging.doku.com/Suite/Receive', + 'checkstatus' => 'https://staging.doku.com/Suite/CheckStatus', + 'void' => 'https://staging.doku.com/Suite/VoidRequest', + 'registerupdate' => 'https://staging.doku.com/Suite/RecurUpdateCard', + 'registerdelete' => 'https://staging.doku.com/AccountBilling/DoDeleteSubscriptionSuite', + ), + 'live' => array( + 'request' => 'https://pay.doku.com/Suite/Receive', + 'checkstatus' => 'https://pay.doku.com/Suite/CheckStatus', + 'void' => 'https://pay.doku.com/Suite/VoidRequest', + 'registerupdate' => 'https://pay.doku.com/Suite/RecurUpdateCard', + 'registerdelete' => 'https://pay.doku.com/AccountBilling/DoDeleteSubscriptionSuite', + ), + ); + $this->isofile = (isset($configs['isofile']) ? $configs['isofile'] : ''); + if (file_exists($this->isofile)) { + $this->isofile = realpath($this->isofile); + } else { + $this->isofile = (dirname(__FILE__) . '/assets/iso3166.json'); + } + $this->endpoint = (isset($dokupayment_enpoint[$configs['endpoint']]) ? $dokupayment_enpoint[$configs['endpoint']] : false); + $this->mallid = (isset($configs['merchant']['mallid']) ? $configs['merchant']['mallid'] : ''); + $this->shopname = (isset($configs['merchant']['shopname']) ? $configs['merchant']['shopname'] : ''); + $this->chainmerchant = (isset($configs['merchant']['chainmerchant']) ? $configs['merchant']['chainmerchant'] : ''); + $this->sharedkey = (isset($configs['merchant']['sharedkey']) ? $configs['merchant']['sharedkey'] : ''); + # Headers + $this->set_dokupayment_headers(); + $this->add_dokupayment_headers('Content-type', 'application/x-www-form-urlencoded'); + //$this->add_dokupayment_headers('Authorization', "Basic {$this->authorization['authorize']}"); + } + public static function init($configs) { + if (!self::$instance) { + self::$instance = new dokusubscription_DokuPayment($configs); + } + return self::$instance; + } + //--------------------- + function get_paymentchannel($code = 4) { + $code = (int)$code; + $paymentchannels = array( + array('17', 'Subscription'), + ); + if (isset($paymentchannels[$code])) { + return $paymentchannels[$code][0]; + } + return $paymentchannels[0][0]; + } + private function read_isofile($file) { + $contents = ''; + if (!$handle = fopen($file, 'r')) { + exit("Cannot read file"); + } + while (!feof($handle)) { + $contents .= fread($handle, 8192); + } + fclose($handle); + return $contents; + } + public function get_countrycode($isoFile, $isoCountry = "ID", $index = 'numeric') { + $countryData = json_decode($this->read_isofile($isoFile), true); + if (isset($countryData[$isoCountry][$index])) { + return $countryData[$isoCountry][$index]; + } + return false; + } + //--------------------------- + # Example : $this->create_payment_structure('create', 0, $params_input = array(), $user_input = array(), $item_data = array(), $shipping_data = array()); + function create_payment_structure($method, $paymentcode, $params_input, $user_input = array(), $item_data = array(), $shipping_data = null) { + $PaymentStructure = array(); + switch(strtolower($method)) { + case 'create': + default: + $items = array( + 'purchase' => 0, + 'currency' => (isset($params_input['transaction_currency']) ? $params_input['transaction_currency'] : 'ID'), + ); + $create_words = array( + 'amount' => (isset($params_input['amount_total']) ? $params_input['amount_total'] : 0), + 'mallid' => $this->mallid, + 'sharedkey' => $this->sharedkey, + 'transaction_id' => (isset($params_input['transaction_id']) ? $params_input['transaction_id'] : 0), + 'currency' => $items['currency'], + ); + if (count($item_data) > 0) { + foreach ($item_data as $val) { + $items['purchase'] += (isset($val['order_price']) ? $val['order_price'] : 0); + } + } + $PaymentStructure = array( + 'MALLID' => $this->mallid, + 'CHAINMERCHANT' => $this->chainmerchant, + 'AMOUNT' => sprintf("%.2f", floatval($create_words['amount'])), + 'PURCHASEAMOUNT' => sprintf("%.2f", floatval($items['purchase'])), + 'TRANSIDMERCHANT' => $create_words['transaction_id'], + 'PAYMENTTYPE' => 'SALE', // DEFAULT is "SALE" + 'WORDS_STRING' => $this->create_words($method, $create_words), + 'WORDS' => sha1($this->create_words($method, $create_words)), + 'REQUESTDATETIME' => (isset($params_input['transaction_datetime']) ? $params_input['transaction_datetime'] : date('YmdHis')), + 'CURRENCY' => $this->get_countrycode($this->isofile, $create_words['currency']), + 'PURCHASECURRENCY' => $this->get_countrycode($this->isofile, $create_words['currency']), + 'SESSIONID' => (isset($params_input['transaction_session']) ? $params_input['transaction_session'] : ''), + 'NAME' => $user_input['name'], + 'EMAIL' => filter_var($user_input['email'], FILTER_VALIDATE_EMAIL), + 'BASKET' => $this->create_basket($method, $item_data), + 'PAYMENTCHANNEL' => $this->get_paymentchannel($paymentcode), + ); + if (isset($shipping_data)) { + $PaymentStructure['ADDITIONALDATA'] = (isset($user_input['shipping_address']['ADDITIONALDATA']) ? $user_input['shipping_address']['ADDITIONALDATA']: ""); + $PaymentStructure['SHIPPING_ADDRESS'] = (isset($user_input['shipping_address']['SHIPPING_ADDRESS']) ? $user_input['shipping_address']['SHIPPING_ADDRESS'] : ""); + $PaymentStructure['SHIPPING_CITY'] = (isset($user_input['shipping_address']['SHIPPING_CITY']) ? $user_input['shipping_address']['SHIPPING_CITY'] : ""); + $PaymentStructure['SHIPPING_STATE'] = (isset($user_input['shipping_address']['SHIPPING_STATE']) ? $user_input['shipping_address']['SHIPPING_STATE'] : ""); + $PaymentStructure['SHIPPING_COUNTRY'] = (isset($user_input['shipping_address']['SHIPPING_COUNTRY']) ? $user_input['shipping_address']['SHIPPING_COUNTRY'] : ""); + $PaymentStructure['SHIPPING_ZIPCODE'] = (isset($user_input['shipping_address']['SHIPPING_ZIPCODE']) ? $user_input['shipping_address']['SHIPPING_ZIPCODE'] : ""); + # New: + $PaymentStructure['ADDRESS'] = $PaymentStructure['SHIPPING_ADDRESS']; + $PaymentStructure['CITY'] = $PaymentStructure['SHIPPING_CITY']; + $PaymentStructure['STATE'] = $PaymentStructure['SHIPPING_STATE']; + $PaymentStructure['COUNTRY'] = $PaymentStructure['SHIPPING_COUNTRY']; + $PaymentStructure['ZIPCODE'] = $PaymentStructure['SHIPPING_ZIPCODE']; + # + $PaymentStructure['HOMEPHONE'] = (isset($user_input['shipping_address']['phone']) ? $user_input['shipping_address']['phone'] : ""); + $PaymentStructure['MOBILEPHONE'] = (isset($user_input['shipping_address']['phone']) ? $user_input['shipping_address']['phone'] : ""); + $PaymentStructure['WORKPHONE'] = (isset($user_input['shipping_address']['phone']) ? $user_input['shipping_address']['phone'] : ""); + } + ## Remove specific payment channel if < 1 + if ((int)$paymentcode < 1) { + unset($PaymentStructure['PAYMENTCHANNEL']); + } + $PaymentStructure['SESSIONID'] = substr($PaymentStructure['SESSIONID'], 0, 48); + $PaymentStructure['MOBILEPHONE'] = substr($PaymentStructure['MOBILEPHONE'], 0, 12); + $PaymentStructure['WORKPHONE'] = substr($PaymentStructure['WORKPHONE'], 0, 13); + break; + case 'check': + $create_words = array( + 'mallid' => $this->mallid, + 'sharedkey' => $this->sharedkey, + 'transaction_id' => (isset($params_input['transaction_id']) ? $params_input['transaction_id'] : 0), + 'session_id' => (isset($params_input['transaction_session']) ? $params_input['transaction_session'] : ''), + 'currency' => (isset($params_input['transaction_currency']) ? $params_input['transaction_currency'] : '360'), + 'currency_purchase' => (isset($params_input['transaction_currency_purchase']) ? $params_input['transaction_currency_purchase'] : '360'), + ); + $PaymentStructure = array( + 'MALLID' => $this->mallid, + 'CHAINMERCHANT' => $this->chainmerchant, + 'TRANSIDMERCHANT' => $create_words['transaction_id'], + 'SESSIONID' => $create_words['session_id'], + 'WORDS_STRING' => $this->create_words($method, $create_words), + 'WORDS' => sha1($this->create_words($method, $create_words)), + 'PAYMENTCHANNEL' => $this->get_paymentchannel($paymentcode), + 'CURRENCY' => $create_words['currency'], + 'PURCHASECURRENCY' => $create_words['currency_purchase'], + ); + if ((int)$paymentcode < 1) { + unset($PaymentStructure['PAYMENTCHANNEL']); + } else { + // Not using payment-channel anymore + unset($PaymentStructure['PAYMENTCHANNEL']); + } + break; + case 'void': + $create_words = array( + 'mallid' => $this->mallid, + 'sharedkey' => $this->sharedkey, + 'transaction_id' => (isset($params_input['transaction_id']) ? $params_input['transaction_id'] : 0), + 'session_id' => (isset($params_input['transaction_session']) ? $params_input['transaction_session'] : ''), + 'currency' => (isset($params_input['transaction_currency']) ? $params_input['transaction_currency'] : '360'), + 'payment_channel' => (isset($params_input['transaction_channel']) ? $params_input['transaction_channel'] : ''), + ); + + ## + $PaymentStructure = array( + 'MALLID' => $this->mallid, + 'CHAINMERCHANT' => $this->chainmerchant, + 'TRANSIDMERCHANT' => $create_words['transaction_id'], + 'SESSIONID' => $create_words['session_id'], + 'WORDS_STRING' => $this->create_words($method, $create_words), + 'WORDS' => sha1($this->create_words($method, $create_words)), + 'PAYMENTCHANNEL' => $create_words['payment_channel'], + ); + break; + //------ + case 'redirect': + case 'redirect-checking': + $create_words = array( + 'mallid' => $this->mallid, + 'sharedkey' => $this->sharedkey, + 'amount' => (isset($params_input['subscription_amount']) ? sprintf("%.2f", floatval($params_input['subscription_amount'])) : '0.00'), + 'transaction_id' => (isset($params_input['subscription_transaction_id']) ? $params_input['subscription_transaction_id'] : 0), + 'transaction_words' => (isset($params_input['subscription_words']) ? $params_input['subscription_words'] : ''), + 'trans_status' => (isset($params_input['subscription_verify_status']) ? (string)$params_input['subscription_verify_status'] : ''), // 00 + 'payment_channel' => (isset($params_input['subscription_transaction_channel']) ? $params_input['subscription_transaction_channel'] : ''), + 'session_id' => (isset($params_input['subscription_transaction_session']) ? $params_input['subscription_transaction_session'] : ''), + 'customer_id' => (isset($params_input['subscription_transaction_customer']) ? $params_input['subscription_transaction_customer'] : ''), + 'bill_number' => (isset($params_input['subscription_transaction_bill']) ? $params_input['subscription_transaction_bill'] : ''), + ); + ## + $PaymentStructure = array( + 'AMOUNT' => $create_words['amount'], + 'TRANSIDMERCHANT' => $create_words['transaction_id'], + 'WORDS_STRING' => $this->create_words($method, $create_words), + 'WORDS' => sha1($this->create_words($method, $create_words)), + 'WORDS_DOKU' => $create_words['transaction_words'], + 'PAYMENTCHANNEL' => $create_words['payment_channel'], + 'SESSIONID' => $create_words['session_id'], + 'CUTOMERID' => $create_words['customer_id'], + 'BILLNUMBER' => $create_words['bill_number'], + ); + break; + case 'regupdate': + $create_words = array( + 'mallid' => $this->mallid, + 'sharedkey' => $this->sharedkey, + 'chainmerchant' => (isset($params_input['subscription_chainmerchant']) ? $params_input['subscription_chainmerchant'] : $this->chainmerchant), + 'amount' => (isset($params_input['subscription_amount']) ? sprintf("%.2f", floatval($params_input['subscription_amount'])) : '0.00'), + 'transaction_id' => (isset($params_input['subscription_transaction_id']) ? $params_input['subscription_transaction_id'] : 0), + 'transaction_words' => (isset($params_input['subscription_words']) ? $params_input['subscription_words'] : ''), + 'transaction_datetime' => (isset($params_input['subscription_transaction_datetime']) ? $params_input['subscription_transaction_datetime'] : date('YmdHis')), + 'trans_status' => (isset($params_input['subscription_verify_status']) ? (string)$params_input['subscription_verify_status'] : ''), // 0000 + 'payment_channel' => (isset($params_input['subscription_transaction_channel']) ? $params_input['subscription_transaction_channel'] : ''), + 'session_id' => (isset($params_input['subscription_transaction_session']) ? $params_input['subscription_transaction_session'] : ''), + 'customer_id' => (isset($params_input['subscription_transaction_customer']) ? $params_input['subscription_transaction_customer'] : ''), + 'bill_number' => (isset($params_input['subscription_transaction_bill']) ? $params_input['subscription_transaction_bill'] : ''), + ); + ## + $PaymentStructure = array( + 'MALLID' => $create_words['mallid'], + 'CHAINMERCHANT' => $create_words['chainmerchant'], + 'TRANSIDMERCHANT' => $create_words['transaction_id'], + 'WORDS_STRING' => $this->create_words($method, $create_words), + 'WORDS' => sha1($this->create_words($method, $create_words)), + 'REQUESTDATETIME' => $create_words['transaction_datetime'], + 'SESSIONID' => $create_words['session_id'], + 'CUSTOMERID' => $create_words['customer_id'], + 'PAYMENTCHANNEL' => '17', + 'BILLNUMBER' => $create_words['bill_number'], + 'REGISTERAMOUNT' => $create_words['amount'], + ); + break; + case 'regsubscription': + $create_words = array( + 'mallid' => $this->mallid, + 'sharedkey' => $this->sharedkey, + 'chainmerchant' => $this->chainmerchant, + 'customer_id' => (isset($params_input['subscription_transaction_customer']) ? $params_input['subscription_transaction_customer'] : ''), + 'customer_name' => (isset($params_input['subscription_transaction_customer_name']) ? $params_input['subscription_transaction_customer_name'] : ''), + 'customer_email' => (isset($params_input['subscription_transaction_customer_email']) ? $params_input['subscription_transaction_customer_email'] : ''), + 'customer_phone' => (isset($params_input['subscription_transaction_customer_phone']) ? $params_input['subscription_transaction_customer_phone'] : ''), + 'customer_mobile' => (isset($params_input['subscription_transaction_customer_mobile']) ? $params_input['subscription_transaction_customer_mobile'] : ''), + 'bill_number' => (isset($params_input['subscription_transaction_bill']) ? $params_input['subscription_transaction_bill'] : ''), + ); + ## + $PaymentStructure = array( + 'CUSTOMERID' => $create_words['customer_id'], + 'CUSTOMERNAME' => $create_words['customer_name'], + 'CUSTOMEREMAIL' => $create_words['customer_email'], + 'CUSTOMERHOMEPHONE' => $create_words['customer_phone'], + 'CUSTOMERMOBILEPHONE' => $create_words['customer_mobile'], + 'BILLNUMBER' => $create_words['bill_number'], + 'WORDS_STRING' => $this->create_words($method, $create_words), + 'WORDS' => sha1($this->create_words($method, $create_words)), + ); + break; + ####################################################### + # RECURRING + ####################################################### + case 'recurring': + case 'create-recurring': + case 'recurring-create': + case 'subscription': + $items = array( + 'purchase' => 0, + 'currency' => (isset($params_input['transaction_currency']) ? $params_input['transaction_currency'] : 'ID'), + ); + $create_words = array( + 'amount' => (isset($params_input['amount_total']) ? $params_input['amount_total'] : 0), + 'mallid' => $this->mallid, + 'sharedkey' => $this->sharedkey, + 'transaction_id' => (isset($params_input['transaction_id']) ? $params_input['transaction_id'] : 0), + 'currency' => $items['currency'], + ); + if (count($item_data) > 0) { + foreach ($item_data as $val) { + $items['purchase'] += (isset($val['order_price']) ? $val['order_price'] : 0); + } + } + $PaymentStructure = array( + 'MALLID' => $this->mallid, + 'CHAINMERCHANT' => $this->chainmerchant, + 'AMOUNT' => sprintf("%.2f", floatval($create_words['amount'])), + 'PURCHASEAMOUNT' => sprintf("%.2f", floatval($items['purchase'])), + 'TRANSIDMERCHANT' => $create_words['transaction_id'], + 'PAYMENTTYPE' => 'SALE', // DEFAULT is "SALE" + 'WORDS_STRING' => $this->create_words($method, $create_words), + 'WORDS' => sha1($this->create_words($method, $create_words)), + 'REQUESTDATETIME' => (isset($params_input['transaction_datetime']) ? $params_input['transaction_datetime'] : date('YmdHis')), + 'CURRENCY' => $this->get_countrycode($this->isofile, $create_words['currency']), + 'PURCHASECURRENCY' => $this->get_countrycode($this->isofile, $create_words['currency']), + 'SESSIONID' => (isset($params_input['transaction_session']) ? $params_input['transaction_session'] : ''), + 'NAME' => $user_input['name'], + 'EMAIL' => filter_var($user_input['email'], FILTER_VALIDATE_EMAIL), + 'ADDITIONALDATA' => '', + 'BASKET' => $this->create_basket($method, $item_data), + 'CUSTOMERID' => '', + 'PAYMENTCHANNEL' => '17', + ); + if (isset($shipping_data)) { + $PaymentStructure['ADDITIONALDATA'] = (isset($user_input['shipping_address']['ADDITIONALDATA']) ? $user_input['shipping_address']['ADDITIONALDATA']: ""); + $PaymentStructure['SHIPPING_ADDRESS'] = (isset($user_input['shipping_address']['SHIPPING_ADDRESS']) ? $user_input['shipping_address']['SHIPPING_ADDRESS'] : ""); + $PaymentStructure['SHIPPING_CITY'] = (isset($user_input['shipping_address']['SHIPPING_CITY']) ? $user_input['shipping_address']['SHIPPING_CITY'] : ""); + $PaymentStructure['SHIPPING_STATE'] = (isset($user_input['shipping_address']['SHIPPING_STATE']) ? $user_input['shipping_address']['SHIPPING_STATE'] : ""); + $PaymentStructure['SHIPPING_COUNTRY'] = (isset($user_input['shipping_address']['SHIPPING_COUNTRY']) ? $user_input['shipping_address']['SHIPPING_COUNTRY'] : ""); + $PaymentStructure['SHIPPING_ZIPCODE'] = (isset($user_input['shipping_address']['SHIPPING_ZIPCODE']) ? $user_input['shipping_address']['SHIPPING_ZIPCODE'] : ""); + # New: + $PaymentStructure['ADDRESS'] = $PaymentStructure['SHIPPING_ADDRESS']; + $PaymentStructure['CITY'] = $PaymentStructure['SHIPPING_CITY']; + $PaymentStructure['STATE'] = $PaymentStructure['SHIPPING_STATE']; + $PaymentStructure['COUNTRY'] = $PaymentStructure['SHIPPING_COUNTRY']; + $PaymentStructure['ZIPCODE'] = $PaymentStructure['SHIPPING_ZIPCODE']; + $PaymentStructure['HOMEPHONE'] = (isset($user_input['shipping_address']['phone']) ? $user_input['shipping_address']['phone'] : ""); + $PaymentStructure['MOBILEPHONE'] = (isset($user_input['shipping_address']['phone']) ? $user_input['shipping_address']['phone'] : ""); + $PaymentStructure['WORKPHONE'] = (isset($user_input['shipping_address']['phone']) ? $user_input['shipping_address']['phone'] : ""); + # + $PaymentStructure['BIRTHDATE'] = (isset($user_input['shipping_address']['birthdate']) ? $user_input['shipping_address']['birthdate'] : ''); + //------------------------------------------------ + # Recurring Billing + //------------------------------------------------ + $PaymentStructure['CUSTOMERID'] = (isset($params_input['subscription']['CUSTOMERID']) ? $params_input['subscription']['CUSTOMERID'] : ''); + $PaymentStructure['BILLNUMBER'] = (isset($params_input['subscription']['BILLNUMBER']) ? $params_input['subscription']['BILLNUMBER'] : ''); + $PaymentStructure['BILLDETAIL'] = (isset($params_input['subscription']['BILLDETAIL']) ? $params_input['subscription']['BILLDETAIL'] : ''); // Details of payment + $PaymentStructure['BILLTYPE'] = (isset($params_input['subscription']['BILLTYPE']) ? $params_input['subscription']['BILLTYPE'] : 'S'); // S = Shopping, I = Installment, D = Donation, P = Payment, B = Billing (Default is SALE) + $PaymentStructure['STARTDATE'] = (isset($params_input['subscription']['STARTDATE']) ? $params_input['subscription']['STARTDATE'] : ''); // Format: YYYYMMDD + $PaymentStructure['ENDDATE'] = (isset($params_input['subscription']['ENDDATE']) ? $params_input['subscription']['ENDDATE'] : 'NA'); // Format: YYYYMMDD + $PaymentStructure['EXECUTETYPE'] = (isset($params_input['subscription']['EXECUTETYPE']) ? $params_input['subscription']['EXECUTETYPE'] : ''); # DAY / DATE / FULLDATE + $PaymentStructure['EXECUTEDATE'] = (isset($params_input['subscription']['EXECUTEDATE']) ? $params_input['subscription']['EXECUTEDATE'] : ''); # If EXECUTETYPE = DAY (SUN / MON / TUE / WED / THU / FRI / SAT), If EXECUTETYPE = DATE (1 / 2 / 3 / ... / 28), If EXECUTETYPE = FULLDATE (Use format: YYYYMMDD) + $PaymentStructure['EXECUTEMONTH'] = (isset($params_input['subscription']['EXECUTEMONTH']) ? $params_input['subscription']['EXECUTEMONTH'] : ''); # Please select one (JAN / FEB / MAR / APR / MAY / JUN / JUL / AUG / SEP / OCT / NOV / DEC) + $PaymentStructure['FLATSTATUS'] = (isset($params_input['subscription']['FLATSTATUS']) ? $params_input['subscription']['FLATSTATUS'] : 'TRUE'); // Dinamyc AMOUNT = FALSE, Static (Fix) AMOUNT = TRUE + # AMOUNT + $PaymentStructure['REGISTERAMOUNT'] = (isset($params_input['subscription']['REGISTERAMOUNT']) ? $params_input['subscription']['REGISTERAMOUNT'] : ''); + } + break; + //------------------------ Recurring-Notify ------------------------ + case 'notify': + case 'notify-checking': + $create_words = array( + 'amount' => (isset($params_input['subscription_amount']) ? sprintf("%.2f", floatval($params_input['subscription_amount'])) : '0.00'), + 'mallid' => $this->mallid, + 'sharedkey' => $this->sharedkey, + 'transaction_id' => (isset($params_input['subscription_transaction_id']) ? $params_input['subscription_transaction_id'] : 0), + 'result_msg' => (isset($params_input['subscription_result_msg']) ? $params_input['subscription_result_msg'] : ''), // SUCCESS + 'verify_status' => (isset($params_input['subscription_verify_status']) ? $params_input['subscription_verify_status'] : ''), // SUCCESS + 'currency' => (isset($params_input['subscription_transaction_currency']) ? $params_input['subscription_transaction_currency'] : 'ID'), + ); + $create_words['currency'] = $this->get_countrycode($this->isofile, $create_words['currency']); + ## + $PaymentStructure = array( + 'MALLID' => $this->mallid, + 'CHAINMERCHANT' => $this->chainmerchant, + 'TRANSIDMERCHANT' => $create_words['transaction_id'], + 'SESSIONID' => $create_words['session_id'], + 'WORDS_STRING' => $this->create_words($method, $create_words), + 'WORDS' => sha1($this->create_words($method, $create_words)), + 'RESULTMSG' => $create_words['result_msg'], + 'VERIFYSTATUS' => $create_words['verify_status'], + ); + break; + case 'notify-subscription': + case 'notify-recurring': + $create_words = array( + 'amount' => (isset($params_input['subscription_amount']) ? sprintf("%.2f", floatval($params_input['subscription_amount'])) : '0.00'), + 'mallid' => $this->mallid, + 'sharedkey' => $this->sharedkey, + 'transaction_id' => (isset($params_input['subscription_transaction_id']) ? $params_input['subscription_transaction_id'] : 0), + 'session_id' => (isset($params_input['subscription_transaction_session']) ? $params_input['subscription_transaction_session'] : ''), + 'transaction_customer' => (isset($params_input['subscription_transaction_customer']) ? $params_input['subscription_transaction_customer'] : ''), + 'transaction_token' => (isset($params_input['subscription_transaction_token']) ? $params_input['subscription_transaction_token'] : ''), + 'result_msg' => (isset($params_input['subscription_result_msg']) ? $params_input['subscription_result_msg'] : ''), // SUCCESS + 'verify_status' => (isset($params_input['subscription_verify_status']) ? $params_input['subscription_verify_status'] : ''), // SUCCESS + 'currency' => (isset($params_input['subscription_transaction_currency']) ? $params_input['subscription_transaction_currency'] : 'ID'), + ); + $create_words['currency'] = $this->get_countrycode($this->isofile, $create_words['currency']); + ## + $PaymentStructure = array( + 'MALLID' => $this->mallid, + 'CHAINMERCHANT' => $this->chainmerchant, + 'TRANSIDMERCHANT' => $create_words['subscription_transaction_id'], + 'SESSIONID' => $create_words['session_id'], + 'WORDS_STRING' => $this->create_words($method, $create_words), + 'WORDS' => sha1($this->create_words($method, $create_words)), + 'RESULTMSG' => $create_words['result_msg'], + 'VERIFYSTATUS' => $create_words['verify_status'], + ); + break; + case 'notify-subscription-checking': + case 'notify-recurring-checking': + $create_words = array( + 'amount' => (isset($params_input['subscription_amount']) ? sprintf("%.2f", floatval($params_input['subscription_amount'])) : '0.00'), + 'mallid' => $this->mallid, + 'sharedkey' => $this->sharedkey, + 'transaction_id' => (isset($params_input['subscription_transaction_id']) ? $params_input['subscription_transaction_id'] : 0), + 'session_id' => (isset($params_input['subscription_transaction_session']) ? $params_input['subscription_transaction_session'] : ''), + 'transaction_customer' => (isset($params_input['subscription_transaction_customer']) ? $params_input['subscription_transaction_customer'] : ''), + 'transaction_token' => (isset($params_input['subscription_transaction_token']) ? $params_input['subscription_transaction_token'] : ''), + 'result_msg' => (isset($params_input['subscription_result_msg']) ? $params_input['subscription_result_msg'] : ''), // SUCCESS + 'verify_status' => (isset($params_input['subscription_verify_status']) ? $params_input['subscription_verify_status'] : ''), // SUCCESS + 'currency' => (isset($params_input['subscription_transaction_currency']) ? $params_input['subscription_transaction_currency'] : 'ID'), + ); + $create_words['currency'] = $this->get_countrycode($this->isofile, $create_words['currency']); + $create_words['currency_purchase'] = $create_words['currency']; + ## + $PaymentStructure = array( + 'MALLID' => $this->mallid, + 'CHAINMERCHANT' => $this->chainmerchant, + 'TRANSIDMERCHANT' => $create_words['subscription_transaction_id'], + 'SESSIONID' => $create_words['session_id'], + 'WORDS_STRING' => $this->create_words($method, $create_words), + 'WORDS' => sha1($this->create_words($method, $create_words)), + 'CURRENCY' => $create_words['currency'], + 'PURCHASECURRENCY' => $create_words['currency_purchase'], + ); + break; + //--------------------------------------------------------------------------------- + // Subscription Callback + //--------------------------------------------------------------------------------- + case 'subscription-notify': + $create_words = array( + 'mallid' => $this->mallid, + 'sharedkey' => $this->sharedkey, + 'chainmerchant' => (isset($params_input['subscription_chainmerchant']) ? $params_input['subscription_chainmerchant'] : $this->chainmerchant), + 'transaction_id' => (isset($params_input['subscription_transaction_id']) ? $params_input['subscription_transaction_id'] : 0), + 'transaction_bill' => (isset($params_input['subscription_transaction_bill']) ? $params_input['subscription_transaction_bill'] : ''), + 'transaction_customer' => (isset($params_input['subscription_transaction_customer']) ? $params_input['subscription_transaction_customer'] : ''), + 'transaction_card' => (isset($params_input['subscription_transaction_card']) ? $params_input['subscription_transaction_card'] : ''), + 'transaction_status' => (isset($params_input['subscription_transaction_status']) ? $params_input['subscription_transaction_status'] : ''), // SUCCESS + 'transaction_error' => (isset($params_input['subscription_transaction_error']) ? $params_input['subscription_transaction_error'] : ''), + 'transaction_message' => (isset($params_input['subscription_transaction_message']) ? $params_input['subscription_transaction_message'] : ''), + 'transaction_type' => (isset($params_input['subscription_transaction_type']) ? $params_input['subscription_transaction_type'] : ''), // G: Notify Registration T: Notify Update + 'currency' => (isset($params_input['subscription_transaction_currency']) ? $params_input['subscription_transaction_currency'] : 'ID'), + ); + $create_words['currency'] = $this->get_countrycode($this->isofile, $create_words['currency']); + ## + $PaymentStructure = array( + 'MALLID' => $this->mallid, + 'CHAINMERCHANT' => $create_words['chainmerchant'], + 'CUSTOMERID' => $create_words['transaction_customer'], + 'BILLNUMBER' => $create_words['transaction_bill'], + 'TRANSIDMERCHANT' => $create_words['transaction_id'], + 'CARDNUMBER' => $create_words['transaction_card'], + 'STATUS' => $create_words['transaction_status'], + 'ERRORCODE' => $create_words['transaction_error'], + 'MESSAGE' => $create_words['transaction_message'], + 'WORDS_STRING' => $this->create_words($method, $create_words), + 'WORDS' => sha1($this->create_words($method, $create_words)), + 'STATUSTYPE' => $create_words['transaction_type'], + ); + break; + case 'subscription-update': + $create_words = array( + 'mallid' => $this->mallid, + 'sharedkey' => $this->sharedkey, + 'chainmerchant' => (isset($params_input['subscription_chainmerchant']) ? $params_input['subscription_chainmerchant'] : $this->chainmerchant), + 'transaction_id' => (isset($params_input['subscription_transaction_id']) ? $params_input['subscription_transaction_id'] : 0), + 'transaction_bill' => (isset($params_input['subscription_transaction_bill']) ? $params_input['subscription_transaction_bill'] : ''), + 'transaction_customer' => (isset($params_input['subscription_transaction_customer']) ? $params_input['subscription_transaction_customer'] : ''), + 'transaction_card' => (isset($params_input['subscription_transaction_card']) ? $params_input['subscription_transaction_card'] : ''), + 'transaction_status' => (isset($params_input['subscription_transaction_status']) ? $params_input['subscription_transaction_status'] : ''), // SUCCESS + 'transaction_error' => (isset($params_input['subscription_transaction_error']) ? $params_input['subscription_transaction_error'] : ''), + 'transaction_message' => (isset($params_input['subscription_transaction_message']) ? $params_input['subscription_transaction_message'] : ''), + 'transaction_type' => (isset($params_input['subscription_transaction_type']) ? $params_input['subscription_transaction_type'] : ''), // G: Notify Registration T: Notify Update + 'currency' => (isset($params_input['subscription_transaction_currency']) ? $params_input['subscription_transaction_currency'] : 'ID'), + ); + ## + $PaymentStructure = array( + 'MALLID' => $create_words['mallid'], + 'CHAINMERCHANT' => $create_words['chainmerchant'], + 'CUSTOMERID' => $create_words['transaction_customer'], + 'BILLNUMBER' => $create_words['transaction_bill'], + 'CARDNUMBER' => $create_words['transaction_card'], + 'STATUS' => $create_words['transaction_status'], + 'ERRORCODE' => $create_words['transaction_error'], + 'MESSAGE' => $create_words['transaction_message'], + 'WORDS_STRING' => $this->create_words($method, $create_words), + 'WORDS' => sha1($this->create_words($method, $create_words)), + 'STATUSTYPE' => $create_words['transaction_type'], + ); + break; + case 'subscription-process': + $create_words = array( + 'amount' => (isset($params_input['subscription_amount']) ? sprintf("%.2f", floatval($params_input['subscription_amount'])) : '0.00'), + 'mallid' => $this->mallid, + 'sharedkey' => $this->sharedkey, + 'chainmerchant' => (isset($params_input['subscription_chainmerchant']) ? $params_input['subscription_chainmerchant'] : $this->chainmerchant), + 'transaction_id' => (isset($params_input['subscription_transaction_id']) ? $params_input['subscription_transaction_id'] : 0), + 'transaction_bill' => (isset($params_input['subscription_transaction_bill']) ? $params_input['subscription_transaction_bill'] : ''), + 'transaction_customer' => (isset($params_input['subscription_transaction_customer']) ? $params_input['subscription_transaction_customer'] : ''), + 'transaction_card' => (isset($params_input['subscription_transaction_card']) ? $params_input['subscription_transaction_card'] : ''), + 'transaction_status' => (isset($params_input['subscription_transaction_status']) ? $params_input['subscription_transaction_status'] : ''), // SUCCESS + 'transaction_error' => (isset($params_input['subscription_transaction_error']) ? $params_input['subscription_transaction_error'] : ''), + 'transaction_message' => (isset($params_input['subscription_transaction_message']) ? $params_input['subscription_transaction_message'] : ''), + 'transaction_type' => (isset($params_input['subscription_transaction_type']) ? $params_input['subscription_transaction_type'] : ''), // G: Notify Registration T: Notify Update + 'transaction_token' => (isset($params_input['subscription_transaction_token']) ? $params_input['subscription_transaction_token'] : ''), + 'transaction_code' => (isset($params_input['transaction_code']) ? $params_input['transaction_code'] : ''), + 'currency' => (isset($params_input['transaction_currency']) ? $params_input['transaction_currency'] : '360'), + 'transaction_approval' => (isset($params_input['transaction_approval']) ? $params_input['transaction_approval'] : ''), + 'transaction_resultmsg' => (isset($params_input['subscription_result_msg']) ? $params_input['subscription_result_msg'] : ''), + 'transaction_bank' => (isset($params_input['transaction_bank']) ? $params_input['transaction_bank'] : ''), + 'verify_id' => (isset($params_input['subscription_verify_id']) ? $params_input['subscription_verify_id'] : ''), + 'verify_score' => (isset($params_input['subscription_verify_score']) ? $params_input['subscription_verify_score'] : ''), + 'verify_status' => (isset($params_input['subscription_verify_status']) ? $params_input['subscription_verify_status'] : ''), + 'transaction_session' => (isset($params_input['subscription_transaction_session']) ? $params_input['subscription_transaction_session'] : ''), + 'transaction_datetime' => (isset($params_input['transaction_datetime']) ? $params_input['transaction_datetime'] : date('YmdHis')), + + ); + ## + $PaymentStructure = array( + 'MALLID' => $this->mallid, + 'CHAINMERCHANT' => $create_words['chainmerchant'], + 'CUSTOMERID' => $create_words['transaction_customer'], + 'TOKENID' => $create_words['transaction_token'], + 'CARDNUMBER' => $create_words['transaction_card'], + 'BILLNUMBER' => $create_words['transaction_bill'], + 'TRANSIDMERCHANT' => $create_words['transaction_id'], + 'AMOUNT' => $create_words['amount'], + 'CURRENCY' => $create_words['currency'], + 'RESPONSECODE' => $create_words['transaction_code'], + 'APPROVALCODE' => $create_words['transaction_approval'], + 'RESULTMSG' => $create_words['transaction_resultmsg'], + 'BANK' => $create_words['transaction_bank'], + 'VERIFYID' => $create_words['verify_id'], + 'VERIFYSCORE' => $create_words['verify_score'], + 'VERIFYSTATUS' => $create_words['verify_status'], + 'SESSIONID' => $create_words['transaction_session'], + 'PAYMENTDATETIME' => $create_words['transaction_datetime'], + 'WORDS_STRING' => $this->create_words($method, $create_words), + 'WORDS' => sha1($this->create_words($method, $create_words)), + ); + break; + } + return $PaymentStructure; + } + //------------------------------------------------------------ + private function create_words_string($create_words = array()) { + $string_words = array(); + if (count($create_words) > 0) { + foreach ($create_words as $keval) { + $string_words[] = (string)$keval; + } + } + $string = ""; + if (count($string_words) > 0) { + foreach($string_words as $keval) { + $string .= (string)$keval; + } + } + //$string = implode("", $string_words); + $string = trim((string)$string); + return $string; + } + private function create_words_string_alter($create_words = array()) { + $string_words = array(); + if (count($create_words) > 0) { + foreach ($create_words as $keval) { + $string_words[] = strval($keval); + } + } + $string = ""; + if (count($string_words) > 0) { + foreach($string_words as $keval) { + $string .= strval($keval); + } + } + //$string = implode("", $string_words); + $string = trim(strval($string)); + return $string; + } + private function create_words($method, $params_input) { + $return_create_words = ""; + $create_words = array(); + switch(strtolower($method)) { + case 'create': + default: + $create_words = array( + 'amount' => (isset($params_input['amount']) ? sprintf("%.2f", floatval($params_input['amount'])) : '1.00'), + 'mallid' => (isset($params_input['mallid']) ? $params_input['mallid'] : $this->mallid), + 'sharedkey' => (isset($params_input['sharedkey']) ? $params_input['sharedkey'] : $this->sharedkey), + 'transaction_id' => (isset($params_input['transaction_id']) ? $params_input['transaction_id'] : 0), + 'currency' => (isset($params_input['currency']) ? $this->get_countrycode($this->isofile, $params_input['currency']) : '360'), + ); + if ((int)$create_words['currency'] === 360) { // using IDR (indonesia) + unset($create_words['currency']); + } + break; + case 'check': + $create_words = array( + 'mallid' => (isset($params_input['mallid']) ? $params_input['mallid'] : $this->mallid), + 'sharedkey' => (isset($params_input['sharedkey']) ? $params_input['sharedkey'] : $this->sharedkey), + 'transaction_id' => (isset($params_input['transaction_id']) ? $params_input['transaction_id'] : 0), + 'currency' => (isset($params_input['currency']) ? $params_input['currency'] : '360'), + ); + if ((int)$create_words['currency'] === 360) { // using IDR (indonesia) + unset($create_words['currency']); + } + break; + case 'void': + $create_words = array( + 'mallid' => (isset($params_input['mallid']) ? $params_input['mallid'] : $this->mallid), + 'sharedkey' => (isset($params_input['sharedkey']) ? $params_input['sharedkey'] : $this->sharedkey), + 'transaction_id' => (isset($params_input['transaction_id']) ? $params_input['transaction_id'] : 0), + 'session_id' => (isset($params_input['session_id']) ? $params_input['session_id'] : ''), + 'currency' => (isset($params_input['currency']) ? $params_input['currency'] : '360'), + ); + unset($create_words['currency']); // There is no currency on void WORDS + break; + case 'redirect': + case 'redirect-checking': + $create_words = array( + 'amount' => (isset($params_input['amount']) ? sprintf("%.2f", floatval($params_input['amount'])) : '0.00'), + 'sharedkey' => (isset($params_input['sharedkey']) ? $params_input['sharedkey'] : $this->sharedkey), + 'transaction_id' => (isset($params_input['transaction_id']) ? $params_input['transaction_id'] : 0), + 'customer_id' => (isset($params_input['customer_id']) ? $params_input['customer_id'] : ''), + 'bill_number' => (isset($params_input['bill_number']) ? (string)$params_input['bill_number'] : ''), + ); + break; + case 'regupdate': + $create_words = array( + 'mallid' => (isset($params_input['mallid']) ? $params_input['mallid'] : $this->mallid), + 'chainmerchant' => (isset($params_input['chainmerchant']) ? $params_input['chainmerchant'] : $this->chainmerchant), + 'bill_number' => (isset($params_input['bill_number']) ? (string)$params_input['bill_number'] : ''), + 'customer_id' => (isset($params_input['customer_id']) ? $params_input['customer_id'] : ''), + 'sharedkey' => (isset($params_input['sharedkey']) ? $params_input['sharedkey'] : $this->sharedkey), + ); + break; + case 'regsubscription': + $create_words = array( + 'customer_id' => (isset($params_input['customer_id']) ? $params_input['customer_id'] : ''), + 'sharedkey' => (isset($params_input['sharedkey']) ? $params_input['sharedkey'] : $this->sharedkey), + 'bill_number' => (isset($params_input['bill_number']) ? (string)$params_input['bill_number'] : ''), + ); + break; + ########################################################## + case 'create-tokenization': + case 'tokenization': + $create_words = array( + 'amount' => (isset($params_input['amount']) ? sprintf("%.2f", floatval($params_input['amount'])) : '1.00'), + 'mallid' => (isset($params_input['mallid']) ? $params_input['mallid'] : $this->mallid), + 'sharedkey' => (isset($params_input['sharedkey']) ? $params_input['sharedkey'] : $this->sharedkey), + 'transaction_id' => (isset($params_input['transaction_id']) ? $params_input['transaction_id'] : 0), + 'currency' => (isset($params_input['currency']) ? $this->get_countrycode($this->isofile, $params_input['currency']) : '360'), + ); + if ((int)$create_words['currency'] === 360) { // using IDR (indonesia) + unset($create_words['currency']); + } + break; + case 'recurring': + case 'create-recurring': + case 'recurring-create': + case 'subscription': + $create_words = array( + 'amount' => (isset($params_input['amount']) ? sprintf("%.2f", floatval($params_input['amount'])) : '1.00'), + 'mallid' => (isset($params_input['mallid']) ? $params_input['mallid'] : $this->mallid), + 'sharedkey' => (isset($params_input['sharedkey']) ? $params_input['sharedkey'] : $this->sharedkey), + 'transaction_id' => (isset($params_input['transaction_id']) ? $params_input['transaction_id'] : 0), + 'currency' => (isset($params_input['currency']) ? $this->get_countrycode($this->isofile, $params_input['currency']) : '360'), + ); + if ((int)$create_words['currency'] === 360) { // using IDR (indonesia) + unset($create_words['currency']); + } + break; + case 'notify': + case 'notify-checking': + $create_words = array( + 'amount' => (isset($params_input['amount']) ? sprintf("%.2f", floatval($params_input['amount'])) : '0.00'), + 'mallid' => (isset($params_input['mallid']) ? $params_input['mallid'] : $this->mallid), + 'sharedkey' => (isset($params_input['sharedkey']) ? $params_input['sharedkey'] : $this->sharedkey), + 'transaction_id' => (isset($params_input['transaction_id']) ? $params_input['transaction_id'] : 0), + 'result_msg' => (isset($params_input['result_msg']) ? $params_input['result_msg'] : ''), // SUCCESS + 'verify_status' => (isset($params_input['verify_status']) ? $params_input['verify_status'] : ''), // SUCCESS + 'currency' => (isset($params_input['currency']) ? $params_input['currency'] : '360'), + ); + if ((int)$create_words['currency'] === 360) { // using IDR (indonesia) + unset($create_words['currency']); + } + break; + case 'notify-subscription': + case 'notify-recurring': + $create_words = array( + 'transaction_id' => (isset($params_input['transaction_id']) ? $params_input['transaction_id'] : 0), + 'mallid' => (isset($params_input['mallid']) ? $params_input['mallid'] : $this->mallid), + 'sharedkey' => (isset($params_input['sharedkey']) ? $params_input['sharedkey'] : $this->sharedkey), + 'customerid' => (isset($params_input['transaction_customer']) ? $params_input['transaction_customer'] : ''), + 'tokenid' => (isset($params_input['transaction_token']) ? $params_input['transaction_token'] : ''), + 'result_msg' => (isset($params_input['result_msg']) ? $params_input['result_msg'] : ''), // SUCCESS + 'verify_status' => (isset($params_input['verify_status']) ? $params_input['verify_status'] : ''), // REVIEW + ); + //(transidmerchant+mallid+sharedkey+customerid+tokenid+resultmsg+verifystatus) + break; + case 'notify-subscription-checking': + case 'notify-recurring-checking': + $create_words = array( + 'mallid' => (isset($params_input['mallid']) ? $params_input['mallid'] : $this->mallid), + 'sharedkey' => (isset($params_input['sharedkey']) ? $params_input['sharedkey'] : $this->sharedkey), + 'transaction_id' => (isset($params_input['transaction_id']) ? $params_input['transaction_id'] : 0), + 'currency' => (isset($params_input['currency']) ? $params_input['currency'] : '360'), + ); + if ((int)$create_words['currency'] === 360) { // using IDR (indonesia) + unset($create_words['currency']); + } + break; + //---------------------------------------------- + case 'subscription-notify': + $create_words = array( + 'mallid' => (isset($params_input['mallid']) ? $params_input['mallid'] : $this->mallid), + 'chainmerchant' => (isset($params_input['chainmerchant']) ? $params_input['chainmerchant'] : $this->chainmerchant), + 'transaction_bill' => (isset($params_input['transaction_bill']) ? $params_input['transaction_bill'] : 0), + 'transaction_customer' => (isset($params_input['transaction_customer']) ? $params_input['transaction_customer'] : ''), + 'transaction_status' => (isset($params_input['transaction_status']) ? $params_input['transaction_status'] : ''), // SUCCESS + 'sharedkey' => (isset($params_input['sharedkey']) ? $params_input['sharedkey'] : $this->sharedkey), + ); + break; + case 'subscription-update': + $create_words = array( + 'mallid' => (isset($params_input['mallid']) ? $params_input['mallid'] : $this->mallid), + 'chainmerchant' => (isset($params_input['chainmerchant']) ? $params_input['chainmerchant'] : $this->chainmerchant), + 'transaction_bill' => (isset($params_input['transaction_bill']) ? $params_input['transaction_bill'] : 0), + 'transaction_customer' => (isset($params_input['transaction_customer']) ? $params_input['transaction_customer'] : ''), + 'transaction_status' => (isset($params_input['transaction_status']) ? $params_input['transaction_status'] : ''), // SUCCESS + 'sharedkey' => (isset($params_input['sharedkey']) ? $params_input['sharedkey'] : $this->sharedkey), + ); + break; + case 'subscription-process': + $create_words = array( + 'transaction_id' => (isset($params_input['transaction_id']) ? $params_input['transaction_id'] : ''), + 'mallid' => (isset($params_input['mallid']) ? $params_input['mallid'] : $this->mallid), + 'sharedkey' => (isset($params_input['sharedkey']) ? $params_input['sharedkey'] : $this->sharedkey), + 'transaction_customer' => (isset($params_input['transaction_customer']) ? $params_input['transaction_customer'] : ''), + 'transaction_token' => (isset($params_input['transaction_token']) ? $params_input['transaction_token'] : ''), + 'transaction_bill' => (isset($params_input['transaction_bill']) ? $params_input['transaction_bill'] : 0), + 'transaction_resultmsg' => (isset($params_input['transaction_resultmsg']) ? $params_input['transaction_resultmsg'] : ''), + 'verify_status' => (isset($params_input['verify_status']) ? $params_input['verify_status'] : ''), + ); + break; + } + return $this->create_words_string($create_words); + } + //---------------------------------------------- + public function check_status_payment($method, $params_input) { + $CheckStructure = array(); + switch (strtolower($method)) { + case 'check': + $CheckStructure = $this->create_payment_structure('check', 0, $params_input); + unset($CheckStructure['WORDS_STRING']); + ksort($CheckStructure); + break; + } + return $this->create_curl_request('POST', $this->client['checkstatus'], 'TDP/Api.Context', $this->create_curl_headers(), $CheckStructure, 30); + } + //---------------------------------------------- + private function create_basket($method, $item_data) { + $create_item_details = array(); + $string_return = array(); + foreach ($item_data as $val) { + $create_item_details[] = array( + 'item_name' => (isset($val['order_item_name']) ? $val['order_item_name'] : ""), + 'item_price' => (isset($val['order_price']) ? $val['order_price'] : 0), + 'item_unit' => (isset($val['order_unit']) ? $val['order_unit'] : 1), + 'item_price_total' => ((isset($val['order_price']) && isset($val['order_unit'])) ? ($val['order_price'] * $val['order_unit']) : 0), + ); + } + if (count($create_item_details) > 0) { + foreach ($create_item_details as &$val) { + $val['item_price'] = sprintf("%.2f", floatval($val['item_price'])); + $val['item_price_total'] = sprintf("%.2f", floatval($val['item_price_total'])); + $string_return[] = implode(",", $val); + } + } + if (count($string_return) > 0) { + return implode(";", $string_return); + } else { + return ""; + } + } + //----------------------------------------------------------------------------- + public static function doku_incoming_callback() { + ############################### + # Request Input + $RequestInputParams = array(); + $RequestInput = file_get_contents("php://input"); + $incomingHeaders = self::apache_headers(); + if (isset($incomingHeaders['Content-Type'])) { + if ((!is_array($incomingHeaders['Content-Type'])) && (!is_object($incomingHeaders['Content-Type']))) { + if (0 === strpos($incomingHeaders['Content-Type'], 'application/json')) { + if (!$RequestInputJson = json_decode($RequestInput, true)) { + parse_str($RequestInput, $RequestInputParams); + } else { + $RequestInputParams = $RequestInputJson; + } + } else if (0 === strpos($incomingHeaders['Content-Type'], 'application/xml')) { + $RequestInputParams = $RequestInput; + } else { + parse_str($RequestInput, $RequestInputParams); + } + } + } else { + parse_str($RequestInput, $RequestInputParams); + } + $params['input'] = $RequestInput; + $params['header'] = $incomingHeaders; + $params['body'] = $RequestInputParams; + return $params; + } + public static function _GET(){ + $__GET = (isset($_GET) ? $_GET : array()); + $request_uri = ((isset($_SERVER['REQUEST_URI']) && (!empty($_SERVER['REQUEST_URI']))) ? $_SERVER['REQUEST_URI'] : ''); + $_get_str = explode('?', $request_uri); + if( !isset($_get_str[1]) ) return $__GET; + $params = explode('&', $_get_str[1]); + foreach ($params as $p) { + $parts = explode('=', $p); + $parts[0] = (is_string($parts[0]) ? strtolower($parts[0]) : $parts[0]); + $__GET[$parts[0]] = isset($parts[1]) ? $parts[1] : ''; + } + return $__GET; + } + public static function get_query_string() { + $__GET = (isset($_GET) ? $_GET : array()); + $request_uri = ((isset($_SERVER['REQUEST_URI']) && (!empty($_SERVER['REQUEST_URI']))) ? $_SERVER['REQUEST_URI'] : ''); + $query_string = (isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : ''); + parse_str(parse_url(html_entity_decode($request_uri), PHP_URL_QUERY), $array); + if (count($array) > 0) { + foreach ($array as $key => $val) { + $__GET[$key] = $val; + } + } + return $__GET; + } + //----------------------------------------------------------------------------- + function set_dokupayment_headers($headers = array()) { + $this->dokupayment_headers = $headers; + return $this; + } + function reset_dokupayment_headers() { + $this->dokupayment_headers = null; + return $this; + } + function add_dokupayment_headers($key, $val) { + if (!isset($this->dokupayment_headers)) { + $this->dokupayment_headers = $this->get_dokupayment_headers(); + } + $add_header = array($key => $val); + $this->dokupayment_headers = array_merge($add_header, $this->dokupayment_headers); + } + function get_dokupayment_headers() { + return $this->dokupayment_headers; + } + //------------------------------------------------------------------------------------------------------ + function create_curl_request($action, $url, $UA, $headers = null, $params = array(), $timeout = 30) { + $cookie_file = (dirname(__FILE__).'/cookies.txt'); + $url = str_replace( "&", "&", urldecode(trim($url)) ); + $ch = curl_init(); + switch (strtolower($action)) { + case 'get': + if ((is_array($params)) && (count($params) > 0)) { + $Querystring = http_build_query($params); + $url .= "?"; + $url .= $Querystring; + } + break; + case 'post': + default: + $url .= ""; + break; + } + curl_setopt($ch, CURLOPT_URL, $url); + curl_setopt($ch, CURLOPT_VERBOSE, true); + if ($headers != null) { + curl_setopt($ch, CURLOPT_HEADER, true); + curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); + } else { + curl_setopt($ch, CURLOPT_HEADER, false); + } + curl_setopt($ch, CURLOPT_USERAGENT, $UA); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + //curl_setopt($ch, CURLOPT_COOKIE, $cookie_file); + //curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file); + curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); + curl_setopt($ch, CURLOPT_ENCODING, ""); + curl_setopt($ch, CURLOPT_AUTOREFERER, true); + curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); + curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); + curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); + curl_setopt($ch, CURLOPT_MAXREDIRS, 10); + $post_fields = NULL; + switch (strtolower($action)) { + case 'get': + curl_setopt($ch, CURLOPT_POST, false); + curl_setopt($ch, CURLOPT_POSTFIELDS, null); + curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET'); + break; + case 'post': + default: + if ((is_array($params)) && (count($params) > 0) && (is_array($headers) && count($headers) > 0)) { + foreach ($headers as $heval) { + $getContentType = explode(":", $heval); + if (strtolower($getContentType[0]) !== 'content-type') { + continue; + } + switch (strtolower(trim($getContentType[0]))) { + case 'content-type': + if (isset($getContentType[1])) { + switch (strtolower(trim($getContentType[1]))) { + case 'application/xml': + $post_fields = $post_fields; + break; + case 'application/json': + $post_fields = json_encode($params, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); + break; + case 'application/x-www-form-urlencoded': + $post_fields = http_build_query($params); + break; + default: + $post_fields = http_build_query($params); + break; + } + } + break; + default: + $post_fields = http_build_query($params); + break; + } + } + } else if ((!empty($params)) || ($params != '')) { + $post_fields = $params; + } + curl_setopt($ch, CURLOPT_POST, true); + curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields); + break; + } + // Get Response + $response = curl_exec($ch); + $mixed_info = curl_getinfo($ch); + $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE); + $header_string = substr($response, 0, $header_size); + $header_content = $this->get_headers_from_curl_response($header_string); + $header_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); + if (count($header_content) > 1) { + $header_content = end($header_content); + } + $body = substr($response, $header_size); + curl_close ($ch); + $return = array( + 'request' => array( + 'method' => $action, + 'host' => $url, + 'header' => $headers, + 'body' => $post_fields, + ), + 'response' => array(), + ); + if (!empty($response) || $response != '') { + $return['response']['code'] = (int)$header_code; + $return['response']['header'] = array( + 'size' => $header_size, + 'string' => $header_string, + 'content' => $header_content, + ); + $return['response']['body'] = $body; + return $return; + } + return false; + } + private static function get_headers_from_curl_response($headerContent) { + $headers = array(); + // Split the string on every "double" new line. + $arrRequests = explode("\r\n\r\n", $headerContent); + // Loop of response headers. The "count($arrRequests) - 1" is to + // avoid an empty row for the extra line break before the body of the response. + for ($index = 0; $index < (count($arrRequests) - 1); $index++) { + foreach (explode("\r\n", $arrRequests[$index]) as $i => $line) { + if ($i === 0) { + $headers[$index]['http_code'] = $line; + } else { + list ($key, $value) = explode(': ', $line); + $headers[$index][$key] = $value; + } + } + } + return $headers; + } + public function create_curl_headers($headers = array()) { + $curlheaders = array(); + foreach ($headers as $ke => $val) { + $curlheaders[] = "{$ke}: {$val}"; + } + return $curlheaders; + } + public static function apache_headers() { + if (function_exists('apache_request_headers')) { + $headers = apache_request_headers(); + $out = array(); + foreach ($headers AS $key => $value) { + $key = str_replace(" ", "-", ucwords(strtolower(str_replace("-", " ", $key)))); + $out[$key] = $value; + } + } else { + $out = array(); + if (isset($_SERVER['CONTENT_TYPE'])) { + $out['Content-Type'] = $_SERVER['CONTENT_TYPE']; + } + if (isset($_ENV['CONTENT_TYPE'])) { + $out['Content-Type'] = $_ENV['CONTENT_TYPE']; + foreach ($_SERVER as $key => $value) { + if (substr($key, 0, 5) == "HTTP_") { + $key = str_replace(" ", "-", ucwords(strtolower(str_replace("_", " ", substr($key, 5))))); + $out[$key] = $value; + } + } + } + } + return $out; + } + // --------------------------------- + // Utilities + // --------------------------------- + function create_custom_arraytoxml($root, $params = array()) { + # Create XML (return object) + $obj_xml = new SimpleXMLElement($root); + $this->custom_arraytoxml($params, $obj_xml); + return $obj_xml; + } + function render_custom_arraytoxml($obj_xml) { + $xml_formatted = $obj_xml->asXML(); + //$xml_formatted = str_replace('', '', $xml_formatted); + //$xml_formatted = str_replace('', '', $xml_formatted); + $domXML = new DOMDocument('1.0'); + $domXML->preserveWhiteSpace = false; + $domXML->formatOutput = true; + $domXML->loadXML($xml_formatted); + $xml_formatted = $domXML->saveXML(); + return $xml_formatted; + } + // Create Unique Billno by Datetime + function generate_transaction_id($timezone = "Asia/Bangkok") { + $microtime = microtime(true); + $micro = sprintf("%06d",($microtime - floor($microtime)) * 1000000); + $DateObject = new DateTime(date("Y-m-d H:i:s.{$micro}", $microtime)); + $DateObject->setTimezone(new DateTimeZone($timezone)); + return $DateObject->format('YmdHisu'); + } + // Create Dateobject + function get_datetime_object($timezone = 'Asia/Bangkok') { + $DateObject = new DateTime(date("Y-m-d H:i:s")); + $DateObject->setTimezone(new DateTimeZone($timezone)); + return $DateObject; + } + function get_ip_address($data = null) { + // Get user IP address + $ip = (isset($data)) ? $data : '0.0.0.0'; + if(strpos($ip, ',')) { + $ip2 = explode(',', $ip); + $ip = $ip2[0]; + if(strpos($ip, '192.168.') !== false && isset($ip2[1])) + { + $ip = $ip2[1]; + } + elseif(strpos($ip, '10.') !== false && isset($ip2[1])) + { + $ip = $ip2[1]; + } + elseif(strpos($ip, '172.16.') !== false && isset($ip2[1])) + { + $ip = $ip2[1]; + } + + } + $ip = filter_var($ip, FILTER_VALIDATE_IP); + $ip = ($ip === false) ? '0.0.0.0' : $ip; + return $ip; + } + //---------------------------------------------- + function custom_arraytoxml($array, &$xml){ + foreach ($array as $key => $value) { + if(is_array($value)){ + if(is_int($key)) { + $key = "e"; + } + $label = $xml->addChild($key); + $this->custom_arraytoxml($value, $label); + } else { + $xml->addChild($key, $value); + } + } + } + function xmltoarray($contents, $get_attributes=1) { + if(!$contents) return array(); + if(!function_exists('xml_parser_create')) { + return array(); + } + $parser = xml_parser_create(); + xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, 0 ); + xml_parser_set_option( $parser, XML_OPTION_SKIP_WHITE, 1 ); + xml_parse_into_struct( $parser, $contents, $xml_values ); + xml_parser_free( $parser ); + if(!$xml_values) return; + $xml_array = array(); + $parents = array(); + $opened_tags = array(); + $arr = array(); + $current = &$xml_array; + foreach($xml_values as $data) { + unset($attributes,$value); + extract($data); + $result = ''; + if($get_attributes) { + $result = array(); + if(isset($value)) $result['value'] = $value; + if(isset($attributes)) { + foreach($attributes as $attr => $val) { + if($get_attributes == 1) $result['attr'][$attr] = $val; + } + } + } elseif(isset($value)) { + $result = $value; + } + if($type == "open") { + $parent[$level-1] = &$current; + if(!is_array($current) or (!in_array($tag, array_keys($current)))) { + $current[$tag] = $result; + $current = &$current[$tag]; + } else { + if(isset($current[$tag][0])) { + array_push($current[$tag], $result); + } else { + $current[$tag] = array($current[$tag],$result); + } + $last = count($current[$tag]) - 1; + $current = &$current[$tag][$last]; + } + } elseif($type == "complete") { + if(!isset($current[$tag])) { + $current[$tag] = $result; + } else { + if((is_array($current[$tag]) and $get_attributes == 0) + or (isset($current[$tag][0]) and is_array($current[$tag][0]) and $get_attributes == 1)) { + array_push($current[$tag],$result); + } else { + $current[$tag] = array($current[$tag],$result); + } + } + } elseif($type == 'close') { + $current = &$parent[$level-1]; + } + } + return($xml_array); + } +} \ No newline at end of file diff --git a/modules/gateways/dokusubscription.php b/modules/gateways/dokusubscription.php new file mode 100644 index 0000000..b2ee827 --- /dev/null +++ b/modules/gateways/dokusubscription.php @@ -0,0 +1,1017 @@ + 'DOKU - Subscription', + 'APIVersion' => '1.1', // Use API Version 1.1 + 'DisableLocalCredtCardInput' => true, + 'TokenisedStorage' => false, + ); +} + +//--------------- +// URL show to admin page +Class dokusubscription_DokuAdmin { + public static $notify = false; + public static $redirect = false; + public static $review = false; + public static $identify = false; + public static $regsubscription = false; + public static $regupdate = false; + public static $regupdatenotify = false; + public static $DOKUCONFIGS; + public function __construct($configs = array()) { + $this->set_protocol(self::getDokuPaymentProtocol()); + $this->protocol = (isset($this->protocol) ? $this->protocol : $this->get_protocol()); + $this->set_hostname(self::getDokuPaymentHost()); + $this->hostname = (isset($this->hostname) ? $this->hostname : $this->get_hostname()); + $this->set_url('notify', "{$this->protocol}{$this->hostname}modules/gateways/callback/dokusubscription.php?page=notify"); + $this->set_url('redirect', "{$this->protocol}{$this->hostname}modules/gateways/callback/dokusubscription.php?page=redirect"); + $this->set_url('review', "{$this->protocol}{$this->hostname}modules/gateways/callback/dokusubscription.php?page=review"); + $this->set_url('identify', "{$this->protocol}{$this->hostname}modules/gateways/callback/dokusubscription.php?page=identify"); + $this->set_url('regsubscription', "{$this->protocol}{$this->hostname}modules/gateways/callback/dokusubscription.php?page=subscription"); + $this->set_url('regupdate', "{$this->protocol}{$this->hostname}modules/gateways/callback/dokusubscription.php?page=regupdate"); + $this->set_url('regupdatenotify', "{$this->protocol}{$this->hostname}modules/gateways/callback/dokusubscription.php?page=notify"); + // Set GLOBAL $DOKUCONFIGS + self::$DOKUCONFIGS = $configs; + } + public static function getDokuPaymentConfigs($Vars) { + $configs = array(); + if (!isset(self::$DOKUCONFIGS)) { + return false; + } + switch (strtolower($Vars)) { + case 'channels': + $configs = (isset(self::$DOKUCONFIGS['paymentchannels']) ? self::$DOKUCONFIGS['paymentchannels'] : NULL); + break; + case 'acquirers': + $configs = (isset(self::$DOKUCONFIGS['paymentacquirers']) ? self::$DOKUCONFIGS['paymentacquirers'] : NULL); + break; + case 'tenors': + $configs = (isset(self::$DOKUCONFIGS['paymenttenors']) ? self::$DOKUCONFIGS['paymenttenors'] : NULL); + break; + } + return $configs; + } + public static function getDokuPaymentProtocol() { + if (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) { + if ( $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' ) { + $_SERVER['HTTPS'] = 'on'; + $_SERVER['SERVER_PORT'] = 443; + } + } + $protocol = 'http://'; + if (isset($_SERVER['HTTPS'])) { + $protocol = (($_SERVER['HTTPS'] == 'on') ? 'https://' : 'http'); + } else { + $protocol = (isset($_SERVER["SERVER_PROTOCOL"]) ? $_SERVER["SERVER_PROTOCOL"] : 'http'); + $protocol = ((strtolower(substr($protocol, 0, 5)) =='https') ? 'https://': 'http://'); + } + return $protocol; + } + public static function getDokuPaymentHost() { + $currentPath = (isset($_SERVER['SCRIPT_NAME']) ? $_SERVER['SCRIPT_NAME'] : ''); + $pathInfo = pathinfo(dirname($currentPath)); + $hostName = (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ''); + $return = $hostName; + $return .= ((substr($hostName, -1) == '/') ? '' : '/'); + return $return; + } + public static function _GET(){ + $__GET = array(); + $request_uri = ((isset($_SERVER['REQUEST_URI']) && (!empty($_SERVER['REQUEST_URI']))) ? $_SERVER['REQUEST_URI'] : '/'); + $_get_str = explode('?', $request_uri); + if( !isset($_get_str[1]) ) return $__GET; + $params = explode('&', $_get_str[1]); + foreach ($params as $p) { + $parts = explode('=', $p); + $__GET[$parts[0]] = isset($parts[1]) ? $parts[1] : ''; + } + return $__GET; + } + public function set_hostname($hostname) { + $this->hostname = $hostname; + return $this; + } + public function get_hostname() { + return $this->hostname; + } + public function set_protocol($protocol) { + $this->protocol = $protocol; + return $this; + } + public function get_protocol() { + return $this->protocol; + } + public static function set_url($type, $url) { + switch (strtolower($type)) { + case 'notify': + default: + self::$notify = $url; + break; + case 'redirect': + self::$redirect = $url; + break; + case 'review': + self::$review = $url; + break; + case 'identify': + self::$identify = $url; + break; + case 'regsubscription': + self::$regsubscription = $url; + break; + case 'regupdate': + self::$regupdate = $url; + break; + case 'regupdatenotify': + self::$regupdatenotify = $url; + break; + } + } +} +// Start new DokuAdmin instance +/* +error_reporting(E_ALL); +ini_set('display_startup_errors', true); +ini_set('display_errors', true); +*/ +// Include @DOKUCONFIGS +$configfile = (dirname(__FILE__) . '/dokuhosted/dokusubscription-config.php'); +if (!file_exists($configfile)) { + Exit("Required configs file does not exists."); +} +require($configfile); +if (!isset($DOKUCONFIGS)) { + Exit("There is no DOKUCONFIGS of included config file."); +} +$DokuAdmin = new dokusubscription_DokuAdmin($DOKUCONFIGS); +/** + * Define gateway configuration options. + * + * The fields you define here determine the configuration options that are + * presented to administrator users when activating and configuring your + * payment gateway module for use. + * + * Supported field types include: + * * text + * * password + * * yesno + * * dropdown + * * radio + * * textarea + * + * Examples of each field type and their possible configuration parameters are + * provided in the sample function below. + * + * @return array + */ +// Require doku-payment class instance +require('dokuhosted/dokusubscription-whmcs.php'); +function dokusubscription_config() { + $configs = array( + // the friendly display name for a payment gateway should be + // defined here for backwards compatibility + 'FriendlyName' => array( + 'Type' => 'System', + 'Value' => 'DOKU - Subscription', + ), + // a text field type allows for single line text input + # Sandbox + //------------- + 'Pembatas-Sandbox' => array( + "FriendlyName" => "(*)", + "Type" => 'hidden', + "Size" => "64", + "Value" => '', + "Description" => 'Sandbox Params', + ), + //------------- + 'MallId' => array( + 'FriendlyName' => 'Sandbox: Mall ID', + 'Type' => 'text', + 'Size' => '25', + 'Default' => '', + 'Description' => 'Enter your Mall ID here', + ), + /* + 'ShopName' => array( + 'FriendlyName' => 'Sandbox: Shop Name', + 'Type' => 'text', + 'Size' => '25', + 'Default' => '', + 'Description' => 'Enter Shop Name here', + ), + */ + 'ChainMerchant' => array( + 'FriendlyName' => 'Development: Chain Merchant Name (Default is: NA)', + 'Type' => 'text', + 'Size' => '25', + 'Default' => 'NA', + 'Description' => 'Enter Chain Merchant Name (Default is: NA)', + ), + 'SharedKey' => array( + 'FriendlyName' => 'Sandbox: Shared Key', + 'Type' => 'text', + 'Size' => '25', + 'Default' => '', + 'Description' => 'Enter Shared Key you got from DOKU Dashboard', + ), + //------------- + 'Pembatas-Live' => array( + "FriendlyName" => "(*)", + "Type" => 'hidden', + "Size" => "64", + "Value" => '', + "Description" => 'Production Params', + ), + //------------- + # Live + 'MallId_Live' => array( + 'FriendlyName' => '(*)Production: Mall ID', + 'Type' => 'text', + 'Size' => '25', + 'Default' => '', + 'Description' => 'Enter your Mall ID here', + ), + /* + 'ShopName_Live' => array( + 'FriendlyName' => '(*)Production: Shop Name', + 'Type' => 'text', + 'Size' => '25', + 'Default' => '', + 'Description' => 'Enter Shop Name here', + ), + */ + 'ChainMerchant_Live' => array( + 'FriendlyName' => '(*)Production: Chain Merchant Name (Default is: NA)', + 'Type' => 'text', + 'Size' => '25', + 'Default' => 'NA', + 'Description' => 'Enter Chain Merchant Name (Default is: NA)', + ), + 'SharedKey_Live' => array( + 'FriendlyName' => '(*)Production: Shared Key', + 'Type' => 'text', + 'Size' => '25', + 'Default' => '', + 'Description' => 'Enter Shared Key you got from DOKU Dashboard', + ), + //------------- + 'Pembatas-Global-Params' => array( + "FriendlyName" => "", + "Type" => 'hidden', + "Size" => "64", + "Value" => '', + "Description" => 'Global Params', + ), + //------------- + # GLOBAL + // the dropdown field type renders a select menu of options (LOGGER) + 'Log-Enabled' => array( + 'FriendlyName' => "Use Logger on Transaction Log? (Billing > Gateway Log)", + 'Type' => "yesno", + 'Description' => "Tick this box to enable Logging", + ), + // the dropdown field type renders a select menu of options + 'Environment' => array( + 'FriendlyName' => 'Environment Mode', + 'Type' => 'dropdown', + 'Options' => array( + 'sandbox' => 'Sandbox', + 'live' => 'Production', + ), + 'Description' => 'Choose environment, sandbox or production', + ), + "EDU-Enabled" => array( + 'FriendlyName' => "Use EDU?", + 'Type' => "yesno", + 'Description' => "Tick this box to enable EDU", + ), + "Identify-Enabled" => array( + 'FriendlyName' => "Use Identify?", + 'Type' => "yesno", + 'Description' => "Tick this box to enable DOKU Identify", + ), + "Void-Enabled" => array( + 'FriendlyName' => "Use Void?", + 'Type' => "yesno", + 'Description' => "Tick this box to enable Payment Void", + ), + #################### + "PaymentCheck-Enabled" => array( + 'FriendlyName' => "Enable Payment Check During Notify and Redirect", + 'Type' => "yesno", + 'Description' => "Tick this box to enable Payment Check (We recomended you enabled payment-check to verified payment for security purpose)", + ), + 'URL-Notify' => array( + "FriendlyName" => "Enter your URL Notify to DOKU Dasboard", + "Type" => 'hidden', + "Size" => "64", + "Default" => dokusubscription_DokuAdmin::$notify, + "Description" => dokusubscription_DokuAdmin::$notify, + ), + 'URL-Redirect' => array( + "FriendlyName" => "Enter your URL Redirect to DOKU Dasboard", + "Type" => 'hidden', + "Size" => "64", + "Default" => dokusubscription_DokuAdmin::$redirect, + "Description" => dokusubscription_DokuAdmin::$redirect, + ), + /* + 'URL-Review' => array( + "FriendlyName" => "Enter your URL Review to DOKU Dasboard", + "Type" => 'hidden', + "Size" => "64", + "Default" => dokusubscription_DokuAdmin::$review, + "Description" => dokusubscription_DokuAdmin::$review, + ), + 'URL-Identify' => array( + "FriendlyName" => "Enter your URL Identify to DOKU Dasboard", + "Type" => 'hidden', + "Size" => "64", + "Default" => dokusubscription_DokuAdmin::$identify, + "Description" => dokusubscription_DokuAdmin::$identify, + ), + 'URL-RegSubscription' => array( + "FriendlyName" => "Enter your URL Subscription Get Amount to DOKU Dasboard", + "Type" => 'hidden', + "Size" => "64", + "Default" => dokusubscription_DokuAdmin::$regsubscription, + "Description" => dokusubscription_DokuAdmin::$regsubscription, + ), + 'URL-RegUpdate' => array( + "FriendlyName" => "Enter your URL Register Update Redirect to DOKU Dasboard", + "Type" => 'hidden', + "Size" => "64", + "Default" => dokusubscription_DokuAdmin::$regupdate, + "Description" => dokusubscription_DokuAdmin::$regupdate, + ), + 'URL-RegUpdateNotify' => array( + "FriendlyName" => "Enter your URL Update Notify to DOKU Dasboard", + "Type" => 'hidden', + "Size" => "64", + "Default" => dokusubscription_DokuAdmin::$regupdatenotify, + "Description" => dokusubscription_DokuAdmin::$regupdatenotify, + ), + */ + //-------------------- + 'Local-Api-Admin-Username' => array( + 'FriendlyName' => '(*) WHMCS Admin Username for using WHMCS::localAPI().', + 'Type' => 'text', + 'Size' => '22', + 'Default' => '', + 'Description' => 'Enter your WHMCS Admin Username for using WHMCS::localAPI().', + ), + //---------------------------------------------------------------------------- + ); + //------------------------------------------------------ + return $configs; +} +/** +// Subscription +// Fill Credit Card +*/ +//function dokusubscription_capture($params) { +function dokusubscription_link($params) { + $Log_Enabled = FALSE; + if (isset($params['Log-Enabled'])) { + $Log_Enabled = ((strtolower($params['Log-Enabled']) == 'on') ? TRUE : FALSE); + } + $htmlReturn = ""; + $htmlForm = ""; + $htmlFormSubmit = ""; + $rawdata = array(); + $LocalApiAdminUsername = (isset($params['Local-Api-Admin-Username']) ? $params['Local-Api-Admin-Username'] : ''); + $localApi = array( + 'command' => 'GetOrders', //'GetInvoice', + 'data' => array( + //'id' => '', // Later updated on review case + 'invoiceid' => '', # Later updated on review case + ), + 'username' => $LocalApiAdminUsername, // Optional for WHMCS 7.2 and later + ); + // Error GLOBAL + $error = false; + $error_msg = array(); + //--------------------------- + $Environment = (isset($params['Environment']) ? $params['Environment'] : 'sandbox'); // Sandbox as Default-Environment + if (!is_string($Environment) && ((!is_array($Environment)) || (!is_object($Environment)))) { + if (strtolower($Environment) === strtolower('live')) { + // Gateway Configuration Parameters + $MallId = (isset($params['MallId_Live']) ? $params['MallId_Live'] : ''); + $ShopName = (isset($params['ShopName_Live']) ? $params['ShopName_Live'] : ''); + $ChainMerchant = (isset($params['ChainMerchant_Live']) ? $params['ChainMerchant_Live'] : 'NA'); + $SharedKey = (isset($params['SharedKey_Live']) ? $params['SharedKey_Live'] : ''); + } else { + // Gateway Configuration Parameters + $MallId = (isset($params['MallId']) ? $params['MallId'] : ''); + $ShopName = (isset($params['ShopName']) ? $params['ShopName'] : ''); + $ChainMerchant = (isset($params['ChainMerchant']) ? $params['ChainMerchant'] : 'NA'); + $SharedKey = (isset($params['SharedKey']) ? $params['SharedKey'] : ''); + } + } else { + // Gateway Configuration Parameters + $MallId = (isset($params['MallId']) ? $params['MallId'] : ''); + $ShopName = (isset($params['ShopName']) ? $params['ShopName'] : ''); + $ChainMerchant = (isset($params['ChainMerchant']) ? $params['ChainMerchant'] : 'NA'); + $SharedKey = (isset($params['SharedKey']) ? $params['SharedKey'] : ''); + } + $LocalApiAdminUsername = (isset($params['Local-Api-Admin-Username']) ? $params['Local-Api-Admin-Username'] : ''); + //$ExchangeCurrency = (isset($params['ExchangeCurrency']) ? $params['ExchangeCurrency'] : ''); + //--------- + // Create DokuPayment Instance + //--------- + $DokuConfigs = array( + 'isofile' => 'dokuhosted/assets/iso3166.json', + 'merchant' => array( + 'mallid' => $MallId, + 'shopname' => $ShopName, + 'chainmerchant' => $ChainMerchant, + 'sharedkey' => $SharedKey, + ), + 'endpoint' => (is_string($Environment) ? strtolower($Environment) : 'sandbox'), // sandbox as default + ); + ## + # DokuPayment Instance + ## + $DokuPayment = new dokusubscription_DokuPayment($DokuConfigs); + $rawdata['params'] = $params; + //----------------------------------------------------- + // Invoice Parameters + $invoiceId = $params['invoiceid']; + $description = $params["description"]; + $amount = $params['amount']; + $currencyCode = $params['currency']; + // Client Parameters + $firstname = $params['clientdetails']['firstname']; + $lastname = $params['clientdetails']['lastname']; + $fullname = $params['clientdetails']['fullname']; + $email = $params['clientdetails']['email']; + $address1 = $params['clientdetails']['address1']; + $address2 = $params['clientdetails']['address2']; + $city = $params['clientdetails']['city']; + $state = $params['clientdetails']['state']; + $postcode = $params['clientdetails']['postcode']; + $country = $params['clientdetails']['country']; + $phone = $params['clientdetails']['phonenumber']; + // System Parameters + $companyName = $params['companyname']; + $systemUrl = $params['systemurl']; + $returnUrl = $params['returnurl']; + $langPayNow = $params['langpaynow']; + $moduleDisplayName = $params['name']; + $moduleName = $params['paymentmethod']; + $whmcsVersion = $params['whmcsVersion']; + // Tokenized Creditcard Parameters + $cc_number = (isset($params['cardnum']) ? $params['cardnum'] : ''); + $cc_exp = array( + 'month' => (isset($params['cardexp']) ? substr($params['cardexp'], 0, 2) : ''), + 'year' => (isset($params['cardexp']) ? substr($params['cardexp'], 2, 2) : ''), + ); + $cc_cvv = (isset($params['cccvv']) ? $params['cccvv'] : ''); + $cc_type = (isset($params['cardtype']) ? $params['cardtype'] : ''); + $cc_lastfour = (isset($params['cardlastfour']) ? $params['cardlastfour'] : ''); + $cc_cardnum = (isset($params['cardnum']) ? $params['cardnum'] : ''); + # URL Of Payment-Request + //--------------------------------------------------- + $DateObject = $DokuPayment->get_datetime_object("Asia/Bangkok"); + // Create input to DokuPayment Instance + $params_input = array( + 'transaction_id' => "{$DateObject->format('YmdHis')}{$params['invoiceid']}", // Create unique request_id + 'transaction_currency' => strtoupper(substr($params['currency'], 0, 2)), + 'transaction_datetime' => $DateObject->format('YmdHis'), + 'transaction_session' => (isset($params['clientdetails']['uuid']) ? $params['clientdetails']['uuid'] : ''), + 'amount_total' => 0, + ); + $params_input['transaction_session'] = md5($params_input['transaction_session']); + $params_input['transaction_customerid'] = (isset($params['clientdetails']['userid']) ? $params['clientdetails']['userid'] : ''); + $params_input['transaction_billnumber'] = $params_input['transaction_id']; + # Temporary for fees items, nex from $logsync['item_lists'] + ########################################################### + $params_input['items'] = Array(); + $item_invoices = array( + 'item_id' => (isset($params['invoicenum']) ? $params['invoicenum'] : 1), + 'order_price' => (isset($params['amount']) ? $params['amount'] : 0), + 'order_unit' => 1, + 'order_item_name' => $params['description'], + ); + array_push($params_input['items'], $item_invoices); + foreach ($params_input['items'] as $val) { + $params_input['amount_total'] += ($val['order_price'] * $val['order_unit']); + } + $user_input = array( + 'name' => $params['clientdetails']['fullname'], // Should be an user input tmn account + 'email' => $params['clientdetails']['email'], // Should be an user input tmn email or myarena email + 'shipping_address' => array( // Input or generate randomly or API to MyArena Account? + 'forename' => $params['clientdetails']['lastname'], + 'surname' => $params['clientdetails']['firstname'], + 'fullname' => $params['clientdetails']['fullname'], + 'email' => $params['clientdetails']['email'], + 'phone' => $params['clientdetails']['phonenumber'], + 'SHIPPING_ADDRESS' => '', + 'SHIPPING_CITY' => $params['clientdetails']['city'], + 'SHIPPING_STATE' => $params['clientdetails']['state'], + 'SHIPPING_COUNTRY' => $params['clientdetails']['country'], + 'SHIPPING_ZIPCODE' => $params['clientdetails']['postcode'], + 'ADDITIONALDATA' => $params['description'], + ), + ); + $user_input['shipping_address']['SHIPPING_ADDRESS'] .= (isset($params['clientdetails']['address1']) ? $params['clientdetails']['address1'] : ''); + $user_input['shipping_address']['SHIPPING_ADDRESS'] .= (isset($params['clientdetails']['address2']) ? ((strlen($params['clientdetails']['address2']) > 0) ? " {$params['clientdetails']['address2']}" : '') : ''); + $user_input['tokenization'] = array( + 'CUSTOMERID' => $params['clientdetails']['userid'], + 'TOKENID' => (isset($params['token']) ? $params['token'] : $cc_number), + ); + $user_input['credit_card'] = array( + 'CARDNUMBER' => $cc_number, + 'EXPIRYDATE' => "{$cc_exp['year']}{$cc_exp['month']}", + 'CVV2' => $cc_cvv, + 'CC_NAME' => $user_input['name'], + ); + //---------------------------- + // Get Invoices Data + //---------------------------- + $OrderData = FALSE; + $InvoiceData = FALSE; + if (isset($localApi['data']['id'])) { + unset($localApi['data']['id']); + } + #if ((__METHOD__) == 'dokusubscription_capture') { + $localApi['command'] = 'GetOrders'; + $localApi['data']['invoiceid'] = (isset($params['invoiceid']) ? $params['invoiceid'] : ''); + $OrdersData = localAPI($localApi['command'], $localApi['data'], $localApi['username']); + if (isset($OrdersData['orders']['order'])) { + if (count($OrdersData['orders']['order']) > 0) { + foreach ($OrdersData['orders']['order'] as $keval) { + if (isset($keval['invoiceid'])) { + if ((int)$keval['invoiceid'] === (int)$localApi['data']['invoiceid']) { + $OrderData = $keval; + } + } + } + } + } + if (!$error) { + if (!$OrderData) { + $error = true; + $error_msg[] = "No Invoice data from localApi: " . (__METHOD__); + } + } + #} + $localApi['command'] = 'GetInvoice'; + $localApi['data']['invoiceid'] = (isset($params['invoiceid']) ? $params['invoiceid'] : ''); + $InvoiceData = localAPI($localApi['command'], $localApi['data'], $localApi['username']); + $Invoice_BillDetail = ""; + if (isset($InvoiceData['items']['item'])) { + if (count($InvoiceData['items']['item']) > 0) { + foreach ($InvoiceData['items']['item'] as $keval) { + $Invoice_BillDetail .= (isset($keval['description']) ? $keval['description'] : ''); + } + } + } + + /* + if (!$error) { + $retDebug = "
";
+		$retDebug .= print_r($InvoiceData, true);
+		return $retDebug;
+	}
+	*/
+	
+	$Invoice_BillCycle = 0;
+	if (!$error) {
+		if (isset($OrderData['lineitems']['lineitem'][0]['billingcycle'])) {
+			switch (strtolower($OrderData['lineitems']['lineitem'][0]['billingcycle'])) {
+				case 'monthly':
+					$Invoice_BillCycle = 1;
+				break;
+				case 'quarterly':
+					$Invoice_BillCycle = 3;
+				break;
+				case 'semi-annually':
+					$Invoice_BillCycle = 6;
+				break;
+				case 'annually':
+					$Invoice_BillCycle = 12;
+				break;
+				case 'biennially':
+					$Invoice_BillCycle = 24;
+				break;
+				case 'triennially':
+					$Invoice_BillCycle = 36;
+				break;
+			}
+		}
+	}
+	if (!$error) {
+		$params_input['subscription'] = array(
+			'CUSTOMERID'			=> (isset($InvoiceData['userid']) ? $InvoiceData['userid'] : ''),
+			'BILLNUMBER'			=> '', // Generate later
+			'BILLDETAIL'			=> substr($Invoice_BillDetail, 0, 256),
+			'BILLTYPE'				=> 'S', // Shopping as default
+			'STARTDATE'				=> (isset($InvoiceData['date']) ? $InvoiceData['date'] : ''),
+			'ENDDATE'				=> (isset($InvoiceData['enddate']) ? $InvoiceData['enddate'] : 'NA'),
+			'EXECUTETYPE'			=> 'DATE', // DAY / DATE / FULLDATE
+			'EXECUTEDATE'			=> '',
+			'EXECUTEMONTH'			=> '',
+			'FLATSTATUS'			=> '',
+			'REGISTERAMOUNT'		=> '',
+		);
+		#### Create Date Time Object ####
+		//DateTime::createFromFormat('Y-m-d', date('Y-m-d'));
+		$DateObject = $DokuPayment->get_datetime_object("Asia/Bangkok");
+		$params_input['subscription']['BILLNUMBER'] = $DateObject->format('YmdHi');
+		$params_input['subscription']['BILLNUMBER'] .= (isset($InvoiceData['invoiceid']) ? $InvoiceData['invoiceid'] : '');
+		$params_input['subscription']['STARTDATE'] = DateTime::createFromFormat('Y-m-d', $params_input['subscription']['STARTDATE']);
+		$params_input['subscription']['STARTDATE'] = $params_input['subscription']['STARTDATE']->format('Ymd');
+		// Make ENDDATE
+		$DateSubscribe = DateTime::createFromFormat('Y-m-d', date('Y-m-d'));
+		switch ($Invoice_BillCycle) {
+			case 1:
+				$DateSubscribe->add(new DateInterval('P1M'));
+			break;
+			case 3:
+				$DateSubscribe->add(new DateInterval('P3M'));
+			break;
+			case 6:
+				$DateSubscribe->add(new DateInterval('P6M'));
+			break;
+			case 12:
+				$DateSubscribe->add(new DateInterval('P12M'));
+			break;
+			case 24:
+				$DateSubscribe->add(new DateInterval('P2Y'));
+			break;
+			case 36:
+				$DateSubscribe->add(new DateInterval('P3Y'));
+				//$DateSubscribe->add(new DateInterval('P3Y0M0DT0H0M0S'));
+			break;
+		}
+		$params_input['subscription']['ENDDATE'] = $DateSubscribe->format('Ymd');
+	}
+	$Invoice_BillCycle_Months = array();
+	if (!$error) {
+		// Make lists of EXECUTEMONTH
+		if ($Invoice_BillCycle > 0) {
+			switch ($Invoice_BillCycle) {
+				case 1:
+				case 3:
+				case 6:
+				case 12:
+					for ($i_bill = 0; $i_bill <= $Invoice_BillCycle; $i_bill++) {
+						$DateSubscribeMonths = new DateTime(date('Y-m-d'));
+						$DateSubscribeMonths->add(new DateInterval("P{$i_bill}M"));
+						$Invoice_BillCycle_Months[] = $DateSubscribeMonths->format('M');
+					}
+				break;
+				case 24:
+				case 36:
+					for ($i_bill = 0; $i_bill <= 12; $i_bill++) {
+						$DateSubscribeMonths = DateTime::createFromFormat('Y-m-d', date('Y-m-d'));
+						$DateSubscribeMonths->add(new DateInterval("P{$i_bill}M"));
+						$Invoice_BillCycle_Months[] = $DateSubscribeMonths->format('M');
+					}
+				break;
+			}
+		}
+		//$params_input['subscription']['EXECUTEMONTH'] = $DateObject->format('M');
+		//$params_input['subscription']['EXECUTEMONTH'] = strtoupper($params_input['subscription']['EXECUTEMONTH']);
+		$params_input['subscription']['EXECUTEMONTH'] = implode(",", $Invoice_BillCycle_Months);
+	}
+	if (!$error) {
+		// filter BILLDETAIL String
+		$params_input['subscription']['BILLDETAIL'] = filter_var($params_input['subscription']['BILLDETAIL'], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH);
+		$params_input['subscription']['BILLDETAIL'] = preg_replace("/[^a-zA-Z0-9]+/", "", $params_input['subscription']['BILLDETAIL']);
+		$params_input['subscription']['BILLDETAIL'] = str_replace('(', '', $params_input['subscription']['BILLDETAIL']);
+		$params_input['subscription']['BILLDETAIL'] = str_replace(')', '', $params_input['subscription']['BILLDETAIL']);
+		$params_input['subscription']['BILLDETAIL'] = str_replace('#', '', $params_input['subscription']['BILLDETAIL']);
+		switch (strtoupper($params_input['subscription']['EXECUTETYPE'])) {
+			case 'DAY':
+				$params_input['subscription']['EXECUTEDATE'] = strtoupper($DateObject->format('D'));
+			break;
+			case 'DATE':
+				$params_input['subscription']['EXECUTEDATE'] = $DateObject->format('j');
+				if ((int)$params_input['subscription']['EXECUTEDATE'] > 28) {
+					$params_input['subscription']['EXECUTEDATE'] = '28';
+				}
+			break;
+			case 'FULLDATE':
+				$params_input['subscription']['EXECUTEDATE'] = $DateObject->format('Ymd');
+			break;
+		}
+				
+		$params_input['subscription']['FLATSTATUS'] = 'TRUE'; // Static (Fix) Value
+		$params_input['subscription']['REGISTERAMOUNT'] = sprintf('%.2f', $InvoiceData['total']);
+	}
+	//-------------------------------------------------------
+	if (!$error) {
+		/*
+		echo "
";
+		if ($OrderData) {
+			echo "
"; + print_r($OrderData); + } + if ($InvoiceData) { + echo "
"; + print_r($InvoiceData); + } + exit; + */ + + # Create Subscription Payment Structure + $createPaymentStructure = $DokuPayment->create_payment_structure('subscription', 0, $params_input, $user_input, $params_input['items'], $user_input['shipping_address']); + $PaymentStructure = array( + 'words_sha1' => (isset($createPaymentStructure['WORDS']) ? $createPaymentStructure['WORDS'] : ""), + 'words_string' => (isset($createPaymentStructure['WORDS_STRING']) ? $createPaymentStructure['WORDS_STRING'] : ""), + 'session_id' => (isset($createPaymentStructure['SESSIONID']) ? $createPaymentStructure['SESSIONID'] : ""), + ); + // Generate Unique SESSIONID Every single payment + $PaymentStructure['session_id'] = sha1("{$PaymentStructure['session_id']}{$DokuPayment->generate_transaction_id()}"); + if ((isset($createPaymentStructure['WORDS_STRING'])) && (isset($createPaymentStructure['SESSIONID']))) { + unset($createPaymentStructure['WORDS_STRING']); + $PaymentStructureJson = json_encode($createPaymentStructure, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT); + // do any log .... + $makepayment_data = json_decode($PaymentStructureJson, true, 512, JSON_BIGINT_AS_STRING); + ksort($makepayment_data); + if ($Log_Enabled) { + logTransaction($moduleName, $makepayment_data, "(WHMCS) REQUEST-PAYMENT"); + } + $rawdata['payment_form'] = $makepayment_data; + //-------------------------------------------------------------------------------------------------------------- + if (isset($rawdata['payment_form']['TOKENID'])) { + unset($rawdata['payment_form']['TOKENID']); + } + if (isset($rawdata['payment_form']['PAYMENTTYPE'])) { + unset($rawdata['payment_form']['PAYMENTTYPE']); + } + //-------------------------------------------------------------------------------------------------------------- + $rawdata['payment_input'] = http_build_query($rawdata['payment_form']); + // CURL AND SAVE LOG + $headers = $DokuPayment->create_curl_headers($DokuPayment->dokupayment_headers); + //$curlData = $DokuPayment->create_curl_request('POST', $DokuPayment->endpoint['request'], 'WHMCS Payment Plugin (http://www.doku.com)', $headers, $rawdata['payment_form'], 30); + //logTransaction($moduleName, $curlData, "(WHMCS) SUBSCRIPTION-REQUEST"); + $htmlForm .= "

doku-checkout

"; + $htmlForm .= '
'; + if (count($rawdata['payment_form']) > 0) { + foreach ($rawdata['payment_form'] as $key => $val) { + //$htmlForm .= "{$key}:
"; + $htmlForm .= ""; + } + } + $htmlForm .= '
'; + // Js submit form + $htmlFormSubmit .= ''; + //------------------------------------------ + /* + $htmlFormSubmit .= ''; + */ + } + } + if (!$error) { + $htmlReturn = "{$htmlForm}{$htmlFormSubmit}"; + return $htmlReturn; + } else { + //$htmlReturn = print_r($error_msg, true); + return false; + } + + /* + if (!$error) { + echo $htmlForm; + echo $htmlFormSubmit; + + + + } + exit; + + if (!$error) { + + + + + + + $htmlForm .= '
'; + if (count($rawdata['payment_form']) > 0) { + foreach ($rawdata['payment_form'] as $key => $val) { + //$htmlForm .= "{$key}: "; + $htmlForm .= ""; + $htmlForm .= "
"; + } + } + $htmlForm .= '
'; + + $htmlFormSubmit .= ''; + + + + echo "
";
+			print_r($params);
+				
+			if ($InvoiceData) {
+				echo "
"; + print_r($InvoiceData); + } + + exit; + + + + + + + echo $htmlForm; + echo $htmlFormSubmit; + exit; + + + } + */ + //$curlData = curlCall($DokuPayment->endpoint['request'], $makepayment_data); + //$tokenize = array( + // "status" => "error", + // "rawdata" => $rawdata + //); + + // + //$tokenize = array( + // 'status' => 'success', + // 'transid' => "{$params['invoiceid']}_{$DokuPayment->generate_transaction_id()}", + // 'rawdata' => $rawdata, + //); + // + //return $tokenize; +} +function dokusubscription_nolocalcc($params) { + return true; +} + + + + + + + + + + + + + + + + + +/** + * Refund transaction. + * + * Called when a refund is requested for a previously successful transaction. + * + * @param array $params Payment Gateway Module Parameters + * + * @see https://developers.whmcs.com/payment-gateways/refunds/ + * + * @return array Transaction response status + */ +function dokusubscription_refund($params) { + // Gateway Configuration Parameters + $accountId = $params['accountID']; + $secretKey = $params['secretKey']; + $testMode = $params['testMode']; + $dropdownField = $params['dropdownField']; + $radioField = $params['radioField']; + $textareaField = $params['textareaField']; + + // Transaction Parameters + $transactionIdToRefund = $params['transid']; + $refundAmount = $params['amount']; + $currencyCode = $params['currency']; + + // Client Parameters + $firstname = $params['clientdetails']['firstname']; + $lastname = $params['clientdetails']['lastname']; + $email = $params['clientdetails']['email']; + $address1 = $params['clientdetails']['address1']; + $address2 = $params['clientdetails']['address2']; + $city = $params['clientdetails']['city']; + $state = $params['clientdetails']['state']; + $postcode = $params['clientdetails']['postcode']; + $country = $params['clientdetails']['country']; + $phone = $params['clientdetails']['phonenumber']; + + // System Parameters + $companyName = $params['companyname']; + $systemUrl = $params['systemurl']; + $langPayNow = $params['langpaynow']; + $moduleDisplayName = $params['name']; + $moduleName = $params['paymentmethod']; + $whmcsVersion = $params['whmcsVersion']; + + // perform API call to initiate refund and interpret result + + return array( + // 'success' if successful, otherwise 'declined', 'error' for failure + 'status' => 'success', + // Data to be recorded in the gateway log - can be a string or array + 'rawdata' => $responseData, + // Unique Transaction ID for the refund transaction + 'transid' => $refundTransactionId, + // Optional fee amount for the fee value refunded + 'fees' => $feeAmount, + ); +} + +/** + * Cancel subscription. + * + * If the payment gateway creates subscriptions and stores the subscription + * ID in tblhosting.subscriptionid, this function is called upon cancellation + * or request by an admin user. + * + * @param array $params Payment Gateway Module Parameters + * + * @see https://developers.whmcs.com/payment-gateways/subscription-management/ + * + * @return array Transaction response status + */ +function dokusubscription_cancelSubscription($params) { + // Gateway Configuration Parameters + $accountId = $params['accountID']; + $secretKey = $params['secretKey']; + $testMode = $params['testMode']; + $dropdownField = $params['dropdownField']; + $radioField = $params['radioField']; + $textareaField = $params['textareaField']; + + // Subscription Parameters + $subscriptionIdToCancel = $params['subscriptionID']; + + // System Parameters + $companyName = $params['companyname']; + $systemUrl = $params['systemurl']; + $langPayNow = $params['langpaynow']; + $moduleDisplayName = $params['name']; + $moduleName = $params['paymentmethod']; + $whmcsVersion = $params['whmcsVersion']; + + // perform API call to cancel subscription and interpret result + + return array( + // 'success' if successful, any other value for failure + 'status' => 'success', + // Data to be recorded in the gateway log - can be a string or array + 'rawdata' => $responseData, + ); +} + + +if (!defined("WHMCS")) { + die("This file cannot be accessed directly"); +} + +