Skip to content

Commit

Permalink
Merge pull request #11 from xendit/TPI-6897/whmcs-implement-php-code-…
Browse files Browse the repository at this point in the history
…sniffer-on-buddy

Re-format the source code using php codeSniffer
  • Loading branch information
andykim authored Apr 20, 2022
2 parents bb327af + 83f0bf2 commit 8e74371
Show file tree
Hide file tree
Showing 12 changed files with 135 additions and 115 deletions.
11 changes: 3 additions & 8 deletions modules/gateways/callback/xendit.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
$payMethodId = isset($_REQUEST['custom_reference']) ? (int)$_REQUEST['custom_reference'] : 0;

// validate hash
if ($creditCard->compareHash($params, $verificationHash)) {
if ($creditCard->compareHash($verificationHash, $params)) {
logTransaction($gatewayParams['paymentmethod'], $_REQUEST, "Invalid Hash");
die('Invalid hash.');
}
Expand All @@ -60,7 +60,6 @@
);
exit;
} catch (Exception $e) {

// Log to gateway log as unsuccessful.
logTransaction($gatewayParams['paymentmethod'], $_REQUEST, $e->getMessage());

Expand Down Expand Up @@ -89,18 +88,14 @@
} else {
// use for callback
$arrRequestInput = json_decode(file_get_contents("php://input"), true);
if (
!empty($arrRequestInput)
&& isset($arrRequestInput['external_id'])
&& !empty($arrRequestInput['external_id'])
) {
if (!empty($arrRequestInput) && isset($arrRequestInput['external_id']) && !empty($arrRequestInput['external_id'])) {
$invoiceId = $callback->getInvoiceIdFromExternalId($arrRequestInput['external_id']);
$transactions = $callback->getTransactionFromInvoiceId($invoiceId);

try {
// Get invoice from Xendit
$xenditInvoice = $xenditRequest->getInvoiceById($arrRequestInput['id']);
if(isset($arrRequestInput['credit_card_token'])){
if (isset($arrRequestInput['credit_card_token'])) {
$xenditInvoice['credit_card_token'] = $arrRequestInput['credit_card_token'];
}
$result = $callback->confirmInvoice(
Expand Down
31 changes: 15 additions & 16 deletions modules/gateways/xendit.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,14 +45,14 @@ function xendit_config()
*/
function xendit_deactivate()
{
try{
try {
(new \Xendit\Lib\Migrate())->removeTransactionTable();
return [
// Supported values here include: success, error or info
'status' => 'success',
'description' => 'Drop Xendit data success.'
];
}catch (\Exception $e){
} catch (\Exception $e) {
return [
// Supported values here include: success, error or info
"status" => "error",
Expand Down Expand Up @@ -126,7 +126,6 @@ function xendit_capture($params)
}

if (!empty($response) && isset($response['status']) && $response['status'] == "CAPTURED") {

// Save transaction status
$xenditRecurring = new Recurring();
$transactions = $xenditRecurring->getTransactionFromInvoiceId($params["invoiceid"]);
Expand Down Expand Up @@ -258,7 +257,7 @@ function xendit_remoteinput($params)
*/
function xendit_remoteupdate($params)
{
if (strpos($_REQUEST["rp"], "/admin/") !== FALSE) {
if (strpos($_REQUEST["rp"], "/admin/") !== false) {
return <<<HTML
<div class="alert alert-info text-center">
Updating your card/bank is not possible. Please create a new Pay Method to make changes.
Expand Down Expand Up @@ -354,9 +353,9 @@ function xendit_adminstatusmsg($params)
*
* @param array $params Payment Gateway Module Parameters
*
* @return array Transaction response status
* @see https://developers.whmcs.com/payment-gateways/refunds/
*
* @return array Transaction response status
*/
function xendit_refund($params)
{
Expand All @@ -369,32 +368,32 @@ function xendit_refund($params)

// perform API call to initiate refund and interpret result
$xenditRequest = new \Xendit\Lib\XenditRequest();
try{
try {
$invoiceResponse = $xenditRequest->getInvoiceById($transactionIdToRefund);
$chargeId = $invoiceResponse['credit_card_charge_id'];
}catch (Exception $e){
if(str_contains($e->getMessage(), "INVOICE_NOT_FOUND_ERROR")){
} catch (Exception $e) {
if (str_contains($e->getMessage(), "INVOICE_NOT_FOUND_ERROR")) {
// The invoice created via CLI & chargeID saved to transaction
$chargeId = $transactionIdToRefund;
}
}

if(empty($chargeId)) {
if (empty($chargeId)) {
return array(
'status' => 'error',
'rawdata' => 'Can not refund the payment because because it is not credit card transaction'
'status' => 'error',
'rawdata' => 'Can not refund the payment because because it is not credit card transaction'
);
}

$body = array(
'store_name' => $companyName,
'external_id' => 'whmcs-refund-' . uniqid(),
'amount' => $refundAmount
'store_name' => $companyName,
'external_id' => 'whmcs-refund-' . uniqid(),
'amount' => $refundAmount
);

try{
try {
$refundResponse = $xenditRequest->createRefund($chargeId, $body);
}catch (Exception $e){
} catch (Exception $e) {
return array(
'status' => 'declined',
'rawdata' => $e->getMessage(),
Expand Down
35 changes: 12 additions & 23 deletions modules/gateways/xendit/assets/js/xendit.js
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ jQuery(function ($) {
},

block: function () {
if(cc_xendit_form.btnSaveCC.find('.loading-icon').length == 0){
if (cc_xendit_form.btnSaveCC.find('.loading-icon').length == 0) {
cc_xendit_form.btnSaveCC.append('<div class="loading-icon spinner-border spinner-border-sm" role="status"></div>');
}
cc_xendit_form.btnSaveCC.prop('disabled', true);
Expand All @@ -111,20 +111,8 @@ jQuery(function ($) {
return true;
},

toggleInputError: function (erred, input) {
input.parent('.form-group').toggleClass('has-error', erred);
return input;
},

extractMonth: function (date) {
var expiryArray = date.split("/");
return String(expiryArray[0]).length === 1 ? '0' + String(expiryArray[0]) : String(expiryArray[0]);
},

extractYear: function (date) {
var expiryArray = date.split("/");
var fullYear = new Date().getFullYear();
return String(String(fullYear).substr(0, 2) + expiryArray[1]);
extractMonth: function (month) {
return month.toString().length < 2 ? '0' + month.toString() : month.toString();
},

onSubmit: function (e) {
Expand All @@ -140,7 +128,7 @@ jQuery(function ($) {
success: function (response) {
if (!response.error) {
var message = cc_xendit_form.isAddNewCC() ? "Payment method added successfully" : "Payment method updated successfully"
cc_xendit_form.form.append('<p class="message text-success">'+message+'</p>')
cc_xendit_form.form.append('<p class="message text-success">' + message + '</p>')
} else {
cc_xendit_form.form.append('<p class="message text-danger">' + response.message + '</p>')
}
Expand All @@ -154,7 +142,8 @@ jQuery(function ($) {

var card = cc_xendit_form.inputCardNumber.val().replace(/\s/g, '');
var cvn = cc_xendit_form.inputCardCVV.val().replace(/ /g, '');
var expiry = cc_xendit_form.inputCardExpiry.val().replace(/ /g, '');
var card_type = $.payment.cardType(card);
var expiry = cc_xendit_form.inputCardExpiry.payment('cardExpiryVal');

// check if all card details are not empty
if (!card || !cvn || !expiry) {
Expand All @@ -173,23 +162,23 @@ jQuery(function ($) {
}

// validate card number
if (!Xendit.card.validateCardNumber(card)) {
if (!$.payment.validateCardNumber(card)) {
var err = {
message: 'Incorrect number'
}
return cc_xendit_form.handleError(err);
}

// validate expiry format MM/YY
if (expiry.length != 5) {
if (!$.payment.validateCardExpiry(expiry.month, expiry.year)) {
var err = {
message: 'Invalid expire'
}
return cc_xendit_form.handleError(err);
}

// validate cvc
if (cvn.length < 3) {
if (!$.payment.validateCardCVC(cvn, card_type)) {
var err = {
message: 'Invalid cvn'
}
Expand All @@ -198,8 +187,8 @@ jQuery(function ($) {

var data = {
"card_number": card,
"card_exp_month": cc_xendit_form.extractMonth(expiry),
"card_exp_year": cc_xendit_form.extractYear(expiry),
"card_exp_month": cc_xendit_form.extractMonth(expiry.month),
"card_exp_year": expiry.year.toString(),
"card_cvn": cvn,
"is_multiple_use": true,
"on_behalf_of": "",
Expand Down Expand Up @@ -288,7 +277,7 @@ jQuery(function ($) {
return 'unknown';
},

backToPaymentMethod: function (e){
backToPaymentMethod: function (e) {
parent.location.href = cc_xendit_form.btnCancel.data("href");
}
};
Expand Down
11 changes: 5 additions & 6 deletions modules/gateways/xendit/autoload.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,17 @@

spl_autoload_register(function ($className) {
if (strpos($className, 'Xendit') !== false) {

$classPath = explode("\\", $className);
unset($classPath[0]);

try{
$filePath = __DIR__ . DIRECTORY_SEPARATOR . implode("/", array_map(function ($path){
try {
$filePath = __DIR__ . DIRECTORY_SEPARATOR . implode("/", array_map(function ($path) {
return $path == "Lib" ? strtolower($path) : $path;
}, $classPath)) . ".php";
if(file_exists($filePath)){
}, $classPath)) . ".php";
if (file_exists($filePath)) {
require $filePath;
}
}catch (Exception $e){
} catch (Exception $e) {
}
}
});
6 changes: 3 additions & 3 deletions modules/gateways/xendit/handler/updatecc.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,17 +28,17 @@
$verificationHash = $_POST['verification_hash'] ?? '';

$comparisonHash = sha1(
implode('|', [
implode('|', [
$publicKey,
$customerId,
$invoiceId,
$amount,
$currencyCode,
$secretKey
])
])
);
if ($verificationHash !== $comparisonHash) {
die('Invalid hash.');
die('Invalid hash.');
}

if ($action === 'payment') {
Expand Down
20 changes: 18 additions & 2 deletions modules/gateways/xendit/hooks.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
<?php

use Xendit\Lib\ActionBase;
use Xendit\Lib\Recurring;

/**
Expand All @@ -8,8 +9,7 @@
* @param $vars
* @return void
*/
add_hook('InvoiceCreation', 1, function ($vars)
{
add_hook('InvoiceCreation', 1, function ($vars) {
$xenditRecurring = new Recurring();
$invoice = $xenditRecurring->getInvoice($vars['invoiceid']);

Expand All @@ -21,3 +21,19 @@
// Save xendit transaction
$xenditRecurring->storeTransactions($vars['invoiceid']);
});

/**
* Hook to show Xendit payment gateway based on currency
*
* @param $vars
* @return array|void
*/
add_hook("ClientAreaPageCart", 1, function ($vars) {
if ($vars['templatefile'] == 'viewcart') {
$activeCurrency = $vars['activeCurrency']->code;
if (!in_array($activeCurrency, ActionBase::ALLOW_CURRENCIES)) {
unset($vars['gateways']["xendit"]);
}
}
return $vars;
});
5 changes: 4 additions & 1 deletion modules/gateways/xendit/lib/ActionBase.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@

class ActionBase
{
const ALLOW_CURRENCIES = ['IDR', 'PHP', 'USD'];

protected $moduleDomain = 'xendit';
protected $xenditRequest;
protected $xenditTransaction;
Expand Down Expand Up @@ -239,7 +241,8 @@ public function confirmInvoice(int $invoiceId, array $xenditInvoiceData, bool $s
// Save payment method
$transactions = $this->getTransactionFromInvoiceId($invoiceId);
if (!empty($transactions)) {
$this->updateTransactions($transactions,
$this->updateTransactions(
$transactions,
[
"status" => XenditTransaction::STATUS_PAID,
"payment_method" => $xenditInvoiceData["payment_method"]
Expand Down
9 changes: 5 additions & 4 deletions modules/gateways/xendit/lib/CreditCard.php
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,9 @@ public function extractItems($invoice): array
public function generateCCPaymentRequest(array $params = [], int $auth_id = null, int $cvn = null): array
{
$invoice = $this->getInvoice($params["invoiceid"]);
if (empty($invoice))
if (empty($invoice)) {
throw new \Exception("Invoice does not exist");
}

$payload = [
"amount" => $params["amount"],
Expand Down Expand Up @@ -97,11 +98,11 @@ public function getCardSetting()
}

/**
* @param array $params
* @param string $verificationHash
* @return void
* @param array $params
* @return false|void
*/
public function compareHash(array $params = [], string $verificationHash)
public function compareHash(string $verificationHash, array $params = [])
{
$comparisonHash = sha1(
implode('|', [
Expand Down
11 changes: 5 additions & 6 deletions modules/gateways/xendit/lib/Link.php
Original file line number Diff line number Diff line change
Expand Up @@ -80,9 +80,9 @@ protected function invoiceUrl($invoiceId, string $systemurl): string
*/
protected function isRefererUrlFromCart(): bool
{
if(isset($_SERVER["HTTP_REFERER"]) && ltrim($_SERVER["SCRIPT_NAME"], "/") == "viewinvoice.php"){
if (isset($_SERVER["HTTP_REFERER"]) && ltrim($_SERVER["SCRIPT_NAME"], "/") == "viewinvoice.php") {
$uri = parse_url($_SERVER['HTTP_REFERER']);
if(ltrim($uri["path"], "/") == "cart.php"){
if (ltrim($uri["path"], "/") == "cart.php") {
return true;
}
}
Expand All @@ -94,10 +94,10 @@ protected function isRefererUrlFromCart(): bool
* @param string $invoiceUrl
* @return string
*/
protected function generateFormParam(array $params, string $invoiceUrl = "")
protected function generateFormParam(array $params, string $invoiceUrl)
{
if($this->isRefererUrlFromCart()){
header("Location: " . $invoiceUrl );
if ($this->isRefererUrlFromCart()) {
header("Location: " . $invoiceUrl);
exit();
}

Expand Down Expand Up @@ -149,7 +149,6 @@ public function generatePaymentLink(array $params, bool $force = false): string

// If force create new invoice
if ($force) {

$payload = $this->generateInvoicePayload($params, true);
$createInvoice = $this->xenditRequest->createInvoice($payload);
$url = $createInvoice['invoice_url'];
Expand Down
Loading

0 comments on commit 8e74371

Please sign in to comment.