I have a function for Paypal redirection for that I pass some values in params..
It only pass the Description field doesn't shows the amount to be paid,and rest of my order summaries..
Here is my function
public function postPayment()
{
$hot_id = \Session::get('hot_id');
$user_id = \Session::get('uid');
$check_in = \Session::get('check_in');
$check_out = \Session::get('check_out');
$mem_count = \Session::get('mem_count');
$rm_no = \Session::get('rm_no');
$check_in = strtotime($check_in);
$check_in = date('Y-m-d',$check_in);
$check_out = strtotime($check_out);
$check_out = date('Y-m-d',$check_out);
$datediff = strtotime($check_out) - strtotime($check_in);
$diff = floor($datediff/(86400));
$room_prize = \DB::select("SELECT `room_prize` FROM `abserve_hotel_rooms` WHERE `room_id` = ".$_POST['room_id']);
$arr = array();
foreach ($room_prize as $key => $value) {
$arr[]= (get_object_vars($value));
}
$room_prize = array();
foreach ($arr as $key => $value) {
$room_prize[]=($value['room_prize']);
}
if($rm_no == 1)
{
$room_prize = (int) $room_prize[0] * (int) $diff;
}
else
{
$room_prize = (int) $room_prize[0] * (int) $diff * (int) $rm_no;
}
$room_prize = number_format((float)$room_prize, 2, '.', '');
$room_id = $_POST['room_id'];
$today = new DateTime();
$created_at = $today->format('Y-m-d');
$values = array('user_id' => $user_id,'hotel_id' => $hot_id,'room_id'=>$room_id,'room_prize'=>$room_prize,'check_in'=>$check_in,'check_out'=>$check_out,'created_at'=>$created_at);
\DB::table('abserve_orders')->insert($values);
$order_id = DB::select("SELECT `id` FROM `abserve_orders` WHERE `room_id` = ".$_POST['room_id']." AND `user_id` = ".$user_id);
$arr = array();
foreach ($order_id as $key => $value) {
$arr[]= (get_object_vars($value));
}
$order_id = array();
foreach ($arr as $key => $value) {
$order_id[]=($value['id']);
}
$order_id = $order_id[0];
$params = array(
'cancelUrl' => url().'/cancel_order',
'returnUrl' => url().'/payment_success',
'name' => 'new order',
'description' => 'description1',
'amount' => $room_prize,
'currency' => 'USD',
'hot_id' => $hot_id,
'room_id' => $room_id,
'user_id' => $user_id,
'check_in' => $check_in,
'check_out' => $check_out,
'order_id' => $order_id,
'nights' => $diff,
);
// print_r($params);exit;
\Session::put('params', $params);
\Session::save();
$gateway = Omnipay::create('PayPal_Express');
$gateway->setUsername('googley555_api1.yahoo.com');
$gateway->setPassword('3EQ6S6PB68A52JKZ');
$gateway->setSignature('AFcWxV21C7fd0v3bYYYRCpSSRl31AHaEiWOLAf5jQQ3-A9hLlhypSz9h');
$gateway->setTestMode(true);
$response = $gateway->purchase($params)->send();
if ($response->isSuccessful()) {
// payment was successful: update database
print_r($response);
} elseif ($response->isRedirect()) {
// redirect to offsite payment gateway
$response->redirect();
} else {
// payment failed: display message to customer
echo $response->getMessage();
}
}
I don't know what are missing in it..
Someone please help me..
You can't pass in arbitrary parameters such as hot_id, room_id, etc to PayPal (or omnipay) because it won't know what to do with them. PayPal is only intended to take certain parameters and the ones that PayPal does not take are ignored by Omnipay.
You may have to provide all of these extra parameters as part of the description parameter, which PayPal does understand.
Ideally these should be displayed by your application in some kind of useful format to the user before redirecting the user to the PayPal checkout page.
Related
In my Laravel project, I've got a job set up which runs and attempts to notify a user based on their threshold and chosen alert metrics. I'm using the php end() method to get the last item in an array and then attempting to get whatever metric the user has chosen.
However, upon dumping the data, this isn't returning the last array item, it's returning every item and I'm not sure why?
When I dump my data, I'm getting this format instead of the last item in the array:
[2021-04-13 13:30:45] production.DEBUG: array (
0 =>
(object) array(
'event_category' => 'My Category',
'event_action' => 'My Event',
'event_count' => '2190',
'period_from' => '2021-04-13 00:00:00',
'period_to' => '2021-04-13 13:30:02',
'created_at' => '2021-04-13 13:30:06',
),
1 =>
(object) array(
'event_category' => 'My Category',
'event_action' => 'My Event',
'event_count' => '5184',
'period_from' => '2021-04-12 00:00:00',
'period_to' => '2021-04-12 23:57:02',
'created_at' => '2021-04-12 23:57:07',
),
2 =>
(object) array(
'event_category' => 'My Category',
'event_action' => 'My Event',
'event_count' => '3820',
'period_from' => '2021-04-11 00:00:00',
'period_to' => '2021-04-11 23:57:02',
'created_at' => '2021-04-11 23:57:07',
),
)
I should just be seeing the last item, amongst all of my code, the following is of significant value here:
/**
* Notify if data meets threshold & alert rules
*
* #return void
*/
public function notifyAlertThreshold($alerts, $data)
{
$newestDataPart = end($data) ?? null;
// alerts for data source
foreach ($alerts as $key => $alert) {
Log::debug($newestDataPart);
$metric = !isset($newestDataPart->{$alert->metric}) ? $newestDataPart : $newestDataPart->{$alert->metric};
}
}
In context, here's some mode of the code, but the primary question here, is why is my end() method not returning the last item?
/**
* Execute the job.
*
* #return void
*/
public function handle()
{
$filters = json_decode($this->report->discovery_filters, true);
$this->reportStatus = 'complete';
$data = [];
foreach ($filters as $findableKey => $findable) {
/*
** If there are datasets on the findable objec, then we assume
** that we can build up a chart or some data structure.
*/
if (isset($findable['datasets'])) {
$pushableDatasets = [];
foreach ($findable['datasets'] as $datasetKey => $dataset) {
// query data
if (isset($dataset['query'])) {
$chartLabel = $findable['name'] ?? 'Untitled Chart';
$this->setDynamicChartOptions($chartLabel);
$additionFromField = $dataset['query']['additionFromField'] ?? '';
$resultData = [];
if ($dataset['query']['prefersConversionCalculation'] == 'yes') {
$totals = DB::table($dataset['query']['table'])
->select($dataset['query']['columns'])
->where($dataset['query']['calculateConversionFromTotals'])
->orderBy($dataset['query']['orderBy']['field'], $dataset['query']['orderBy']['direction'])
->get()
->chunk(100);
$goal = DB::table($dataset['query']['table'])
->select($dataset['query']['columns'])
->where($dataset['query']['calculateConversionByGoal'])
->orderBy($dataset['query']['orderBy']['field'], $dataset['query']['orderBy']['direction'])
->get()
->chunk(100);
$totals = $totals->flatten();
$goal = $goal->flatten();
$totalsGrouped = $this->groupData(
$totals,
$dataset['query']['groupBy'],
$dataset['query']['groupByFormat'],
$additionFromField
);
$goalsGrouped = $this->groupData(
$goal,
$dataset['query']['groupBy'],
$dataset['query']['groupByFormat'],
$additionFromField
);
$totalsGroupedFlattened = $totalsGrouped->flatten();
$goalsGroupedFlattened = $goalsGrouped->flatten();
$resultData = $this->getStructure($findable, $datasetKey, $goalsGroupedFlattened, $totalsGroupedFlattened);
array_push($pushableDatasets, $resultData);
} else {
$res = DB::table($dataset['query']['table'])
->select($dataset['query']['columns'])
->where($dataset['query']['filterBy'])
->orderBy($dataset['query']['orderBy']['field'], $dataset['query']['orderBy']['direction'])
->get()
->chunk(100);
$res = $res->flatten();
if (isset($dataset['query']['useGrouping']) && $dataset['query']['useGrouping'] == 'yes') {
$results = $this->groupData(
$res,
$dataset['query']['groupBy'],
$dataset['query']['groupByFormat'],
$additionFromField
);
// if we're using an addition function our array is already flattened
if (!empty($additionFromField)) {
$resultData = $results;
} else {
$resultData = $results->flatten();
}
array_push($pushableDatasets, $this->getStructure($findable, $datasetKey, $resultData));
}
}
$dataForAlerts = $resultData;
if ($dataset['query']['prefersConversionCalculation'] == 'yes') {
$dataForAlerts = $dataForAlerts['data'];
}
// alerting
$alerts = $this->getAlertThresholds($dataset['query']['table']);
$this->notifyAlertThreshold($alerts, $dataForAlerts);
}
}
$findable['datasets'] = $pushableDatasets;
}
array_push($data, $findable);
}
// no data or it's empty
if (!isset($data) || empty($data)) {
$this->reportStatus = 'error';
}
// create our report data entry
$this->updateReportData(false, $data);
}
i am using express checkout with this package :
https://github.com/srmklive/laravel-paypal
exactly as example repository one change i made is that the price and item info was hard coded but i passed a model to that function called event because i want to sell events . so it looks like below now :
protected function getCheckoutData($recurring = false,$event = null)
{
$data = [];
$order_id = Invoice::all()->count() + 1;
if ($recurring === true) {
$data['items'] = [
[
'name' => 'Monthly Subscription '.config('paypal.invoice_prefix').' #'.$order_id,
'price' => 12222,
'qty' => 1,
],
];
$data['return_url'] = url('/paypal/ec-checkout-success?mode=recurring');
$data['subscription_desc'] = 'Monthly Subscription '.config('paypal.invoice_prefix').' #'.$order_id;
} else {
$data['items'] = [
[
'name' => $event->title,
'price' => $event->price,
'qty' => 1,
'event_id' => $event->id,
]
];
$data['return_url'] = url('/paypal/ec-checkout-success');
}
$data['invoice_id'] = config('paypal.invoice_prefix').'_'.$order_id;
$data['invoice_description'] = $event->title;
$data['cancel_url'] = url('/');
$total = 0;
foreach ($data['items'] as $item) {
$total += $item['price'] * $item['qty'];
}
$data['total'] = $total;
return $data;
}
now on getExpressCheckoutSuccess function after payment it calls the getCheckoutData again but this time there is no model event on that like below :
public function getExpressCheckoutSuccess(Request $request)
{
$recurring = ($request->get('mode') === 'recurring') ? true : false;
$token = $request->get('token');
$PayerID = $request->get('PayerID');
$cart = $this->getCheckoutData($recurring);
// Verify Express Checkout Token
$response = $this->provider->getExpressCheckoutDetails($token);
.
.
.
so my question is that how can pass the paypal my event id and it returns that to me again or do some thing to detect the event
and pass it to getCheckoutData and verify the payment . thanks in advance
now i'm trying to get the value from another form. But i don't know how to make it.
This is my first form:
and this is method, when we click submit in the the form1, the page will redirect to this method.
public function input_data_inserted()
{
$id_data_inserted = $this->input->post('id_data_inserted');
$date = $this->input->post('date');
$id_data = $this->input->post('id_data');
$amount= $this->input->post('amount');
$id_room = $this->input->post('id_room');
$passed = FALSE;
$checkIdData = $this->modelku->cek_idData()->result_array();
$checkIdRoom = $this->modelku->cek_idRoom()->result_array();
foreach ($cekIdData as $cID)
{
foreach ($cekIdRoom as $cIR)
{
if ($id_data == $cID['id_data'] && $id_room == $cIR['id_room'])
{
$data = array
(
'id_data_inserted' => $id_data_inserted,
'date' => $date,
'id_data' => $cID['id_data'],
'amount' => $amount,
'id_room' => $cIR['id_room'],
);
$this->modelku->input_data($data, 'table_data_inserted');
$data['table_data_inserted'] = $this->modelku->show_data('table_data_inserted')->result();
$this->modelku->increase_value($amount, $id_data);
//redirect to second form
redirect('admin/Data/data\view_detail_data');
$passed = TRUE;
break;
}
}
}
if(!$passed)
{
echo "ERORR";
}
}
And this is my second form:
Method for second form:
public function input_detail_barang()
{
$id_data = $this->input->post('id_data');
$no_inv = $this->input->post('no_inv');
$condition = $this->input->post('condition');
$data = array
(
'id_data' => $id_data,
'no_inv' => $no_inv,
'condition' => $condition
);
//I need amount from first form, because i will use it. How can i do?
}
Any Solution? Thx
After this line you can save it to session:
$data = array (
'id_data_inserted' => $id_data_inserted,
'date' => $date,
'id_data' => $cID['id_data'],
'amount' => $amount,
'id_room' => $cIR['id_room'], // You missed single quote here
);
$this->load->library('session');
$this->session->set_userdata("Firstformdata",$data);
And for show this data add this line:
$this->session->userdata("Firstformdata");
I am trying to check if a coupon is still valid (hasn't reached its usage limit) and display content under this condition.
The reason for this is that I want to be able to hand out a coupon code to particular visitors, but obviously don't want to hand out a coupon that has already reached it's usage limit.
I am trying to achieve this with PHP and imagine the code to be something like this:
<?php if (coupon('mycouponcode') isvalid) {
echo "Coupon Valid"
} else {
echo "Coupon Usage Limit Reached"
} ?>
Any help here would be great :)
I believe the recommended way encouraged by WooCommerce is to use the \WC_Discounts Class. Here is an example:
function is_coupon_valid( $coupon_code ) {
$coupon = new \WC_Coupon( $coupon_code );
$discounts = new \WC_Discounts( WC()->cart );
$response = $discounts->is_coupon_valid( $coupon );
return is_wp_error( $response ) ? false : true;
}
Note: It's also possible to initialize the WC_Discounts class with a WC_Order object as well.
It's important to remember doing that inside the wp_loaded hook at least, like this:
add_action( 'wp_loaded', function(){
is_coupon_valid('my-coupon-code');
});
There is an apparent simpler method is_valid() from the WC_Coupon class but it was deprecated in favor of WC_Discounts->is_coupon_valid()
$coupon = new WC_Coupon( 'my-coupon-code' );
$coupon->is_valid();
$code = 'test123';
$coupon = new WC_Coupon($code);
$coupon_post = get_post($coupon->id);
$coupon_data = array(
'id' => $coupon->id,
'code' => $coupon->code,
'type' => $coupon->type,
'created_at' => $coupon_post->post_date_gmt,
'updated_at' => $coupon_post->post_modified_gmt,
'amount' => wc_format_decimal($coupon->coupon_amount, 2),
'individual_use' => ( 'yes' === $coupon->individual_use ),
'product_ids' => array_map('absint', (array) $coupon->product_ids),
'exclude_product_ids' => array_map('absint', (array) $coupon->exclude_product_ids),
'usage_limit' => (!empty($coupon->usage_limit) ) ? $coupon->usage_limit : null,
'usage_count' => (int) $coupon->usage_count,
'expiry_date' => (!empty($coupon->expiry_date) ) ? date('Y-m-d', $coupon->expiry_date) : null,
'enable_free_shipping' => $coupon->enable_free_shipping(),
'product_category_ids' => array_map('absint', (array) $coupon->product_categories),
'exclude_product_category_ids' => array_map('absint', (array) $coupon->exclude_product_categories),
'exclude_sale_items' => $coupon->exclude_sale_items(),
'minimum_amount' => wc_format_decimal($coupon->minimum_amount, 2),
'maximum_amount' => wc_format_decimal($coupon->maximum_amount, 2),
'customer_emails' => $coupon->customer_email,
'description' => $coupon_post->post_excerpt,
);
$usage_left = $coupon_data['usage_limit'] - $coupon_data['usage_count'];
if ($usage_left > 0) {
echo 'Coupon Valid';
}
else {
echo 'Coupon Usage Limit Reached';
}
The code is tested and fully functional.
Reference
WC_API_Coupons::get_coupon( $id, $fields )
add_action( 'rest_api_init', 'coupon' );
function coupon($request) {
register_rest_route('custom-plugin', '/coupon_code/',
array(
'methods' => 'POST',
'callback' => 'coupon_code',
)
);
}
function coupon_code($request)
{
$code = $request->get_param('coupon');
$applied_coupon = $request->get_param('applied_coupon');
$cart_amount = $request->get_param('cart_amount');
$user_id = $request->get_param('user_id');
// $code = 'test123';
$coupon = new WC_Coupon($code);
$coupon_post = get_post($coupon->id);
$coupon_data = array(
'id' => $coupon->id,
'code' => esc_attr($coupon_post->post_title),
'type' => $coupon->type,
'created_at' => $coupon_post->post_date_gmt,
'updated_at' => $coupon_post->post_modified_gmt,
'amount' => wc_format_decimal($coupon->coupon_amount, 2),
'individual_use' => ( 'yes' === $coupon->individual_use ),
'product_ids' => array_map('absint', (array) $coupon->product_ids),
'exclude_product_ids' => array_map('absint', (array) $coupon->exclude_product_ids),
'usage_limit' => (!empty($coupon->usage_limit) ) ? $coupon->usage_limit : null,
'usage_count' => (int) $coupon->usage_count,
'expiry_date' => (!empty($coupon->expiry_date) ) ? date('Y-m-d', $coupon->expiry_date) : null,
'enable_free_shipping' => $coupon->enable_free_shipping(),
'product_category_ids' => array_map('absint', (array) $coupon->product_categories),
'exclude_product_category_ids' => array_map('absint', (array) $coupon->exclude_product_categories),
'exclude_sale_items' => $coupon->exclude_sale_items(),
'minimum_amount' => wc_format_decimal($coupon->minimum_amount, 2),
'maximum_amount' => wc_format_decimal($coupon->maximum_amount, 2),
'customer_emails' => $coupon->customer_email,
'description' => $coupon_post->post_excerpt,
);
if ($coupon_data['code'] != $code) {
$response['status'] = "failed";
$response['message'] = "COUPON ".$code." DOES NOT EXIST!";
return new WP_REST_Response($response);
}
$Acoupon = new WC_Coupon($applied_coupon);
// print_r($Acoupon);exit();
if($Acoupon->individual_use == 'yes'){
$response['status'] = "failed";
$response['message'] = "SORRY, COUPON ".$applied_coupon." HAS ALREADY BEEN APPLIED AND CANNOT BE USED IN CONJUNCTION WITH OTHER COUPONS.";
$response['result'] = $Acoupon->individual_use;
return new WP_REST_Response($response);
}
if ($coupon_data['minimum_amount'] > $cart_amount) {
$response['status'] = "failed";
$response['message'] = "THE MINIMUM SPEND FOR THIS COUPON IS $".$coupon_data['minimum_amount'].".";
return new WP_REST_Response($response);
}
if ($coupon_data['maximum_amount'] < $cart_amount) {
$response['status'] = "failed";
$response['message'] = "THE MAXIMUM SPEND FOR THIS COUPON IS $".$coupon_data['maximum_amount'].".";
return new WP_REST_Response($response);
}
if ($coupon_data['exclude_sale_items'] == true) {
$response['status'] = "failed";
$response['message'] = "SORRY, THIS COUPON IS NOT VALID FOR SALE ITEMS.";
return new WP_REST_Response($response);
}
$usage_left = $coupon_data['usage_limit'] - $coupon_data['usage_count'];
if ($usage_left == 0) {
$response['status'] = "failed";
$response['message'] = "SORRY, COUPON USAGE LIMIT HAS BEEN REACHED.";
return new WP_REST_Response($response);
}
$current_time = date('Y-m-d');
$coupon_Expiry_date = $coupon->expiry_date;
if ($coupon_Expiry_date < $current_time) {
$response['status'] = "failed";
$response['message'] = "THIS COUPON HAS EXPIRED.";
return new WP_REST_Response($response);
}
$user_limite = get_post_meta($coupon_data['id'], 'usage_limit_per_user', true);
$p_id = $coupon_data['id'];
global $wpdb;
$count_of_per_user = $wpdb->get_results("SELECT * FROM wp_postmeta where post_id = $p_id and meta_key = '_used_by' and meta_value = $user_id");
$count = count($count_of_per_user);
if ( $count >= $user_limite) {
$response['status'] = "failed"`enter code here`;
$response['message'] = "COUPON USAGE LIMIT HAS BEEN REACHED.";
return new WP_REST_Response($response);
}enter code here
else{
$response['status'] = "Success";
$response['message'] = "COUPON APPLIED.";
return new WP_REST_Response($response);
}
}
use this function
How to increase the performance of following function in phalcon framework. There are thousands of records in the table. I tried different ways, but I am stuck the point. How can I increase the efficiency and reduce the execution time. Following are two methods:
public function currentmonthAction()
{
$payload = $this->request->getJsonRawBody();
$this->setDB();
$ticketsmodel = new Tickets();
$fromcitycondition = "";
if( isset($payload->city->id) )
{
$fromcitycondition = "and fromcity='{$payload->city->id}'";
}
try{
$date = new \Datetime($payload->date);
$year = $date->format('Y');
$month = $date->format('m');
$month = '08';
$daysInMonth = cal_days_in_month(CAL_GREGORIAN, $month, $year);
/* result for all cities passenger */
$result = array();
// get all cities permutations
$tmpcitiesdata = array();
$rawresultset = Tickets::find (
array(
'columns' => 'fromcity,tocity',
'conditions' => "departure between '{$year}-{$month}-01' and '{$year}-{$month}-$daysInMonth' and tickettype in (1) ". $fromcitycondition,
'group' => 'fromcity,tocity'
));
foreach ($rawresultset as $rawresult) {
$tmpcitiesdata[$rawresult->fromcity.'-'.$rawresult->tocity]['fromcity'] = $rawresult->fromcity;
$tmpcitiesdata[$rawresult->fromcity.'-'.$rawresult->tocity]['tocity'] = $rawresult->tocity;
}
//var_dump($rawresultset);
// get tickets sold based on cities combinations
$total = 0;
foreach ($tmpcitiesdata as $tmpcities) {
$rawresultset = Tickets::find (
array(
'columns' => 'customer',
'conditions' => "departure between '{$year}-{$month}-01' and '{$year}-{$month}-$daysInMonth' and tickettype in (1) and fromcity=". $tmpcities['fromcity']." and tocity=".$tmpcities['tocity'],
'group' => 'customer'
));
$totalsoldRaw = count($rawresultset);
// get ticket cancellations
$rawresultset = Tickets::find (
array(
'conditions' => "departure between '{$year}-{$month}-01' and '{$year}-{$month}-$daysInMonth' and tickettype in (3) and fromcity=". $tmpcities['fromcity']." and tocity=".$tmpcities['tocity']
));
//make sure cancellations are tickets cancellations not booking cancellations
foreach($rawresultset as $rawresult)
{
$resultNumber = Tickets::find("departure='$rawresult->departure' and seatno={$rawresult->seatno} and id < {$rawresult->id} and tickettype = 1" );
if( count($resultNumber) > 0 ){
$totalsoldRaw = $totalsoldRaw-1;
}
}
$total += $totalsoldRaw;
array_push($result, array('total' => $totalsoldRaw, 'fromcity' => Cities::findFirstById($tmpcities['fromcity'])->name, 'tocity' => Cities::findFirstById($tmpcities['tocity'])->name));
}
//sort result based on counts
arsort($result);
//cut result to max 6 cities
$result = array_slice($result, 0, 6);
$this->response->setContentType('application/json')
->setJsonContent(
array( 'totaltickets' => $total, "allcities" => $result )
);
$this->response->send();
return;
}
catch(\PDOException $e)
{
$this->response->setStatusCode('422','Invalid Payload');
$this->response->setContentType('application/json')
->setJsonContent(array(
'flash' => array(
'class' => 'danger',
'message' => $e->getMessage()
)
));
$this->response->send();
return;
}
}
Use count instead of count(result of find). Also are you sure in // get ticket cancellations you don't need group ? Then you can select all tickets for customers in 1,3 tickettype and then filter resultset.
Also can't your first $rawresulset can't be:
$rawresultset = Tickets::find (
array(
'columns' => 'customer,fromcity,tocity,tickettype ',
'conditions' => "departure between '{$year}-{$month}-01' and '{$year}-{$month}-$daysInMonth' and tickettype in (1,3)".$fromcitycondition
'group' => 'customer,fromcity,tocity'
));
?
$ticketCanccelations = $rawresultset->filter(function($row){
if($row->tickettype == 3) {
return $row;
}
});
$resultNumber = Tickets::count("departure='$rawresult->departure' and seatno={$rawresult->seatno} and id < {$rawresult->id} and tickettype = 1" );