WooCommerce: Check if coupon is valid - php

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

Related

How can i check all selected value quantity?

Can anyone help me? how can i check all the product selected on the select or in the option? i'm using codeigniter 3 and i want to check if there was an available stock or none but i'm new and don't know how to do it i wish someone can help me. first it was working if i select a product with 0 quantity it will not process but if i select a first product with a quantity on hand greater than 0 and selected the second one with empty qty it will still process because it only check the stocks of the first product. how can i check all the qty selected in my select option?
my model:
public function create()
{
$user_id = $this->session->userdata('id');
// get store id from user id
$user_data = $this->model_users->getUserData($user_id);
$bill_no = 'BUBBLE-'.strtoupper(substr(md5(uniqid(mt_rand(), true)), 0, 4));
$data = array(
'bill_no' => $bill_no,
'date_time' => strtotime(date('Y-m-d h:i:s a')),
'gross_amount' => $this->input->post('gross_amount_value'),
'service_charge_rate' => $this->input->post('service_charge_rate'),
'service_charge_amount' => ($this->input->post('service_charge_value') > 0) ?$this->input->post('service_charge_value'):0,
'vat_charge_rate' => $this->input->post('vat_charge_rate'),
'vat_charge_amount' => ($this->input->post('vat_charge_value') > 0) ? $this->input->post('vat_charge_value') : 0,
'net_amount' => $this->input->post('net_amount_value'),
'discount' => $this->input->post('discount_amount_value'),
'paid_status' => 3,
'user_id' => $user_id,
'table_id' => $this->input->post('table_name'),
'discount_id' => json_encode($this->input->post('discount')),
'discount_percent' => $this->input->post('discount_perct_value'),
'datetoday' => date('Y-m-d h:i:s a'),
'payment_id' => json_encode($this->input->post('payment')),
);
$count_product = count($this->input->post('product'));
for($x = 0; $x < $count_product; $x++) {
$prodid = $this->input->post('product')[$x];
$prod_quan = $this->model_products->getProductData($prodid);
$inputQuantity = (int)$this->input->post('qty')[$x];
$check = $this->model_orders->check_stock($prodid, $inputQuantity);
if($check == TRUE)
{
$insert = $this->db->insert('orders', $data);
$order_id = $this->db->insert_id();
$count_product = count($this->input->post('product'));
for($x = 0; $x < $count_product; $x++) {
$items = array(
'order_id' => $order_id,
'product_id' => $this->input->post('product')[$x],
'qty' => $this->input->post('qty')[$x],
'rate' => $this->input->post('rate_value')[$x],
'amount' => $this->input->post('amount_value')[$x],
);
$this->db->insert('order_items', $items);
}
$this->load->model('model_tables');
$this->model_tables->update($this->input->post('table_name'), array('available' => 2));
return ($order_id) ? $order_id : false;
}
else
{
return false;
}
}
}
public function check_stock($productId, $inputQuantity)
{
$product = $this->db->get_where('products', ['id' => $productId])->row();
if(isset($product))
{
if($product->qty < $inputQuantity)
{
$this->session->set_flashdata('error','No more stock on some selected items');
return false;
}
else
{
return true;
}
}
}
and my select in view is something like this:
<select class="form-control select_group update-select" data-row-id="row_1" id="product_1" name="product[]" style="width:100%;" onchange="getProductData(1)" required>
<option disabled selected hidden value=''>--Select Products--</option>
<?php foreach ($products as $k => $v): ?>
<option value="<?php echo $v['id'] ?>"><?php echo $v['name'] ?></option>
<?php endforeach ?>
</select>
Easiest solution is to return false as soon as you find a product that is out of stock, something like the following:
Loop through the selected products and for each one check the stock. If you encounter a product that is out of stock, return false.
If all products are in stock, create the order, then loop through the selected products again and add those to the order in the database.
I haven't tested the code below, so there may be errors. I only changed the if($check == TRUE) part and some curly braces.
public function create()
{
$user_id = $this->session->userdata('id');
// get store id from user id
$user_data = $this->model_users->getUserData($user_id);
$bill_no = 'BUBBLE-'.strtoupper(substr(md5(uniqid(mt_rand(), true)), 0, 4));
$data = array(
'bill_no' => $bill_no,
'date_time' => strtotime(date('Y-m-d h:i:s a')),
'gross_amount' => $this->input->post('gross_amount_value'),
'service_charge_rate' => $this->input->post('service_charge_rate'),
'service_charge_amount' => ($this->input->post('service_charge_value') > 0) ?$this->input->post('service_charge_value'):0,
'vat_charge_rate' => $this->input->post('vat_charge_rate'),
'vat_charge_amount' => ($this->input->post('vat_charge_value') > 0) ? $this->input->post('vat_charge_value') : 0,
'net_amount' => $this->input->post('net_amount_value'),
'discount' => $this->input->post('discount_amount_value'),
'paid_status' => 3,
'user_id' => $user_id,
'table_id' => $this->input->post('table_name'),
'discount_id' => json_encode($this->input->post('discount')),
'discount_percent' => $this->input->post('discount_perct_value'),
'datetoday' => date('Y-m-d h:i:s a'),
'payment_id' => json_encode($this->input->post('payment')),
);
$count_product = count($this->input->post('product'));
for($x = 0; $x < $count_product; $x++) {
$prodid = $this->input->post('product')[$x];
$prod_quan = $this->model_products->getProductData($prodid);
$inputQuantity = (int)$this->input->post('qty')[$x];
$check = $this->model_orders->check_stock($prodid, $inputQuantity);
if($check != TRUE)
{
return false;
}
}
$insert = $this->db->insert('orders', $data);
$order_id = $this->db->insert_id();
$count_product = count($this->input->post('product'));
for($x = 0; $x < $count_product; $x++) {
$items = array(
'order_id' => $order_id,
'product_id' => $this->input->post('product')[$x],
'qty' => $this->input->post('qty')[$x],
'rate' => $this->input->post('rate_value')[$x],
'amount' => $this->input->post('amount_value')[$x],
);
$this->db->insert('order_items', $items);
}
$this->load->model('model_tables');
$this->model_tables->update($this->input->post('table_name'), array('available' => 2));
return ($order_id) ? $order_id : false;
}

