Fedex Freight API not giving accurate rates - php

The code the developer put in our site has a bunch of express (non freight) service types. I only need to implement FedEx Freight rates into my website and the developer has ran off on me. Any help would be greatly appreciated.
if($cominfo[0]['companyNAME'] == "FedEx" && $rescar12[0]['login']!="" && $rescar12[0]['carpassword']!="" && $rescar12[0]['accountNUMBER']!="" && $rescar12[0]['accesskey']!="" && $rescar12[0]['meterkey']!=""){
/*$fedx_accountnumber = $rescar12[0]['accountNUMBER'];
$fedex_meterkey = $rescar12[0]['meterkey'];
$fedex_freightAccount = $rescar12[0]['meterkey'];
$fedex_accessKey = $rescar12[0]['meterkey'];
$fedex_productionPassword = $rescar12[0]['meterkey'];*/
echo '<pre>';
print_r($_SESSION['order']);
$fedx_accountnumber = 'account number';
$fedex_meterkey = 'meter key';
$fedex_freightAccount = 'freight account';
$fedex_accessKey = 'secret access key';
$fedex_productionPassword = 'secret password';
//$services1['fedex']['STANDARDOVERNIGHT'] = 'Standard Overnight';
if($_SESSION['order'][$counter]['weight_unit'] != "lb"){
$weight= convert_weight($_SESSION['order'][$counter]['weight'],$_SESSION['order'][$counter]['weight_unit'],'lb');
$weight_units = 'LB';
} else{
$weight = $_SESSION['order'][$counter]['weight'] ;
$weight_units = $_SESSION['order'][$counter]['weight_unit'];
}
// Services
$services = $services1;
// Weight
$weight = $_SESSION['order'][$counter]['weight']; // Default = 1
$weight_units = $_SESSION['order'][$counter]['weight_unit']; // lb (default), oz, gram, kg
// Size
$size_length = $_SESSION['order'][$counter]['len_gth']; // Default = 8
$size_width = $_SESSION['order'][$counter]['width']; // Default = 4
$size_height = $_SESSION['order'][$counter]['height']; // Default = 2
$size_units = $_SESSION['order'][$counter]['dimesions']; // in (default), feet, cm
$role = $_SESSION['order'][$counter]['role'];
// From
$from_zip = $_SESSION['order'][$counter]['f_zipcode'];
$from_state = $_SESSION['order'][$counter]['f_stateID']; // Only Required for FedEx
$from_country = $_SESSION['order'][$counter]['f_countryID'];
$from_city = $_SESSION['order'][$counter]['f_cityID'];
// To
$to_zip = $_SESSION['order'][$counter]['t_zipcode'];
$to_state = $_SESSION['order'][$counter]['t_stateID']; // Only Required for FedEx
$to_country = $_SESSION['order'][$counter]['t_countryID'];
$to_city = $_SESSION['order'][$counter]['t_cityID'];
require_once "library/fedex-common.php";
//Please include and reference in $path_to_wsdl variable.
$path_to_wsdl = "wsdl/RateService_v14.wsdl";
ini_set("soap.wsdl_cache_enabled", "0");
$client = new SoapClient($path_to_wsdl, array('trace' => 1)); // Refer to http://us3.php.net/manual/en/ref.soap.php for more information
$request['WebAuthenticationDetail'] = array(
'UserCredential' =>array(
'Key' => getProperty('key'),
'Password' => getProperty('password')
)
);
$request['ClientDetail'] = array(
'AccountNumber' => getProperty('shipaccount'),
'MeterNumber' => getProperty('meter')
);
$request['TransactionDetail'] = array('CustomerTransactionId' => ' *** Rate Request v14 using PHP ***');
$request['Version'] = array(
'ServiceId' => 'crs',
'Major' => '14',
'Intermediate' => '0',
'Minor' => '0'
);
$request['ReturnTransitAndCommit'] = true;
$request['RequestedShipment']['DropoffType'] = 'REGULAR_PICKUP'; // valid values REGULAR_PICKUP, REQUEST_COURIER, ...
$request['RequestedShipment']['ShipTimestamp'] = date('c');
$request['RequestedShipment']['ServiceType'] = 'FEDEX_FREIGHT_ECONOMY'; // valid values STANDARD_OVERNIGHT, PRIORITY_OVERNIGHT, FEDEX_GROUND, ...
$request['RequestedShipment']['PackagingType'] = 'YOUR_PACKAGING'; // valid values FEDEX_BOX, FEDEX_PAK, FEDEX_TUBE, YOUR_PACKAGING, ...
$request['RequestedShipment']['Shipper'] = getProperty('freightbilling');
$request['RequestedShipment']['Recipient'] = addRecipient();
$request['RequestedShipment']['ShippingChargesPayment'] = addShippingChargesPayment();
$request['RequestedShipment']['FreightShipmentDetail'] = array(
'FedExFreightAccountNumber' => getProperty('freightaccount'),
'FedExFreightBillingContactAndAddress' => getProperty('freightbilling'),
'Role' =>$role,
'PaymentType' => 'PREPAID',
'LineItems' => array(
'FreightClass' => 'CLASS_0'.$_SESSION['order'][$counter]['class'],
'Weight' => array(
'Value' => $weight,
'Units' => $weight_units,
),
'Dimensions' => array(
'Length' => $size_length,
'Width' => $size_width,
'Height' => $size_height,
'Units' => $size_units
),
)
);
$request['RequestedShipment']['RateRequestTypes'] = 'ACCOUNT';
$request['RequestedShipment']['RateRequestTypes'] = 'LIST';
$request['RequestedShipment']['PackageCount'] = '1';
try{
if(setEndpoint('changeEndpoint')){
$newLocation = $client->__setLocation(setEndpoint('endpoint'));
}
$response = $client -> getRates($request);
echo '<pre>';
print_r($response);
exit;
if ($response -> HighestSeverity != 'FAILURE' && $response -> HighestSeverity != 'ERROR'){
echo $rateReply = $response -> RateReplyDetails->RatedShipmentDetails[0]->ShipmentRateDetail->TotalNetCharge->Amount;
// printSuccess($client, $response);
}else{
echo $rateReply ='N/A';
//printError($client, $response);
}
//writeToLog($client); // Write to log file
} catch (SoapFault $exception) {
printFault($exception, $client);
}
$_SESSION['FedEx'][$counter]['price'] = $rateReply;
}

