Redirection to a page for new customers without an active product WHMCS - hook

Good morning,
I made a hook to try to redirect new customers and those who no longer have an active product among product group 1 :
add_hook('ClientAreaPage', 1, function($vars) {
if ($_SERVER['REQUEST_URI'] === '/store/adhesion') {
return;
}
if (isset($_SESSION['uid']) && $_SESSION['uid']) {
$client_id = $_SESSION['uid'];
$result = localAPI('GetClientsProducts', array('clientid' => $client_id, 'status' => 'Active'), '');
if ($result['result'] == 'success') {
$products = $result['products'];
$has_active_product = false;
foreach ($products as $product) {
if ($product['gid'] == 1 && $product['status'] == 'Active') {
$has_active_product = true;
break;
}
}
if (!$has_active_product) {
header('Location: /store/adhesion');
exit;
}
}
}
});
With this, the customer is always redirected to the page /store/adhesion even if he has an active product,
I check documentation, this is my first hook and I can't figure out where the problem is.
Can you help me ?
Thank you so much

Related

Calculate the sum of a specific array data

After calling all the data from my database, I would like to try and calculate the individual values of my array. I have made 2 users state as "banned"
//get all banned status for all users
res.data.data.forEach((dataItem, index) => {
console.log(`Banned ${index}`, dataItem.banned);
I would like to try and get the sum of "banned" and "not banned" which in this case is "banned 2" and "NotBanned 2"
tried this but dint work
for (const dataItem of res.data.data) {
let NotBanned = 0;
if(dataItem.banned === false){
NotBanned++;
console.log("Not Banned", NotBanned);
}
}
for (const dataItem of res.data.data) {
var BannedUsers = 0;
if(dataItem.banned === true){
BannedUsers++;
console.log("Not Banned",BannedUsers);
}
}
let
bannedUsers = 0,
unBannedUsers = 0;
const response = res.data.data
for(let users = 0; users < response.length; users ++ ) {
if(!response.banned) {
unBannedUsers += users;
}
else {
bannedUsers += users;
}
}
console.log(`Banned Users : ${bannedUsers} , UnBanned Users : ${unBannedUsers}` )

How to focus first invalid ngx-formly field

I am using ngx-formly for creating dynamic form from field configuration. On submitting form, validation is showed correctly. I want to focus first invalid formly field.
A little late to the party here but I was able to implement a solution that returned the user to the first instance of an invalid input using getElementById:
var errorField = null;
fields.forEach(field => {
for (var key in field.formControl["controls"]) {
let control = field.formControl["controls"][key];
if (control instanceof FormControl && control.status === "INVALID") {
errorField = control["_fields"][0]["_elementRefs"][0].nativeElement.id;
break;
}
else if (control instanceof FormGroup) {
for (var subKey in control.controls) {
let subControl = control.controls[subKey];
if (subControl.status === "INVALID") {
errorField = subControl["_fields"][0]["_elementRefs"][0].nativeElement.id;
break;
}
}
}
if (errorField) break;
}
});
let el = document.getElementById(errorField);
el.scrollIntoView({
behavior: 'smooth',
block: "center"
});

Stripe ach payment getway without plaid get account number and routing number of bank

i am trying to use ACH stripe getaway without palid third party to get manually account number ,routing number ,account holder name nd account type stripe.js/v3 create bank token i use this token create customer and then create charge all thing is done but when we test using stripe testng account num and reuting number this give me fatal error "this account cannot create payment"
this is my onclick button function that create abnk token
function test1(){
var one_coach = $('input.checkbox-coaches').is(':checked');
if(one_coach == false){
alert('Please Choose at least one coach');
return false;
}
var one_athlete = $('input.checkbox-athletes').is(':checked');
if(one_athlete == false){
alert('Please Choose at least one athlete');
return false;
}
//create single-use token to charge the use
var stripe = Stripe('pk_test_UM0qUCRVFnrem3uAIGtWcPiJ');
//create single-use token to charge the use
stripe.createToken('bank_account', {
country: 'US',
currency: 'usd',
routing_number: $('#routing_number').val(),
account_number: $('#account_number').val(),
account_holder_name: $('#account_holder_name').val(),
account_holder_type: $('#account_holder_type').val(),
}).then(function(result) {
//console.log(result);
if (result.error) {
//enable the submit button
$('#payBtn').removeAttr("disabled");
//display the errors on the form
// $('#payment-errors').attr('hidden', 'false');
$('#payment-errors').addClass('alert alert-danger');
$("#payment-errors").html(result.error.message);
} else {
var form$ = $("#order_form");
//get token id
var token_ach = result.token.id;
var bank_account_id=result.token.bank_account.id;
//alert(token_ach);
//insert the token into the form
form$.append("<input type='hidden' id='bank_account' name='bank_account' value='" + bank_account_id + "' />");
form$.append("<input type='hidden' id='stripeToken' name='stripeToken' value='" + token_ach + "' />");
//submit form to the server
// form$.get(0).submit();
function ach(){
var charges = $( "#service_charges" ).text();
var formdata=$('#order_form').serialize()+ '&charges=' + charges;
$('#ach_button').attr('disabled','disabled').attr('value','Ordering...');
$.ajax({
type : 'POST',
url : 'register/ach',
data : formdata,
beforeSend: function() {
$("#loader").show();
},
success:
function(data){
$('#results').removeClass('hide');
var result = JSON.parse(data);
if(result.error == 100)
{
$("#loader").hide();
$('#alert_msg').addClass('alert-error');
$('#results h4').text('On snap!');
$('#results p').text(result.msg);
$('#place_order').removeClass('disabled').attr('value','Place Order').removeAttr('disabled');
}
else
{
$("#loader").hide();
$('#alert_msg').removeClass('alert-error').addClass('alert-success');
$('#results h4').text('Congratulations!');
$('#results p').html(result.msg + '<br/>An email confirmation has been sent to you. You can visit the My Account area to view your invoice.');
return false;
}
return false;
}
});
}
// $('#stripeToken').val(token);
}
});
// var token = $('#stripeToken').val();
// alert(token); return;
// //submit from callback
// process_order(token);
}
php code that get all data
public function ach()
{
$post = array_2_obj($this->input->post());
if(!empty($post->stripeToken))
{
$contact_id = $this->club->infusion_contact_id;
$post->event = $this->events_model->get('events',array('id' => $post->event_id));
$attending = $this->get_attending_details($post->event_id,$this->input->post('athletes'));
//echo "<pre>";print_r($attending);
$teams = $this->get_team_comps($post->event_id,$attending);
// echo "<pre>";print_r($teams);
$this->session->unset_userdata("register_{$post->event_id}");
/**
* Check if Order has already been created by Session register_{event_id} Create Blank Order inside Infusionsoft
*/
if(!isset($this->session->userdata["register_{$post->event_id}"])):
$invoice_id = $this->infusion->create_order($contact_id,$post,$attending,$teams);
$this->session->set_userdata("register_{$post->event_id}",$invoice_id);
else :
$invoice_id = $this->session->userdata["register_{$post->event_id}"];
endif;
/**
* Charge Invoice
*/
// $merchant_id = $this->db_model->get_setting_value('merchant_id');
/**
* Unset the Invoice Id
*/
//$this->session->unset_userdata("register_{$post->event_id}");
//print_r($post); exit;
// echo "<pre>";print_r($_POST);
//get token, card and user info from the form
$bank_a_token = $post->stripeToken;
$account_holder_name = $post->account_holder_name;
// $email = $_POST['email'];
$routing_number = $post->routing_number;
$account_number =$post->account_number;
// $bank_account_id=$post->bank_account;
//include Stripe PHP library
require_once APPPATH."third_party/stripe/init.php";
//set api key
$stripe = array(
"secret_key" => "sk_test_HfRFUzMnvuq1rY1CfBZZUgKv",
"publishable_key" => "pk_test_UM0qUCRVFnrem3uAIGtWcPiJ"
);
\Stripe\Stripe::setApiKey($stripe['secret_key']);
$create_customer=\Stripe\Customer::create(array(
"source" => $bank_a_token,
"description" => $account_holder_name
));
//print_r($create_customer); exit;
$customer_id=$create_customer->id;
$source=$create_customer->default_source;
//get the existing bank account
$customer = \Stripe\Customer::retrieve($customer_id);
$bank_account = $customer->sources->retrieve($source);
// verify the account
$bank_account->verify(array('amounts' => array(32, 45)));
//print_r($bank_account); exit;
$label="";
$price=0;
$teamprice=0;
$teamlable="";
//item information
foreach ($attending as $product) {
$label.=$product->label.",";
$price=($product->total)+$price;
}
if (!empty($teams)) {
foreach ($teams as $tprice) {
$teamlable.=$tprice->label.",";
$teamprice=$tprice->team_price;
}
}
$charges=$post->charges;
$new_price=$price+$teamprice+$charges;
$itemName = $label;
$itemNumber = $post->event->product_id;
$itemPrice = $new_price*100;
$currency = "usd";
$orderID = $post->event->action_set_id;
//print_r($customer);
try {
$charge = \Stripe\Charge::create(array(
"amount" => $itemPrice,
"currency" => $currency,
"customer" => $customer_id // Previously stored, then retrieved
));
} catch(\Stripe\Error\Card $e) {
// Since it's a decline, \Stripe\Error\Card will be caught
$body = $e->getJsonBody();
$err = $body['error'];
print('Status is:' . $e->getHttpStatus() . "\n");
print('Type is:' . $err['type'] . "\n");
print('Code is:' . $err['code'] . "\n");
// param is '' in this case
print('Param is:' . $err['param'] . "\n");
print('Message is:' . $err['message'] . "\n");
} catch (\Stripe\Error\RateLimit $e) {
// Too many requests made to the API too quickly
} catch (\Stripe\Error\InvalidRequest $e) {
$msg = array('error' => 100,'msg' => "this account cannot create payment ");
echo json_encode($msg);
exit;
// Invalid parameters were supplied to Stripe's API
} catch (\Stripe\Error\Authentication $e) {
// Authentication with Stripe's API failed
// (maybe you changed API keys recently)
} catch (\Stripe\Error\ApiConnection $e) {
// Network communication with Stripe failed
} catch (\Stripe\Error\Base $e) {
// Display a very generic error to the user, and maybe send
// yourself an email
} catch (Exception $e) {
$msg = array('error' => 0,'msg' => "this account cannot create payment ");
echo json_encode($msg);
exit;
// Something else happened, completely unrelated to Stripe
}
//retrieve charge details
$chargeJson = $charge->jsonSerialize();
//check whether the charge is successful
if($chargeJson['amount_refunded'] == 0 && $chargeJson['paid'] == 1 && $chargeJson['captured'] == 1)
{
//order details
$amount = $chargeJson['amount'];
$balance_transaction = $chargeJson['balance_transaction'];
$currency = $chargeJson['currency'];
$status = $chargeJson['status'];
$date = date("Y-m-d H:i:s");
//insert tansaction data into the database
$data = new stdClass();
$data->attending_details = $attending;
$data->post = $post;
$data->teams = $teams;
$data->club = new stdClass();
$data->club = $this->club;
$data->bank = new stdClass();
$data->bank->last4 = substr($post->account_number,-4);
$data->bank->account_holder_type = $post->account_holder_type;
$data->bank->account_number = $post->account_number;
$data->bank->routing_number = $post->routing_number;
// $data->card->stripeToken=$post->stripeToken;
unset($data->post->account_number);
unset($data->post->routing_number);
/**
* Add Coaches and Athlete Data so it does not get deleted
*/
$data->coaches = array();
foreach($data->post->coaches as $coach_id):
if($coach_id > 0):
$data->coaches[] = $this->coaches_model->get(array('id' => $coach_id));
endif;
endforeach;
$data->athletes = array();
foreach($data->post->athletes as $athlete_id):
if($athlete_id > 0):
$data->athletes[] = $this->athletes_model->get(array('id' => $athlete_id));
endif;
endforeach;
//Insert Data into Database
$order_data = $this->db_model->add_order($this->club->id,$invoice_id,$data->post->event_id,$data);
$pdf_base64 = execute_curl(base_url() . 'invoice/base/' . $order_data->key,array(),TRUE);
// if(strlen($pdf_base64) > 10 ):
// $file_name = $data->post->event->name . ' - ' . $data->club->club . ' Invoice.pdf';
// $this->infusion->uploadFile($file_name,$pdf_base64,$contact_id);
// endif;
// //Update Invoice Key and then send email
// $this->infusion->updateCon($contact_id,array('_InvoiceKey' => $order_data->key));
// $this->infusion->sendTemplate(array($contact_id),$this->db_model->get_setting_value('invoice_email_template'));
// $this->infusion->sendTemplate(array($contact_id),$this->db_model->get_setting_value('admin_notification_email_template'));
// $global_action_set = $this->db_model->get_setting_value('all_events_action_set_id');
// if(isset($global_action_set) && $global_action_set > 0):
// $this->infusion->runAS($contact_id,$global_action_set);
// endif;
}
// $msg = array('error' => 0,'msg' => "You have successfully registered your club for " . $data->post->event->name. ' Event');
$msg = array('error' => 0,'msg' => "You have successfully registered your club for " . "$chargeforach->". ' Event');
echo json_encode($msg);
exit;
}
else
{
$msg = array('error' => 100,'msg' => "Invalid TOken");
echo json_encode($msg);
exit;
}
}
Are you based in US?
Currently according to the documents. It only supports ACH charges in the US
https://stripe.com/docs/ach

Show only one partial view among many in ajax success method

Here is my controler action method......from that action i want to return a partial view which is conditionaly true....and show this partial view in ajax success method....
public ActionResul InsertPestType (PestTypeViewModel model)
{
if (ModelState.IsValid == true)
{
pest_type emp = new pest_type();
ViewBag.emp = db.pest_type.SingleOrDefault(x => x.pest_type_name
== model.pest_type_name && x.isdeleted == false);
if (ViewBag.emp != null)
{
emp = ViewBag.emp;
}
if (emp.pest_type_name == model.pest_type_name)
{
ViewBag.Message = "This Pest Type is already exist in the
record";
return PartialView("Insert_PestType", model);
}
else
{
emp.pest_type_name = model.pest_type_name;
emp.isdeleted = false;
db.pest_type.Add(emp);
db.SaveChanges();
List<pest_type> model1 = db.pest_type.Where(x => x.isdeleted
== false).ToList();
ViewBag.pesttypelist = model1;
return PartialView("pest_type_partial", model);
}
}
else
return PartialView("inex_partial", model);
}
Below is my ajax success method.......here i want to show only one partial view which is true ocording to the condition...........Now my question is that how can i differentiate between two partial views in ajax success method??
var success=function(response)
{
if ()
{
$("#RegisterPestTypeModel").modal('hide')
$("#dvCategoryResults").html(response.AjaxReturn)
}
else
{
$("#PestTypeModalBody").html(response)
}

Get parent Id on checked unchecked event in aciTree

I want to ask a question that how can i get the parent id of child node in aciTree. If uservchecked the child node then i want to save its id with its parent id.
Any help in this regard will be highly appreciated.
I have gone through aciTree documentation http://acoderinsights.ro/source/aciTree/documentation.html# but didn't found any method to get the parent id on child selection.
if (eventName == 'checked') {
if (bankUsers.indexOf(api.getId(item)) == -1) {
if (api.getId(item) == -2 || api.getId(item) - 3) {
bankUsers = new Array();
bankUsers[0] = api.getId(item);
} else {
bankUsers.push(api.getId(item));
}
}
} else if (eventName == 'unchecked') {
if (bankUsers.indexOf(api.getId(item)) != -1) {
if (api.getId(item) == -2 || api.getId(item) - 3) {
bankUsers = new Array();
} else {
bankUsers.splice(bankUsers.indexOf(api.getId(item)), 1);
}
}
}
you can use this function :
var parentID = api.itemData(api.parent(item)).id;
as simple as this.
if .id give undefiend you can use the following:
var parentID = api.getId(api.parent(item));

Resources