Parsing returns an empty value

I make a parser of items from DotA 2 user inventory in the Steam service. Every time I try to parse user data, I get an empty value:
{"success":true,"items":[]}, but there are items in my Steam inventory.
My function to parse items:
public function loadMyInventory() {
if(Auth::guest()) return ['success' => false];
$prices = json_decode(Storage::get('prices.txt'), true);
$response = json_decode(file_get_contents('https://steamcommunity.com/inventory/'.$this->user->steamid64.'/570/2?l=russian&count=5000'), true);
if(time() < (Session::get('InvUPD') + 5)) {
return [
'success' => false,
'msg' => 'Error, repeat in '.(Session::get('InvUPD') - time() + 5).' сек.',
'status' => 'error'
];
}
//return $response;
$inventory = [];
foreach($response['assets'] as $item) {
$find = 0;
foreach($response['descriptions'] as $descriptions) {
if($find == 0) {
if(($descriptions['classid'] == $item['classid']) && ($descriptions['instanceid'] == $item['instanceid'])) {
$find++;
# If we find the price of an item, then move on.
if(isset($prices[$descriptions['market_hash_name']])) {
# Search data
$price = $prices[$descriptions['market_hash_name']]*$this->config->curs;
$class = false;
$text = false;
if($price <= $this->config->min_dep_sum) {
$price = 0;
$text = 'Cheap';
$class = 'minPrice';
}
if(($descriptions['tradable'] == 0) || ($descriptions['marketable'] == 0)) {
$price = 0;
$class = 'minPrice';
$text = 'Not tradable';
}
# Adding to Array
$inventory[] = [
'name' => $descriptions['market_name'],
'price' => floor($price),
'color' => $this->getRarity($descriptions['tags']),
'tradable' => $descriptions['tradable'],
'class' => $class,
'text' => $text,
'classid' => $item['classid'],
'assetid' => $item['assetid'],
'instanceid' => $item['instanceid']
];
}
}
}
}
}
Session::put('InvUPD', (time() + 5));
return [
'success' => true,
'items' => $inventory
];
}
But should return approximately the following value:
{"success":true,"items":[{"classid":"2274725521","instanceid":"57949762","assetid":"18235196074","market_hash_name":"Full-Bore Bonanza","price":26}]}
Where my mistake?
First of all, you are iterating on descriptions for every assets, which is assets*descriptions iteration, it's quite a lot, but you can optimize this.
let's loop once for descriptions and assign classid and instanceid as object key.
$assets = $response["assets"];
$descriptions = $response["descriptions"];
$newDescriptions=[];
foreach($descriptions as $d){
$newDescriptions[$d["classid"]][$d["instanceid"]] = $d;
}
this will give as the ability to not loop over description each time, we can access the description of certain asset directly $newDescriptions[$classid][$instanceid]]
foreach($assets as $a){
if(isset($newDescriptions[$a["classid"]]) && isset($newDescriptions[$a["classid"]][$a["instanceid"]])){
$assetDescription = $newDescriptions[$a["classid"]][$a["instanceid"]];
$inventory = [];
if(isset($prices[$assetDescription["market_hash_name"]])){
$price = $prices[$assetDescription['market_hash_name']]["price"]*$this->config->curs;
$class = false;
$text = false;
if($price <= $this->config->min_dep_sum) {
$price = 0;
$text = 'Cheap';
$class = 'minPrice';
}
if(($assetDescription['tradable'] == 0) || ($assetDescription['marketable'] == 0)) {
$price = 0;
$class = 'minPrice';
$text = 'Not tradable';
}
$inventory["priceFound"][] = [
'name' => $assetDescription['market_name'],
'price' => floor($price),
'color' => $this->getRarity($assetDescription['tags']),
'tradable' => $assetDescription['tradable'],
'class' => $class,
'text' => $text,
'classid' => $a['classid'],
'assetid' => $a['assetid'],
'instanceid' => $a['instanceid']
];
}else{
$inventory["priceNotFound"][] = $assetDescription["market_hash_name"];
}
}
}
About your mistake:
are you Sure your "prices.txt" contains market_hash_name?
I don't see any other issue yet, operationg on the data you have provided in comment, I got print of variable $assetDescription. Please doublecheck variable $prices.