Related

How can I integrate Stripe without using JS? I have a problem with creating a session to stripe?

Since I have payments, through PayPal I try to integrate payments through Stripe. My system works on the following principle:
dashboard.php - here I have , in which Gateway is selected (paypal or stripe) and the corresponding amount that the client wants to add to his personal balance
```
<form action="/balance" method="post" id="form-balance" data-ajax="true">
stripe: <input type="radio" name="method" value="stripe" id="method_stripe">
paypal: <input type="radio" name="method" value="paypal" id="method_paypal">
</div>
<div class="form" style="width:330px">
<label class="required">Amount:</label>
<div class="input-group">
<input type="number" name="price" value="" min="1" autofocus required>
<button type="submit" class="btn btn-primary">continue</button>
</div>
</div>
</form>
```
balance.php - (ajax) this is the ajax part. In it I check and process the sent data: gateway, amount.
<?php
$stop = $res = [];
switch ( $subaction ) {
case 'balance':
$sum = ( isset($_REQUEST['amount']) && validate_price($_REQUEST['amount']) ) ? round($_REQUEST['amount'], 2) : 35;
$method = ( isset($_REQUEST['method']) && trim($_REQUEST['method']) != '' ) ? strip_tags( trim($_REQUEST['method']) ) : '';
if ( ! $sum ) {
$stop[] = $lng->data['Enter the amount to be filled'];
} elseif ( $sum < $config['minimal_transfer'] ) {
$stop[] = $lng->data['Minimum amount to power the deposit']." - <b>".$config['valuta']['EUR']."".$config['minimal_transfer'].".</b>";
}
if ( $stop ) {
$res['answer'] = 'stop';
$res['error'] = $stop;
} else {
$db->query( "INSERT INTO " . PREFIX_S . "_payment (`user_id`, `sum`, `temp`, `date`) VALUES ('" . USER_ID . "', '{$sum}', '1', '{$_DATE}')" );
$id = $db->insert_id();
$res['answer'] = 'ok';
switch ( $method ) {
// stripe
case 'stripe':
$params = [
'PAYMENT_AMOUNT' => $sum,
'PAYMENT_DESC_BASE64' => base64_encode($lng->data['Funding of an account'].' #' . SITE_ID),
'PAYMENT_NO' => $id
];
$location = "/site/payment_do/stripe_charget?" . http_build_query($params);
$res['eval'] = "window.location.href = '{$location}';";
break;
// paypal
case 'paypal':
$params = [
'PAYMENT_AMOUNT' => $sum,
'PAYMENT_DESC_BASE64' => base64_encode($lng->data['Funding of an account'].' #' . SITE_ID),
'PAYMENT_NO' => $id
];
$location = "/site/payment_do/paypal_charget?" . http_build_query($params);
$res['eval'] = "window.location.href = '{$location}';";
break;
default:
$params = [
'PAYMENT_AMOUNT' => $sum,
'PAYMENT_NO' => $id
];
$_SESSION['params'] = $params;
break;
}
}
break;
default: die( 'error' );
}
$content = json_encode($res);
header( "Content-type: application/json; charset=" . $config['charset'] );
echo $content;
payment.php - If everything is fine in balance.php (ajax) I send the data to the appropriate gateway for payment to payment.php. It sends to the appropriate official gateway (paypal.com or stripe.com) for payment
<?php
$_TIME = time();
$_DATE = date( "Y-m-d H:i:s", $_TIME );
require ENGINE_DIR . '/autoloader.php';
/*Array
(
[PAYMENT_AMOUNT] => 35
[PAYMENT_DESC_BASE64] => 0JfQsNGF0YDQsNC90LLQsNC90LUg0L3QsCDRgdC80LXRgtC60LAgIzI1
[PAYMENT_NO] => 2578
[PAYEE_PURSE] =>
[init] => site
[do] => payment_do
[action] => stripe_charget
[lang] => 7
)
*/
define('STRIPE_SUCCESS_URL', '/site/payment_do/success/');
define('STRIPE_CANCEL_URL', 'site/payment_do/cancel/');
$productName = "Funding an Account";
$productID = "DP12345";
$currency = "eur";
$params = ( isset($_REQUEST['params']) && is_array($_REQUEST['params']) ) ? $_REQUEST['params'] : [];
$productPrice = ( isset($_REQUEST['PAYMENT_AMOUNT']) && $_REQUEST['PAYMENT_AMOUNT'] > 10 ) ? $_REQUEST['PAYMENT_AMOUNT'] : 35;
$stripeAmount = round($productPrice*100, 2); // Convert product price to cent
$res = $stop = [];
ini_set("display_errors", "1"); error_reporting(E_ALL);
switch ( $action ) {
case 'stripe_charget':
// Include Stripe PHP library
require_once ENGINE_DIR . '/stripe-php/init.php';
// Set API key
\Stripe\Stripe::setApiKey($config['stripe']['stripe_api_key']);
$response = array(
'status' => 0,
'error' => array(
'message' => 'Invalid Request!'
)
);
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$input = file_get_contents('php://input');
$request = json_decode($input);
//print_r($request);
//die;
}
if (json_last_error() !== JSON_ERROR_NONE) {
http_response_code(400);
echo json_encode($response);
exit;
}
if(!empty($request->checkoutSession)){
// Create new Checkout Session for the order
try {
$session = \Stripe\Checkout\Session::create([
'payment_method_types' => ['card'],
'line_items' => [[
'price_data' => [
'product_data' => [
'name' => $productName,
'metadata' => [
'pro_id' => $productID
]
],
'unit_amount' => $stripeAmount,
'currency' => $currency,
],
'quantity' => 1,
'description' => $productName,
]],
'mode' => 'payment',
'success_url' => STRIPE_SUCCESS_URL.'?session_id={CHECKOUT_SESSION_ID}',
'cancel_url' => STRIPE_CANCEL_URL,
]);
}catch(Exception $e) {
$api_error = $e->getMessage();
}
if(empty($api_error) && $session){
$response = array(
'status' => 1,
'message' => 'Checkout Session created successfully!',
'sessionId' => $session['id']
);
}else{
$response = array(
'status' => 0,
'error' => array(
'message' => 'Checkout Session creation failed! '.$api_error
)
);
}
}
unset($_SESSION['params']);
// Return response
echo json_encode($response);
break;
case 'paypal':
$id = ( isset($_REQUEST['params']['account']) && (int)$_REQUEST['params']['account'] > 0 ) ? (int)$_REQUEST['params']['account'] : 0;
break;
default:
die( 'error action' );
}
When I use stripe js, I get the following error because I can't send the data to balance.php and from there to payment.php
{"status":0,"error":{"message":"Invalid Request!"}}
If I do the code as described here: https://stripe.com/docs/checkout/integration-builder, it works but this way I stop working for payments via PayPal - I want to have two working payment systems in this case, i don't have to use js on stripe.

