I have to implement notification functionality in my project which is made in CodeIgniter.
Scenario is like, I have two apps in my device i.e. driver and passenger app. I have created a function in a controller file and trying to send notifications to both the apps. But I am getting the notification on only one driver app.
Below is my controller function. Please suggest me where I am committing mistake -
public function tripNotStartedCron() {
try {
$allTripsdata = $this->trip->getAllTripsCron();
echo "<pre>";print_r($allTripsdata);
$allCancelTripsdata = $this->trip->getAllTripsCron(1);
print_r($allCancelTripsdata);
// Send notification for trip notification after 30 min
foreach ($allTripsdata as $tripsData) {
/* Time calculation */
$buggyTimeZones = array('19800' => 'Asia/Calcutta');
if (array_key_exists($tripsData['timezone'], $buggyTimeZones)) {
$pickUpLocationTimeZone = $buggyTimeZones[$tripsData['timezone']];
} else {
$pickUpLocationTimeZone = timezone_name_from_abbr('', $tripsData['timezone'], 0);
}
$date = new DateTime('NOW', new DateTimeZone($pickUpLocationTimeZone));
$tripsData['pickupdatetime'] = date('Y-m-d H:i:s', strtotime($tripsData['pickupdatetime'] . ' +' . CONFIRMED_CANCELLED_TRIP . ' minutes'));
$tripDateTime = new DateTime($tripsData['pickupdatetime'], new DateTimeZone($pickUpLocationTimeZone));
/* End time calculation */
$driverId = $tripsData['fkdriverid'];
$rideId = $tripsData['rideid'];
$asap = $tripsData['is_pickup_as_soon'];
$tripStatusId = TRIP_STATUS_DRIVERCONFIRMED;
//$message = 'You have a trip that was scheduled to start more than ' . CONFIRMED_CANCELLED_TRIP . ' minutes ago, if you do not start it within ' . DRIVER_TRIP_CANCELLED_SECOND_WARING . ' minutes it will be automatically cancelled.';
$message = 'You have a trip that was scheduled to start more than 1 hour ago, if you do not start it within ' . DRIVER_TRIP_CANCELLED_SECOND_WARING . ' minutes it will be automatically cancelled.';
//echo date($date->format('U'))."----------".date($tripDateTime->format('U'));
if ($date->format('U') > $tripDateTime->format('U')) {
if ($driverId > 0) {
/* * ** Send push notificaion on ios *** */
$iosDeviceDetailArr = $this->profile->getIosNotificationStatus($driverId, DRIVER_ROLE, IOS);
$tripCompleteDetail = $this->trip->getOrderDetailForARide($rideId);
$driverDetails = $this->profile->getDriverDetails($driverId);
$driverBUserId = $driverDetails[0]->id ? $driverDetails[0]->id : 0;
$driverCurrentUserId = $driverId;
$driverCurrentRoleId = DRIVER_ROLE;
$additionalDetail = array();
if (!empty($driverBUserId)) {
$additionalDetail = array('bUserId' => $driverBUserId, 'currentUserId' => $driverCurrentUserId, 'currentRoleId' => $driverCurrentRoleId);
}
/* store notification detail in db start */
$dataDictionary = array(
'alert' => $message,
'ondemand' => $asap,
'ridedetail' => $tripCompleteDetail,
'rideid' => $rideId,
'type' => "trip_cancel_reminder",
'userdetail' => $additionalDetail
);
$dataToSave = array(
'buserid' => $additionalDetail['bUserId'],
'currentuserid' => $additionalDetail['currentUserId'],
'currentroleid' => $additionalDetail['currentRoleId'],
'datadictionary' => json_encode($dataDictionary),
'rideid' => $rideId,
'notificationlabel' => 'Trip Scheduling Alert',
'createddate' => date('Y-m-d H:i:s'),
'modifydate' => date('Y-m-d H:i:s')
);
$notificationId = $this->common->saveDetails(TBL_PUSH_NOTIFICATIONS, $dataToSave);
if ($notificationId) {
updateNotificationStatus(array('currentuserid' => $additionalDetail['currentUserId'], 'rideid' => $rideId, 'notificationid !=' => $notificationId), 'trip_cancel_reminder');
}
$tripCompleteDetail[0]['notificationId'] = (isset($notificationId) && $notificationId) ? $notificationId : 0;
/* store notification detail in db start */
$res = member_notification_ios($iosDeviceDetailArr, $message, $rideId, $asap, $tripCompleteDetail, $additionalDetail, 'trip_cancel_reminder');
/* * ** Send push notificaion on antroid device *** */
$androidDeviceDetailArr = $this->profile->getIosNotificationStatus($driverId, DRIVER_ROLE, ANTROID);
if (is_array($androidDeviceDetailArr) && count($androidDeviceDetailArr) > 0)
foreach ($androidDeviceDetailArr as $deviceDetail) {
/* * ** Code for send push notification *** */
$deviceToken = isset($deviceDetail['devicetoken']) ? $deviceDetail['devicetoken'] : '';
$deviceToken = get_device_token($deviceToken);
if (isset($deviceToken) && !empty($deviceToken))
$androidRes = member_notification_antroid($deviceDetail['devicetoken'], $message, $rideId, $asap, $tripCompleteDetail, $additionalDetail, 'trip_cancel_reminder');
}
/* Update notification status in TBL_TRIPS_ASSIGNEDDRIVER table */
$data = array('notificationflag' => 1);
$condition = array('fkdriverid' => $driverId, 'rideid' => $rideId, 'tripstatusid' => $tripStatusId);
$updateResult = $this->common->saveDetails(TBL_TRIPS_ASSIGNEDDRIVER, $data, $condition);
/* * ** End of code for push notification *** */
}
}
}
// Send notification for trip cancelation after 35 min
foreach ($allCancelTripsdata as $canceltripsData) {
/* Time calculation */
$buggyTimeZones = array('19800' => 'Asia/Calcutta');
if (array_key_exists($canceltripsData['timezone'], $buggyTimeZones)) {
$pickUpLocationTimeZone = $buggyTimeZones[$canceltripsData['timezone']];
} else {
$pickUpLocationTimeZone = timezone_name_from_abbr('', $canceltripsData['timezone'], 0);
}
$date = new DateTime('NOW', new DateTimeZone($pickUpLocationTimeZone));
$canceltripsData['pickupdatetime'] = date('Y-m-d H:i:s', strtotime($canceltripsData['pickupdatetime'] . ' +' . CONFIRMED_CANCELLED_TRIP_FINAL . ' minutes'));
$tripDateTime = new DateTime($canceltripsData['pickupdatetime'], new DateTimeZone($pickUpLocationTimeZone));
$driverId = $canceltripsData['fkdriverid'];
$rideId = $canceltripsData['rideid'];
$asap = $canceltripsData['is_pickup_as_soon'];
$tripStatusId = TRIP_STATUS_DRIVERCONFIRMED;
//$message = 'Your trip has been cancelled because it was never started.';
$messagePassenger = 'Your trip has been cancelled because the driver did not show up to the location.';
$messageDriver = 'Your trip has been cancelled because you did not show up to the location.';
if ($date->format('U') > $tripDateTime->format('U')) {
if ($driverId > 0) {
/** ** Send push notificaion on ios *** */
$tripCompleteDetail = $this->trip->getOrderDetailForARide($rideId);
$iosDeviceDetailArrDriver = $this->profile->getIosNotificationStatus($driverId, DRIVER_ROLE, IOS);
//echo "<pre>";print_r($iosDeviceDetailArr);die(' ll');
$driverDetails = $this->profile->getDriverDetails($driverId);
$driverBUserId = $driverDetails[0]->id ? $driverDetails[0]->id : 0;
$driverCurrentUserId = $driverId;
$driverCurrentRoleId = DRIVER_ROLE;
$additionalDetailDriver = array();
$additionalDetailPassenger = array();
if (!empty($driverBUserId)) {
$additionalDetailDriver = array('bUserId' => $driverBUserId, 'currentUserId' => $driverCurrentUserId, 'currentRoleId' => $driverCurrentRoleId);
}
/* store notification detail in db start */
$dataDictionaryDriver = array(
'alert' => $messageDriver,
'ondemand' => $asap,
'ridedetail' => $tripCompleteDetail,
'rideid' => $rideId,
'type' => "trip_cancel_notification_driver",
'userdetail' => $additionalDetailDriver
);
$dataToSaveDriver = array(
'buserid' => $additionalDetailDriver['bUserId'],
'currentuserid' => $additionalDetailDriver['currentUserId'],
'currentroleid' => $additionalDetailDriver['currentRoleId'],
'datadictionary' => json_encode($dataDictionaryDriver),
'rideid' => $rideId,
'notificationlabel' => 'Trip Cancelled',
'forlisting' => 0,
'createddate' => date('Y-m-d H:i:s'),
'modifydate' => date('Y-m-d H:i:s')
);
$notificationIdDriver = $this->common->saveDetails(TBL_PUSH_NOTIFICATIONS, $dataToSaveDriver);
if ($notificationIdDriver) {
updateNotificationStatus(array('currentuserid' => $additionalDetailDriver['currentUserId'], 'rideid' => $rideId, 'notificationid !=' => $notificationIdDriver), 'trip_cancel_notification_driver');
}
$tripCompleteDetail[0]['notificationId'] = (isset($notificationIdDriver) && $notificationIdDriver) ? $notificationIdDriver : 0;
/* store notification detail in db start */
$res = member_notification_ios($iosDeviceDetailArrDriver, $messageDriver, $rideId, $asap, $tripCompleteDetail, $additionalDetailDriver, 'trip_cancel_notification_driver');
$androidDeviceDetailArrDriver = $this->profile->getIosNotificationStatus($driverId, DRIVER_ROLE, ANTROID);
if (is_array($androidDeviceDetailArrDriver) && count($androidDeviceDetailArrDriver) > 0) {
foreach ($androidDeviceDetailArrDriver as $deviceDetail) {
/* * ** Code for send push notification *** */
$deviceToken = isset($deviceDetail['devicetoken']) ? $deviceDetail['devicetoken'] : '';
$deviceToken = get_device_token($deviceToken);
if (isset($deviceToken) && !empty($deviceToken))
$androidRes = member_notification_antroid($deviceDetail['devicetoken'], $messageDriver, $rideId, $asap, $tripCompleteDetail, $additionalDetailDriver, 'trip_cancel_notification_driver');
}
}
/*********************************************************/
$iosDeviceDetailArrPassenger = $this->profile->getIosNotificationStatus($tripCompleteDetail[0]['currentuserid'], USER_ROLE, IOS);
$userRecord = $this->common->getData(TBL_USE_AS, array('use_driverfy_as' => $tripCompleteDetail[0]['currentuserid']), 'array', 'userid', 'rows');
if (!empty($userRecord)) {
$additionalDetailPassenger = array('bUserId' => $userRecord[0]['userid'], 'currentUserId' => $tripCompleteDetail[0]['currentuserid'], 'currentRoleId' => USER_ROLE);
}
$dataDictionaryPassenger = array(
'alert' => $messagePassenger,
'ondemand' => $asap,
'ridedetail' => $tripCompleteDetail,
'rideid' => $rideId,
'type' => "trip_cancel_notification_passenger",
'userdetail' => $additionalDetailPassenger
);
$dataToSavePassenger = array(
'buserid' => $additionalDetailPassenger['bUserId'],
'currentuserid' => $additionalDetailPassenger['currentUserId'],
'currentroleid' => $additionalDetailPassenger['currentRoleId'],
'datadictionary' => json_encode($dataDictionaryPassenger),
'rideid' => $rideId,
'notificationlabel' => 'Trip Cancelled',
'forlisting' => 0,
'createddate' => date('Y-m-d H:i:s'),
'modifydate' => date('Y-m-d H:i:s')
);
$notificationIdPassenger = $this->common->saveDetails(TBL_PUSH_NOTIFICATIONS, $dataToSavePassenger);
if ($notificationIdPassenger) {
updateNotificationStatus(array('currentuserid' => $additionalDetailPassenger['currentUserId'], 'rideid' => $rideId, 'notificationid !=' => $notificationIdPassenger), 'trip_cancel_notification_passenger');
}
$tripCompleteDetail[0]['notificationId'] = (isset($notificationIdPassenger) && $notificationIdPassenger) ? $notificationIdPassenger : 0;
/* store notification detail in db start */
$res = member_notification_ios($iosDeviceDetailArrPassenger, $messagePassenger, $rideId, $asap, $tripCompleteDetail, $additionalDetailPassenger, 'trip_cancel_notification_passenger', '', USER_ROLE);
die("tt");
/** ** Send push notificaion on antroid device *** */
$androidDeviceDetailArrPassenger = $this->profile->getIosNotificationStatus($tripCompleteDetail[0]['currentuserid'], USER_ROLE, ANTROID);
if (is_array($androidDeviceDetailArrPassenger) && count($androidDeviceDetailArrPassenger) > 0) {
foreach ($androidDeviceDetailArrPassenger as $deviceDetail) {
/* * ** Code for send push notification *** */
$deviceToken = isset($deviceDetail['devicetoken']) ? $deviceDetail['devicetoken'] : '';
$deviceToken = get_device_token($deviceToken);
if (isset($deviceToken) && !empty($deviceToken))
$androidRes = member_notification_antroid($deviceDetail['devicetoken'], $messagePassenger, $rideId, $asap, $tripCompleteDetail, $additionalDetailPassenger, 'trip_cancel_notification_passenger');
}
}
/* * ** End Send push notificaion on antroid device *** */
/* Update notification status in TBL_TRIPS_ASSIGNEDDRIVER table */
$cancelData = array('tripstatusid' => TRIP_STATUS_CANCEL_RUN);
$conditionCancel = array('fkdriverid' => $driverId, 'rideid' => $rideId, 'tripstatusid' => $tripStatusId);
$updateResult = $this->common->saveDetails(TBL_TRIPS_ASSIGNEDDRIVER, $cancelData, $conditionCancel);
/* * ** End of code for push notification *** */
/* Code for void authorized amount of cancel trip */
$orderResultedData = $this->common->getData(TBL_RS_ORDER, array('bookingid' => $canceltripsData['bookingid']), 'array', 'orderid');
//echo 'orderId=>'.$orderResultedData['orderid']; echo "<br/>";
$tripAuthorizationDetails = $this->common->getRowDetails(TBL_RS_ORDER_AUTHORIZATION, array('orderid' => $orderResultedData['orderid'], 'authorization_status' => 'hold', 'is_edit_charge' => 0, 'is_cancel_charge' => 0), '', 1);
//print_r($tripAuthorizationDetails);
if (count($tripAuthorizationDetails) > 0) {
foreach ($tripAuthorizationDetails as $key => $value) {
$brainTreeAuthorizationId = base64_decode($value['braintree_authorization_id']);
$orderAuthorizationId = $value['id'];
/* Here we will void all amount and maintain records in tables for future */
$this->load->library("braintreelib");
$rsltVoidSucc = $this->braintreelib->voidTransactionCustomer($brainTreeAuthorizationId);
if ($rsltVoidSucc->success) {
/* Insert records in escrow details table */
$tableName = TBL_ORDER_ESCROW_DETAIL;
$condition = array();
$dataToSave = array(
'escrow_status' => VOID_ALL_AMOUNT,
'order_id' => $orderResultedData['orderid'],
'final_trip_amount' => 0,
'created_date' => date('Y-m-d H:i:s'),
'braintree_escrow_id' => $brainTreeAuthorizationId,
'order_authorization_id' => $orderAuthorizationId
);
$insertData = $this->common->saveDetails($tableName, $dataToSave, $condition);
if ($insertData) {
$updateData = $this->common->saveDetails(TBL_RS_ORDER_AUTHORIZATION, array('authorization_status' => 'amount_void'), array('id' => $value['id']));
} else {
$this->data['status'] = faLSE;
$this->data['data'] = '';
$this->data['errorMessages'] = 'Your trip is cancel, but amount is not refund. Please contact to admin.';
}
/* End */
} else {
$errorFound = '';
foreach ($rsltVoidSucc->errors->deepAll() as $error) {
echo $errorFound = $error->message;
}
die();
}
}
}
/* End code for void authorized amount of cancel trip */
}
}
}
} catch (Exception $e) {
echo $e->getMessage() . "<br>" . $e->getFile() . "<br>" . $e->getLine();
}
}
Related
It turns out that students can actually start an exam even when the exam date is still to the future.
Normally, when a student clicks on the 'start exam' button when it's not time, there is usually a warning message but for some reason, it doesn't work again.
Students should be restricted from being able to start an exam when the date of the exam has not been reached
View
<button type="button" class="btn btn-info questions" data-recordid="<?php echo $exam->id; ?>" data-loading-text="<i class='fa fa-spinner fa-spin'></i> Please wait..."><i class="fa fa-bullhorn"></i> <?php echo $this->lang->line('start') . " " . $this->lang->line('exam') ?></button>
Teacher Controller
public function add() {
$this->form_validation->set_rules('exam', $this->lang->line('exam'), 'trim|required|xss_clean');
$this->form_validation->set_rules('attempt', $this->lang->line('attempt'), 'trim|required|xss_clean');
$this->form_validation->set_rules('exam_from', $this->lang->line('exam') . " " . $this->lang->line('from'), 'trim|required|xss_clean');
$this->form_validation->set_rules('exam_to', $this->lang->line('exam') . " " . $this->lang->line('to'), 'trim|required|xss_clean');
$this->form_validation->set_rules('duration', $this->lang->line('duration'), 'trim|required|xss_clean');
$this->form_validation->set_rules('description', $this->lang->line('description'), 'trim|required|xss_clean');
$this->form_validation->set_rules('passing_percentage', $this->lang->line('percentage'), 'trim|required|xss_clean');
if ($this->form_validation->run() == false) {
$msg = array(
'exam' => form_error('exam'),
'attempt' => form_error('attempt'),
'exam_from' => form_error('exam_from'),
'duration' => form_error('duration'),
'exam_to' => form_error('exam_to'),
'description' => form_error('description'),
'passing_percentage' => form_error('passing_percentage'),
);
$array = array('status' => 0, 'error' => $msg, 'message' => '');
} else {
$is_active = 0;
$publish_result = 0;
if (isset($_POST['is_active'])) {
$is_active = 1;
}
if (isset($_POST['publish_result'])) {
$publish_result = 1;
}
$idd = $this->session->userdata('admin');
$insert_data = array(
'exam' => $this->input->post('exam'),
'attempt' => $this->input->post('attempt'),
'exam_from' => date('Y-m-d', $this->customlib->datetostrtotime($this->input->post('exam_from'))),
'exam_to' => date('Y-m-d', $this->customlib->datetostrtotime($this->input->post('exam_to'))),
'duration' => $this->input->post('duration'),
'description' => $this->input->post('description'),
'session_id' => $this->setting_model->getCurrentSession(),
'is_active' => $is_active,
'publish_result' => $publish_result,
'passing_percentage' => $this->input->post('passing_percentage'),
'teacher_id' => $idd['id'],
);
$id = $this->input->post('recordid');
if ($id != 0) {
$insert_data['id'] = $id;
}
$this->onlineexam_model->add($insert_data);
$array = array('status' => 1, 'error' => '', 'message' => $this->lang->line('success_message'));
}
echo json_encode($array);
}
user controller
public function startexam____($id) {
$data = array();
$this->session->set_userdata('top_menu', 'Hostel');
$this->session->set_userdata('sub_menu', 'hostel/index');
$questionOpt = $this->customlib->getQuesOption();
$data['questionOpt'] = $questionOpt;
$onlineexam_question = $this->onlineexam_model->getExamQuestions($id);
$data['examquestion'] = $onlineexam_question;
$this->load->view('layout/student/header');
$this->load->view('user/onlineexam/startexam', $data);
$this->load->view('layout/student/footer');
}
public function getExamForm() {
$data = array();
$question_status = 0;
$recordid = $this->input->post('recordid');
$exam = $this->onlineexam_model->get($recordid);
$data['questions'] = $this->onlineexam_model->getExamQuestions($recordid);
$student_current_class = $this->customlib->getStudentCurrentClsSection();
$student_session_id = $student_current_class->student_session_id;
$onlineexam_student = $this->onlineexam_model->examstudentsID($student_session_id, $exam->id);
$data['onlineexam_student_id'] = $onlineexam_student;
$getStudentAttemts = $this->onlineexam_model->getStudentAttemts($onlineexam_student->id);
$data['question_status'] = 0;
if (strtotime(date('Y-m-d H:i:s')) >= strtotime(date($exam->exam_to . ' 23:59:59'))) {
$question_status = 1;
$data['question_status'] = 1;
} else if ($exam->attempt > $getStudentAttemts) {
$this->onlineexam_model->addStudentAttemts(array('onlineexam_student_id' => $onlineexam_student->id));
} else {
$question_status = 1;
$data['question_status'] = 1;
}
$questionOpt = $this->customlib->getQuesOption();
$data['questionOpt'] = $questionOpt;
$pag_content = $this->load->view('user/onlineexam/_searchQuestionByExamID', $data, true);
echo json_encode(array('status' => 0, 'exam' => $exam, 'page' => $pag_content, 'question_status' => $question_status));
}
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.
I have a problem about creating a record for attendance of an employee using DATE() and TIME() with NOW() in laravel. I have the table Attendance with column to store the record into database.
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->date('attendance_date')->nullable();
$table->string('scan_in_location')->nullable();
$table->string('scan_out_location')->nullable();
$table->time('scan_in_time')->nullable();
$table->time('scan_out_time')->nullable();
$table->time('work_hour')->nullable();
$table->time('work_hour_total')->nullable();
$table->time('lunch_break')->default('01:00:00');
$table->integer('scan_in_status')->nullable();
$table->integer('scan_out_status')->nullable();
$table->timestamps();
When the employee press CHECK IN on mobile, the record to will stored in column (user_id, scan_in_time, scan_in_location, scan_in_status) but when i only do
$attendance = new Attendance();
if ($this->user->attendance()->save($attendance))
return response()->json([
'success' => true,
'attendance' => $attendance
]);
else
return response()->json([
'success' => false,
'message' => 'Sorry, check in attendance could not be added'
], 500);
This code runs smooth with the account based on user_id. But when i press Create, i want to stored (user_id, scan_in_location, scan_in_time, scan_in_status) and this code return MariaDB version
//declare variable for taking current date - time
$user_id = request('user_id');
//check attendance using user_id
$res = Attendance::select('id')
->where('user_id' , '=' , $user_id)
->where('attendance_date', '=' , DB::RAW('DATE(NOW())'))
->where('user_id' , '!=' , null)
->where('scan_in_time', '!=' , null)
->where('scan_out_time', '=', null)->get()->count();
//set status 0 - Absent, 1 - On time, 2 - Late, 3 - very late, 4 - On leave
$attendance_status = Attendance::where('user_id', '=' , $user_id)
->select(DB::RAW("CASE WHEN TIME(NOW()) >= '08:30:00' AND TIME(NOW()) < '09:00:00' THEN '2' WHEN TIME(NOW()) > '09:00:00' THEN '3' ELSE '1'))
->value('scan_in_status');
if($res > 0){
$res = DB::RAW("UPDATE attendances SET scan_out_time = NOW(),scan_out_location = ? ,work_hour = TIMESTAMPDIFF(MINUTE, scan_in_time, scan_out_time,lunch_break), work_hour_total = TIMESTAMPDIFF(MINUTE, scan_in_time, scan_out_time) WHERE `user_id` = ? AND NOT scan_in_time IS NULL AND scan_out_time IS NULL", [$user_id, $user_id, $scan_out_location]);
return response()->json(
array(
'success' => true,
'user_id' => $user_id,
'action' => 'SCAN_OUT',
'scan_out_location' => $scan_out_location,
'date' => date('Y/m/d'),
'time' => date('H:i:s')
)
);
}else{
$res = DB::RAW("UPDATE attendances SET scan_in_time = NOW(), scan_in_location = ?, scan_in_status = ?
WHERE attendance_date = DATE(NOW()) AND `user_id` = ?", [$scan_in_location, $scan_in_status, $user_id]);
return response()->json(
array(
'success' => true,
'user_id' => $user_id,
'action' => 'SCAN_IN',
'scan_in_location' => $scan_in_location,
'date' => date('Y/m/d'),
'time' => date('H:i:s')
)
);
}
Can anyone give me some advises on this check in attendance using real time DATE(NOW()) and TIME(NOW)). Thank you.
First, get the authenticated user and then get his email-id or user id. after that on the check in button clicked get email-id or userid from button click Attendance of user will be created.
public function createAttandace(Request $req)
{
// getting authenticated userid
$Auth_userid = Auth::user()->userid;
// current year
$curr_year = Carbon::now()->format('Y');
// current month
$curr_month = Carbon::now()->format('F');
// current date
// $curr_date = date('d-m-Y ');
$curr_date = date('Y-m-d H:i:s');
// current day in string
$curr_day = Carbon::parse($curr_date)->format('l');
// current time
$curr_time = Carbon::now()->timezone('Asia/Kolkata')->format('H:i:s');
$lastId = DB::table('attandances')->orderBy('id', 'desc')->first();
$next_day = date('Y-m-d', strtotime(' +1 day'));
$prev_day = date('Y-m-d', strtotime(' -1 day'));
$curr_dateymd = date('Y-m-d');
$office_time = '9:0:0';
$isData = Attandance::where('userid', $Auth_userid)->where('att_date', $curr_dateymd)->get();
if ($isData->isEmpty()) {
$req->validate(
[
'email' => 'required|max:25',
],
[
'email.required' => 'Please enter email id!',
]
);
if($curr_time <= $office_time)
{
$user_attandace = new Attandance;
$user_attandace->userid = $Auth_userid;
$user_attandace->email = $req->email;
$user_attandace->year = $curr_year;
$user_attandace->month = $curr_month;
$user_attandace->att_date = $curr_date;
$user_attandace->att_day = $curr_day;
// $user_attandace->holiday = '-';
$user_attandace->in_time = $curr_time;
$user_attandace->save();
$success['email'] = $user_attandace->email;
$success['in_time'] = $user_attandace->in_time;
$response = [
'success' => true,
'status_code' => '201',
'data' => $success,
'message' => 'Attandance added successfully!!'
];
// in time email message
$fName = Auth::user()->first_name;
$lName = Auth::user()->last_name;
$fullName = $fName . ' ' . $lName;
$toMail = $success['email'];
$mailInTime = $success['in_time'];
$email = your#mail.com';
$someOthermail = 'test#gmail.com';
$details = [
'subject' => $fullName .' checked-in to the office on ' . $curr_date,
'title' => 'Congrats, you are on time. Keep it up!',
];
Mail::to($toMail)->bcc($someOthermail)->send(new attMail($details));
// in time email message
return response()->json($response, 201);
}else{
$user_attandace = new Attandance;
$user_attandace->userid = $Auth_userid;
$user_attandace->email = $req->email;
$user_attandace->year = $curr_year;
$user_attandace->month = $curr_month;
$user_attandace->att_date = $curr_date;
$user_attandace->att_day = $curr_day;
$user_attandace->att_status = 'Late';
$user_attandace->is_late = 1;
$user_attandace->in_time = $curr_time;
$user_attandace->save();
$success['email'] = $user_attandace->email;
$success['in_time'] = $user_attandace->in_time;
$response = [
'success' => true,
'status_code' => '201',
'data' => $success,
'message' => 'Attandance added successfully!!',
'late_message' => "Oops, you are late today. We hope that next time, you make it on time. Please take it on priority."
];
// in time email message
$fName = Auth::user()->first_name;
$lName = Auth::user()->last_name;
$fullName = $fName . ' ' . $lName;
$toMail = $success['email'];
$mailInTime = $success['in_time'];
$email = your#mail.com';
$someOthermail = 'test#gmail.com';
$details = [
'subject' => $fullName .' checked-in to the office on ' . $curr_date,
'title' => 'Oops, you are late today. We hope that next time, you make it on time. Please take it on priority.',
];
Mail::to($toMail)->bcc($someOthermail)->send(new attMail($details));
// in time email message
return response()->json($response, 201);
}
} elseif ($lastId->in_time != null) {
// dd();
$curr_dateymd = date('Y-m-d');
$curr_time = Carbon::now()->timezone('Asia/Kolkata')->format('H:i:s');
$in_time = new Carbon($lastId->in_time);
$out_time = new Carbon($curr_time);
$difff = $in_time->diff($out_time)->format('%H hr : %I min');
$success = DB::table('attandances')->where(['userid' => $Auth_userid])->update(['out_time' => $curr_time]);
$updateTotalHour = DB::table('attandances')->where(['userid' => $Auth_userid])->where(['att_date' => $curr_dateymd])->update(['total_hours' => $difff]);
$successData = Attandance::where('userid', $Auth_userid)->where('att_date', $curr_dateymd)->get();
$response = [
'success' => true,
'status_code' => '201',
'data' => $successData,
'message' => 'Attandance Punched successfully!!'
];
// Out time email message
$fName = Auth::user()->first_name;
$lName = Auth::user()->last_name;
$email = Auth::user()->email;
$fullName = $fName . ' '. $lName;
$toMail = $email;
$email = your#mail.com';
$someOthermail = 'test#gmail.com';
$details = [
'subject' => $fullName .' checked-out from the office on ' . $curr_dateymd . $curr_time,
'title' => $fullName .' checked-out from the office on ' . $curr_dateymd . $curr_time,
];
Mail::to($toMail)->bcc($someOthermail)->send(new attMail($details));
// dd("Mail Send Successfully");
// Out time email message
return response()->json($response, 201);
} else {
echo 'Nothing';
}
}
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. :)
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;
}