php Prestashop- where can I find the following functions

In a Prestashop Ecommerce website I have a module that was created specially to compare and set products price in my website,
I need some help understand some of his PHP code.
The followng code set the price of a product in my website after scanning and finding the minumum price in other website link providede at the product backend page:
My Question is: How does this code works? where is the part of the code that scan the other website and get the minumum price in it?
<?php
class ProductCMP extends Module
{
public function __construct()
{
$this->name = 'productcmp';
$this->tab = 'front_office_features';
$this->version = '1.0.0';
$this->author = 'biznesownia';
parent::__construct();
$this->displayName = $this->l('ProductCMP', FALSE, NULL);
}
public function install()
{
return parent::install()
and $this->registerHook('displayAdminProductsExtra')
and $this->registerHook('actionAdminProductsControllerSaveAfter');
}
public function hookDisplayAdminProductsExtra($params)
{
$product = new Product((int) Tools::getValue('id_product'), false);
$tpl = $this->context->smarty->createTemplate(dirname(__FILE__).'/templates/tab.tpl', $this->context->smarty);
$tpl->assign('product', $product);
return $tpl->fetch();
}
public function hookActionAdminProductsControllerSaveAfter($params)
{
# set data
$id_product = (int) Tools::getValue('id_product');
$product = new Product($id_product, false, (int) $this->context->language->id);
$product->compare_active = (bool) Tools::getValue('compare_active', false);
$product->compare_link = (string) Tools::getValue('compare_link', '');
$product->compare_price = (string) Tools::getValue('compare_price', 0);
return $product->save();
}
public function compare()
{
define('PRODUCT_COMPARE_EMAIL', 'uditools#gmail.com');
set_time_limit(60*60);
# get list
$products = Db::getInstance()->executeS("
SELECT p.`id_product`, pl.`name`
FROM `"._DB_PREFIX_."product` p
LEFT JOIN `"._DB_PREFIX_."product_lang` pl ON (p.`id_product` = pl.`id_product` ".Shop::addSqlRestrictionOnLang('pl').")
WHERE
pl.`id_lang` = ".(int)$this->context->language->id."
AND p.`compare_active`=1
ORDER BY p.`id_product`
");
# job
$report = array();
foreach($products as $p)
{
try
{
$result = $this->_compareProduct((int) $p['id_product']);
if($result && $result['changed'])
{
$result['id_product'] = $p['id_product'];
$result['name'] = $p['name'];
$report[] = $result;
}
}
catch(Exception $e)
{
$report[] = array(
'id_product' => $p['id_product'],
'name' => $p['name'],
'res' => false,
'msg' => 'Exception occured',
);
}
}
# if there is nothing to report
if(!$report)
return true;
# output
$output = '';
foreach($report as $row)
{
$link = $this->context->link->getProductLink($row['id_product']);
$output .= $row['id_product'] .' - '. $row['name'] .' '. ($row['res'] ? 'Ok!' : 'Error!') .' : '. $row['msg'] ."\r\n";
}
# send mail
$tpl_vars = array(
'{report_txt}' => strip_tags($output),
'{report_html}' => nl2br($output),
);
Mail::Send(
$this->context->language->id,
'report',
'Price update report',
$tpl_vars,
PRODUCT_COMPARE_EMAIL,
'',
Configuration::get('PS_SHOP_EMAIL'),
Configuration::get('PS_SHOP_NAME'),
null,
null,
dirname(__FILE__).'/mails/',
null,
$this->context->shop->id
);
return true;
}
public function compareTest($id_product)
{
$report = $this->_compareProduct($id_product);
var_dump($report);
die;
}
protected function _compareProduct($id_product)
{
# load product
$product = new Product($id_product, false, $this->context->language->id, $this->context->shop->id);
if(!Validate::isLoadedObject($product))
return false;
if(!$product->compare_link)
return false;
$oldPrice = (float) $product->price;
//******
# request
$data = file_get_contents($product->compare_link);
# analize price
if(!preg_match('!data-free-data=\'([^\']+)\'!i', $data, $matches))
{
return array(
'res' => false,
'msg' => 'Price not found!',
);
}
//******
$prices = json_decode($matches[1], true);
$newPrice = (float) $prices['minPrice'];
if(!$newPrice)
{
return array(
'res' => false,
'msg' => 'Zero price!',
);
}
# check change
$changed = $oldPrice != $newPrice;
if(!$changed)
{
return array(
'res' => false,
'msg' => 'The price is the same.',
);
}
$newPrice += (float) $product->compare_price;
# check change
$changed = $oldPrice != $newPrice;
if(!$changed)
{
return array(
'res' => false,
'msg' => 'The price is the same.',
);
}
# update
$product->price = $newPrice;
if(!$product->save())
{
return array(
'res' => false,
'msg' => 'Not saved!',
);
}
return array(
'res' => true,
'changed' => $changed,
'msg' => 'Updated! From: '.round($oldPrice, 2).' To: '.round($newPrice, 2),
);
}
}
There are needed function
protected function _compareProduct($id_product)
{
# load product
$product = new Product($id_product, false, $this->context->language->id, $this->context->shop->id);
if(!Validate::isLoadedObject($product))
return false;
if(!$product->compare_link)
return false;
$oldPrice = (float) $product->price;
//******
# request
$data = file_get_contents($product->compare_link);
# analize price
if(!preg_match('!data-free-data=\'([^\']+)\'!i', $data, $matches))
{
return array(
'res' => false,
'msg' => 'Price not found!',
);
}
//******
$prices = json_decode($matches[1], true);
$newPrice = (float) $prices['minPrice'];
if(!$newPrice)
{
return array(
'res' => false,
'msg' => 'Zero price!',
);
}
# check change
$changed = $oldPrice != $newPrice;
if(!$changed)
{
return array(
'res' => false,
'msg' => 'The price is the same.',
);
}
$newPrice += (float) $product->compare_price;
# check change
$changed = $oldPrice != $newPrice;
if(!$changed)
{
return array(
'res' => false,
'msg' => 'The price is the same.',
);
}
# update
$product->price = $newPrice;
if(!$product->save())
{
return array(
'res' => false,
'msg' => 'Not saved!',
);
}
return array(
'res' => true,
'changed' => $changed,
'msg' => 'Updated! From: '.round($oldPrice, 2).' To: '.round($newPrice, 2),
);
}

PayPal does not show order summary-Omnipay

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.

Checking if key exists in array [duplicate]

This question already has answers here:
Giving my function access to outside variable
(6 answers)
Closed 6 years ago.
EDIT:
if(array_key_exists($errcode, $Errors)){
$Data['status'] = -1;
$Data['err'] = array(
"err_code" => $errcode,
"err_str" => $Errors[$errcode]
);
}
I'm having a harsh time figuring out if a key exists in an array, I've tried using array_key_exists method, but no luck! I've also tried empty($array[$key]) which seems to return the same generic error rather than the specific one.
Calling err(null, 3) will output:
{
"status": -1,
"err": {
"err_code": null,
"err_str": "Generic error"
}
}
I've tried using the array_key_exists method which returns a bool but it doesn't seem to work, why is this?
My site should output error 5: Invalid
//Errors ENUM
$Errors = array(
0 => "Cannot parse <GameID>",
1 => "Invalid steam session",
2 => "Invalid <GameID>, non-numeric",
3 => "SQL Connection refused",
4 => "SQL Query error",
5 => "invalid <GameID>"
);
function err($status, $errcode){
if(isset($errcode)){
if($Errors[$errcode] != null){
$Data['status'] = -1;
$Data['err'] = array(
"err_code" => $errcode,
"err_str" => $Errors[$errcode]
);
} else {
$Data['status'] = -1;
$Data['err'] = array(
"err_code" => null,
"err_str" => "Generic error"
);
}
} else {
$Data['status'] = $status;
$Data['err'] = array(
"err_code" => null,
"err_str" => null
);
}
echo(json_encode($Data, 128 | 32));
}
The err function doesn't see global $Errors variable. Declare Errors variable as global inside Err function:
function err($status, $errcode){
global $Errors;
if(isset($errcode)){
if($Errors[$errcode] != null){
$Data['status'] = -1;
$Data['err'] = array(
"err_code" => $errcode,
"err_str" => $Errors[$errcode]
);
} else {
$Data['status'] = -1;
$Data['err'] = array(
"err_code" => null,
"err_str" => "Generic error"
);
}
} else {
$Data['status'] = $status;
$Data['err'] = array(
"err_code" => null,
"err_str" => null
);
}
echo(json_encode($Data, 128 | 32));
}

Categories