Display product price when searching

I purchased a search module that displays a popup and would like to add the price of the product I searched for in it, I found the file that I should make the changes, but what should I add to display the product price
This is the responsible function for displaying the product characteristics
protected function _prepareProducts()
{
$isEnabledImage = (bool) Mage::getStoreConfig(self::ENABLE_IMAGE_CONFIG);
$imageHeight = (int) Mage::getStoreConfig(self::IMAGE_HEIGHT_CONFIG);
$imageWidth = (int) Mage::getStoreConfig(self::IMAGE_WIDTH_CONFIG);
$isEnabledDescription = (bool) Mage::getStoreConfig(self::ENABLE_DESCRIPTION_CONFIG);
$lengthDescription = (int) Mage::getStoreConfig(self::DESCRIPTION_LENGTH_CONFIG);
$collection = $this->_getAlternativeProductCollection();
// $this->_prepareQueryPopularity($collection->getSize());
$toolbar = $this->getToolbarBlock();
$toolbar->setCollection($collection);
$size = (int) Mage::getStoreConfig(self::RESULT_SIZE_CONFIG);
$collection->setPageSize($size);
// $collection->getSelect()->limit($size);
$sortOrder = Mage::getStoreConfig(self::SORT_ORDER_PRODUCT);
if (0 < count($collection)) {
$this->_suggestions[$sortOrder][] = array('html' =>
'<p class="headercategorysearch">' . $this->__("") . '</p>'
);
}
if ($isEnabledImage) {
$helper = Mage::helper('catalog/image');
}
foreach ($collection as $_row) {
$_product = Mage::getModel('catalog/product')
->setStoreId($this->getStoreId())
->load($_row->getId());
$_image = $_srcset = $_description = '';
if ($isEnabledImage) {
$_image = (string) $helper->init($_product, 'thumbnail')->resize($imageWidth, $imageHeight);
$_srcset = (string) $helper->init($_product, 'thumbnail')->resize($imageWidth * 2, $imageHeight * 2);
$_srcset .= ' 2x';
}
if ($isEnabledDescription) {
$_description = strip_tags($this->_trim(
$_product->getShortDescription(),
$lengthDescription
));
}
// $store = Mage::app()->getStore();
// $path = Mage::getResourceModel('core/url_rewrite')
// ->getRequestPathByIdPath('product/' . $_product->getId(), $store);
// // $url = $store->getBaseUrl($store::URL_TYPE_WEB) . $path;
// $url = rtrim(Mage::getUrl($path, array('_store' => $store->getStoreId())), '/');
$url = $_product->getProductUrl();
$this->_suggestions[$sortOrder][] = array(
'name' => $_product->getName(),
'url' => $url,
'image' => $_image,
'srcset' => $_srcset,
'description' => $_description,
);
}
}
Simply add this line
'price' => $_product->getPrice() in suggestions array
$this->_suggestions[$sortOrder][] = array(
'name' => $_product->getName(),
'price' => $_product->getPrice(),
'url' => $url,
'image' => $_image,
'srcset' => $_srcset,
'description' => $_description,
);
you may use
$_product->getFinalPrice()
inside this _suggestions property, but i guess there is also a template or a bit of js responsible for output of all this.

Codeigniter Uploading excel and Saving to database (Network Error (tcp_error))

Really need your support on this one.
This works on intranet not until we decided to upload it on public.
Im using Codeigniter + SQL Server + Apache
This how it should work:
upload the excel file, read the content, save to database and send an email & sms.
But:
Everytime I upload the excel file after 3 Mins it stops and got this error written on Developer Opt->Network Tab:
"Network Error (tcp_error)
A communication error occurred: ""
The Web Server may be down, too busy, or experiencing other problems preventing it from responding to requests. You may wish to try again at a later time."
Here's my code:
public function do_upload()
{
set_time_limit(0);
ignore_user_abort(1);
$accID = $this->input->get('acc');
$rmi = $this->input->get('rmi');
$spInst = $this->input->get('spInst');
$dateReq = '';
$dateReqq = $this->input->get('dateReq');
if($dateReqq==null or $dateReqq==''){
$dateReq = date('Y-m-d');
}else{
$dateReq = $this->input->get('dateReq');
}
$dateNow = date("F_d_Y__h_i_s__A");
$status = "";
$msg = "";
$file_element_name = 'file';
$file_name = '';
if ($status != "error")
{
$config['upload_path'] = 'c:/xampp/htdocs/eDR/assets/uploads/';
$config['allowed_types'] = 'xlsx';
$config['max_size'] = 60000;
$config['overwrite'] = TRUE;
$config['remove_spaces'] = TRUE;
$config['file_name'] = uniqid('file')."_". $dateNow;
$this->load->library('upload', $config);
if (!$this->upload->do_upload($file_element_name))
{
$status = FALSE;
$msg = $this->upload->display_errors('', '');
}
else
{
$data = $this->upload->data();
//$file_id = $this->files_model->insert_file($data['file_name'], $_POST['title']);
//if($file_id)
//{
$file_name = $data['file_name'];
$file = "c:/xampp/htdocs/eDR/assets/uploads/" . $file_name;
$this->do_read($file,$accID,$rmi,$spInst,$dateReq);
$status = TRUE;
$msg = "File successfully uploaded";
//}
//else
// {
// unlink($data['full_path']);
// $status = "error";
// $msg = "Something went wrong when saving the file, please try again.";
// }
}
#unlink($_FILES[$file_element_name]);
}
echo json_encode(array('status' => $status, 'msg' => $msg, 'name' => $file_name));
}
public function do_read($file,$accID,$rmi,$spInst,$dateReq){
//load the excel library
$this->load->library('excel');
//read file from path
$objPHPExcel = PHPExcel_IOFactory::load($file);
//get only the Cell Collection
$cell_collection = $objPHPExcel->getActiveSheet()->getCellCollection();
//extract to a PHP readable array format
foreach ($cell_collection as $cell) {
$column = $objPHPExcel->getActiveSheet()->getCell($cell)->getColumn();
$row = $objPHPExcel->getActiveSheet()->getCell($cell)->getRow();
$data_value = $objPHPExcel->getActiveSheet()->getCell($cell)->getValue();
//header will/should be in row 1 only. of course this can be modified to suit your need.
//if ($row == 1) {
// $header[$row][$column] = $data_value;
//} else {
$arr_data[$row][$column] = $data_value;
//}
}
//send the data in an array format
//$data['header'] = $header;
$drCount = ($this->up->get_DRcount($accID));
$date = date("F d, Y h:i: s A");
$data['values'] = $arr_data;
$last = count($arr_data) - 1;
$totalQty = 0;
$abbr = $this->up->get_Abbr($accID);
$TATnAGING = '';
$dAdd ='';
$posReq='';
$reqD;
foreach ($arr_data as $i => $row)
{
if( empty($row['B']) or
empty($row['C']) or
empty($row['D']) or
empty($row['E']) or
empty($row['F']) or
empty($row['G']) or
empty($row['H']) or
empty($row['I']) or
empty($row['J']) or
empty($row['K'])
){
$msg = 'B = ' . $row['B'] . ' C = ' . $row['C'] . ' D = ' . $row['D'] . ' E = ' . $row['E'] . ' F = ' . $row['F'] . ' G = ' . $row['G'] . ' H = ' . $row['H'] . ' I = ' . $row['I']
. ' J = ' . $row['J'] . ' K = ' . $row['K'] ;
$status = FALSE;
echo json_encode(array('status' => $status, 'msg'=>$msg));
exit();
}
}
foreach ($arr_data as $i => $row)
{
try {
$reqDatee = date('F d, Y', strtotime($dateReq));
$start = new DateTime( $reqDatee );
$end = new DateTime(date("F d, Y"));
$oneday = new DateInterval("P1D");
$days = array();
$data1 = "7.5";
foreach(new DatePeriod($start, $oneday, $end->add($oneday)) as $day) {
$day_num = $day->format("N"); /* 'N' number days 1 (mon) to 7 (sun) */
if($day_num < 6) { /* weekday */
$days[$day->format("Y-m-d")] = $data1;
}
}
$TATnAGING = count($days). ' day/s';
$dAdd = trim(strtoupper($row['D']));
$posReq = trim(strtoupper($row['B']));
$reqD = $dateReq;
$isFirst = ($i == 0);
$isLast = ($i == $last);
$id = $this->session->userdata('username');
$totalQty += $row['G'];
} catch (Exception $e) {
$msg = 'Caught exception: '. $e->getMessage(). "\n";
$status = FALSE;
echo json_encode(array('status' => $status, 'error'=>$msg));
exit();
}
if($i>1){
$data1 = array();
try {
if(trim(strtoupper($row['B']))=='YES' or trim(strtoupper($row['B']))=='Y'){
$data1 = array(
"drRef" => $abbr . '2017' . sprintf("%07d", ($drCount + 1)),
"postReq" => trim(strtoupper($row['B'])),
"reqDate" => $dateReq,
"reqBy" => trim(strtoupper($row['C'])),
"deliveryAcc" => trim(strtoupper($row['D'])),
"matCode" => trim(strtoupper($row['E'])),
"matDescription" => trim(strtoupper($row['F'])),
"qty" => $row['G'],
"UOM" => trim(strtoupper($row['H'])),
"location" => trim(strtoupper($row['I'])),
"postRef" => '',
// "postDate" => date("F d, Y h:i:s A"),
// "postBy" => $this->session->userdata['name'],
"status" => 'PENDING FOR POSTING',
// "TAT" => trim(strtoupper($row['O'])),
// "AGING" => trim(strtoupper($row['P'])),
"userID" => $id,
'addedBy' => $this->session->userdata('name'),
'addedUsing' => gethostbyaddr($_SERVER['REMOTE_ADDR']),
'dateAdded' => $date,
'seqNo' => uniqid(),
'accID' => $accID,
'fromIMEI' => trim(strtoupper($row['J'])),
'toIMEI' => trim(strtoupper($row['K'])),
);
}else{
$data1 = array(
"drRef" => $abbr .'2017' . sprintf("%07d", ($drCount + 1)),
"postReq" => trim(strtoupper($row['B'])),
"reqDate" => $dateReq,
"reqBy" => trim(strtoupper($row['C'])),
"deliveryAcc" => trim(strtoupper($row['D'])),
"matCode" => trim(strtoupper($row['E'])),
"matDescription" => trim(strtoupper($row['F'])),
"qty" => $row['G'],
"UOM" => trim(strtoupper($row['H'])),
"location" => trim(strtoupper($row['I'])),
"postRef" => '',
"postDate" => date("F d, Y h:i:s A"),
"postBy" => $this->session->userdata['name'],
"status" => 'POSTED',
"TAT" => $TATnAGING,
"userID" => $id,
'addedBy' => $this->session->userdata('name'),
'addedUsing' => gethostbyaddr($_SERVER['REMOTE_ADDR']),
'dateAdded' => $date,
'seqNo' => uniqid(),
'accID' => $accID,
'fromIMEI' => trim(strtoupper($row['J'])),
'toIMEI' => trim(strtoupper($row['K'])),
);
}
} catch (Exception $e) {
$msg = 'Caught exception: '. $e->getMessage(). "\n";
$status = FALSE;
echo json_encode(array('status' => $status, 'error'=>$msg));
exit;
}
$insert = $this->up->save($data1);
$data1 = array();
}
}
if($posReq=='YES' or $posReq=='Y'){
$data1 = array(
'drRef' => $abbr . '2017' . sprintf("%07d", ($drCount + 1)),
'accID' => $accID,
'userID' => $this->session->userdata['id'],
// 'postRef' => trim(strtoupper($row['K'])),
// 'postBy' => $this->session->userdata['name'],
// 'postDate' => $date,
'totQty' => $totalQty,
'status' => 'PENDING FOR POSTING',
'isPosted' => 'No',
'isApproved' => 'Pending',
'approverID' => $this->session->userdata('head'),
'postReq' => $posReq,
'reqDate' => $reqD,
'deliveryAdd' => $dAdd,
'reason' => urldecode($rmi),
'spInst' => urldecode($spInst),
);
}else{
$data1 = array(
'drRef' => $abbr . '2017' . sprintf("%07d", ($drCount + 1)),
'accID' => $accID,
'userID' => $this->session->userdata['id'],
//'postRef' => $this->session->userdata('username'),
'postBy' => $this->session->userdata['name'],
'postDate' => $date,
'totQty' => $totalQty,
'status' => 'POSTED',
'isPosted' => 'Yes',
'isApproved' => 'Pending',
'approverID' => $this->session->userdata('head'),
'postReq' => $posReq,
'tat' => $TATnAGING ,
'reqDate' => $reqD,
'deliveryAdd' => $dAdd,
'reason' => urldecode($rmi),
'spInst' => urldecode($spInst),
);
}
$insert = $this->up->saveOrder($data1);
$drRef = $abbr . '2017' . sprintf("%07d", ($drCount + 1));
$id = $this->up->get_Data('head','tblUser','userID',$this->session->userdata('id'));
$recepient = $this->up->get_Data('email','tblUser','userID',$id);
$name = $this->up->get_Data('name','tblUser','userID',$id);
$config = Array(
'protocol' => 'smtp',
'smtp_host' => '182.50.151.61',
'smtp_port' => 587,
'smtp_user' => 'user',
'smtp_pass' => 'pass',
'mailtype' => 'html',
'charset' => 'iso-8859-1'
);
$this->load->library('email', $config);
$this->email->set_newline("\r\n");
// Set to, from, message, etc.
$this->email->from('eDR#domain.com', 'e - Delivery Receipt');
$this->email->to($recepient);
//$this->email->subject('eDR Notifications');
$this->email->subject('eDR Notification < DR Request >');
$message = 'Message';
$this->email->message($message);
$result = $this->email->send();
// if (!$result) {
// $this->email->print_debugger();
// }
$receiver = $this->up->get_Data('phoneNum','tblUser','userID',$this->session->userdata('head'));
$sms = array(
'receiver' => $receiver,
'msg' => 'message',
'status' => 'Send',
);
$this->up->sendSMS($sms);
}
Thanks.
I solved this problem via CRON job or calling cmd command on my PHP script so that it will execute the query on server itself really fast. :)

WooCommerce: Check if coupon is valid

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

Get all inbox messages with Gmail API using PHP

How can I get all inbox messages using Gmail API with PHP? I can just get message ID, and nothing beyond that. I need to fetch Subject, Sender and Message Text.
<?php
$list = $gmail->users_messages->listUsersMessages('me', ['maxResults' => 10000, 'q' => 'category:primary']);
$messageList = $list->getMessages();
$client->setUseBatch(true);
$batch = new Google_Http_Batch($client);
foreach($messageList as $mlist){
$batch->add($gmail->users_messages->get('me', $mlist->id, ['format' => 'raw']), $mlist->id);
}
$batchMessages = $batch->execute();
$inboxMessage = [];
foreach($batchMessages as $dMessage){
$messageId = $dMessage->id;
$messageSnippet = $dMessage->snippet;
$dcMessage = base64url_decode($dMessage->getRaw());
$params['include_bodies'] = true;
$params['decode_bodies'] = true;
$params['decode_headers'] = true;
$mimeDecode = new Mail_mimeDecode($dcMessage);
$mimeSubject = $mimeDecode->decode($params)->headers['subject'];
$inboxMessage[] = [
'messageId' => $messageId,
'messageSubject' => $messageSubject
];
}
?>
This is how i did it.
<?php
$list = $gmail->users_messages->listUsersMessages('me', [
'maxResults' => 10,
'q' => $search
]);
$messageList = $list->getMessages();
$inboxMessage = [];
foreach($messageList as $mlist) {
$optParamsGet2['format'] = 'full';
$single_message = $gmail->users_messages->get('me', $mlist->id, $optParamsGet2);
$message_id = $mlist->id;
$headers = $single_message->getPayload()->getHeaders();
$snippet = $single_message->getSnippet();
foreach($headers as $single) {
if ($single->getName() == 'Subject') {
$message_subject = $single->getValue();
} elseif ($single->getName() == 'Date') {
$message_date = $single->getValue();
$message_date = date('M jS Y h:i A', strtotime($message_date));
} elseif ($single->getName() == 'From') {
$message_sender = $single->getValue();
$message_sender = str_replace('"', '', $message_sender);
}
}
$inboxMessage[] = [
'messageId' => $message_id,
'messageSnippet' => $snippet,
'messageSubject' => $message_subject,
'messageDate' => $message_date,
'messageSender' => $message_sender
];
}
?>

Categories