Example #1
0
 /**
  * Check if booking time is still available
  * Return TRUE if time is available
  *
  * @return bool
  */
 public function checkBookingTime()
 {
     /** @var WPDB $wpdb */
     global $wpdb;
     $booked_datetime = $this->userData->get('appointment_datetime');
     $endDate = new DateTime($booked_datetime);
     $endDate->modify("+ {$this->userData->getService()->get('duration')} sec");
     $query = $wpdb->prepare("SELECT `a`.*, `ss`.`capacity`, SUM(`ca`.`number_of_persons`) AS `total_number_of_persons`\n                FROM `" . AB_CustomerAppointment::getTableName() . "` `ca`\n                LEFT JOIN `" . AB_Appointment::getTableName() . "`   `a`  ON `a`.`id` = `ca`.`appointment_id`\n                LEFT JOIN `" . AB_StaffService::getTableName() . "` `ss` ON `ss`.`staff_id` = `a`.`staff_id` AND `ss`.`service_id` = `a`.`service_id`\n                WHERE `a`.`staff_id` = %d\n                GROUP BY `a`.`start_date` , `a`.`staff_id` , `a`.`service_id`\n                HAVING\n                      (`a`.`start_date` = %s AND `service_id` =  %d AND `total_number_of_persons` >= `capacity`) OR\n                      (`a`.`start_date` = %s AND `service_id` <> %d) OR\n                      (`a`.`start_date` > %s AND `a`.`end_date` <= %s) OR\n                      (`a`.`start_date` < %s AND `a`.`end_date` > %s) OR\n                      (`a`.`start_date` < %s AND `a`.`end_date` > %s)\n                LIMIT 1", $this->userData->getStaffId(), $booked_datetime, $this->userData->get('service_id'), $booked_datetime, $this->userData->get('service_id'), $booked_datetime, $endDate->format('Y-m-d H:i:s'), $endDate->format('Y-m-d H:i:s'), $endDate->format('Y-m-d H:i:s'), $booked_datetime, $booked_datetime);
     return !(bool) $wpdb->get_row($query);
 }
 /**
  * Get service prices of every staff member.
  *
  * @return array
  */
 private function _getPrices()
 {
     /** @var WPDB $wpdb */
     global $wpdb;
     $result = array();
     $rows = $wpdb->get_results($wpdb->prepare("SELECT * FROM `ab_staff_service` WHERE `staff_id` IN ({$this->_staffIdsStr}) AND `service_id` = %d", $this->_userData->getServiceId()));
     if (is_array($rows)) {
         foreach ($rows as $row) {
             $result[$row->staff_id] = $row->price;
         }
     }
     return $result;
 }
 /**
  * Do AIM payment.
  */
 public function executeAuthorizeNetAIM()
 {
     include_once AB_PATH . '/lib/payment/authorize.net/autoload.php';
     $response = null;
     $userData = new AB_UserBookingData($this->getParameter('form_id'));
     if ($userData->load()) {
         define("AUTHORIZENET_API_LOGIN_ID", get_option('ab_authorizenet_api_login_id'));
         define("AUTHORIZENET_TRANSACTION_KEY", get_option('ab_authorizenet_transaction_key'));
         define("AUTHORIZENET_SANDBOX", (bool) get_option('ab_authorizenet_sandbox'));
         $price = $userData->getFinalServicePrice() * $userData->get('number_of_persons');
         $sale = new AuthorizeNetAIM();
         $sale->amount = $price;
         $sale->card_num = $this->getParameter('ab_card_number');
         $sale->card_code = $this->getParameter('ab_card_code');
         $sale->exp_date = $this->getParameter('ab_card_month') . '/' . $this->getParameter('ab_card_year');
         $sale->first_name = $userData->get('name');
         $sale->email = $userData->get('email');
         $sale->phone = $userData->get('phone');
         $response = $sale->authorizeAndCapture();
         if ($response->approved) {
             /** @var AB_Appointment $appointment */
             $appointment = $userData->save();
             $customer_appointment = new AB_CustomerAppointment();
             $customer_appointment->loadBy(array('appointment_id' => $appointment->get('id'), 'customer_id' => $userData->getCustomerId()));
             $payment = new AB_Payment();
             $payment->set('total', $price);
             $payment->set('type', 'authorizeNet');
             $payment->set('customer_appointment_id', $customer_appointment->get('id'));
             $payment->set('created', current_time('mysql'));
             $payment->save();
             $response = array('state' => 'success');
         } else {
             $response = array('status' => 'error', 'error' => $response->response_reason_text);
         }
     } else {
         $response = array('status' => 'error', 'error' => __('Session error.', 'bookly'));
     }
     wp_send_json($response);
 }
 public function executeStripe()
 {
     $response = null;
     $userData = new AB_UserBookingData($this->getParameter('form_id'));
     if ($userData->load()) {
         if ($userData->get('service_id')) {
             Stripe::setApiKey(get_option('ab_stripe_secret_key'));
             Stripe::setApiVersion("2014-10-07");
             $price = $userData->getFinalServicePrice() * $userData->get('number_of_persons');
             $stripe_data = array('number' => $this->getParameter('ab_card_number'), 'exp_month' => $this->getParameter('ab_card_month'), 'exp_year' => $this->getParameter('ab_card_year'), 'cvc' => $this->getParameter('ab_card_code'));
             try {
                 $charge = Stripe_Charge::create(array('card' => $stripe_data, 'amount' => intval($price * 100), 'currency' => get_option('ab_paypal_currency'), 'description' => "Charge for " . $userData->get('email')));
                 if ($charge->paid) {
                     $appointment = $userData->save();
                     $customer_appointment = new AB_CustomerAppointment();
                     $customer_appointment->loadBy(array('appointment_id' => $appointment->get('id'), 'customer_id' => $userData->getCustomerId()));
                     $payment = new AB_Payment();
                     $payment->set('total', $price);
                     $payment->set('type', 'stripe');
                     $payment->set('customer_appointment_id', $customer_appointment->get('id'));
                     $payment->set('created', current_time('mysql'));
                     $payment->save();
                     $response = array('status' => 'success');
                 } else {
                     $response = array('status' => 'error', 'error' => 'unknown error');
                 }
             } catch (Exception $e) {
                 $response = array('status' => 'error', 'error' => $e->getMessage());
             }
         }
     } else {
         $response = array('status' => 'error', 'error' => __('Session error.', 'bookly'));
     }
     // Output JSON response.
     wp_send_json($response);
 }
 /**
  * Render info text into a variable.
  *
  * @param string $text
  * @param AB_UserBookingData $userData
  * @param int $preset_price
  *
  * @return string
  */
 private function _prepareInfoText($text, $userData, $preset_price = null)
 {
     if (empty($this->replacement)) {
         $service = $userData->getService();
         $category_name = $service->getCategoryName();
         $staff_name = $userData->getStaffName();
         $price = $preset_price === null ? $userData->getServicePrice() : $preset_price;
         $number_of_persons = $userData->get('number_of_persons');
         $service_date = AB_DateTimeUtils::formatDate($userData->get('appointment_datetime'));
         if (get_option('ab_settings_use_client_time_zone')) {
             $service_time = AB_DateTimeUtils::formatTime(AB_DateTimeUtils::applyTimeZoneOffset($userData->get('appointment_datetime'), $userData->get('time_zone_offset')));
         } else {
             $service_time = AB_DateTimeUtils::formatTime($userData->get('appointment_datetime'));
         }
         $this->replacement = array('[[STAFF_NAME]]' => '<b>' . $staff_name . '</b>', '[[SERVICE_NAME]]' => '<b>' . $service->get('title') . '</b>', '[[CATEGORY_NAME]]' => '<b>' . $category_name . '</b>', '[[NUMBER_OF_PERSONS]]' => '<b>' . $number_of_persons . '</b>', '[[SERVICE_TIME]]' => '<b>' . $service_time . '</b>', '[[SERVICE_DATE]]' => '<b>' . $service_date . '</b>', '[[SERVICE_PRICE]]' => '<b>' . AB_Utils::formatPrice($price) . '</b>', '[[TOTAL_PRICE]]' => '<b>' . AB_Utils::formatPrice($price * $number_of_persons) . '</b>', '[[LOGIN_FORM]]' => get_current_user_id() == 0 ? $this->render('_login_form', array(), false) : '');
     }
     return strtr(nl2br($text), $this->replacement);
 }
 /**
  * Process the Express Checkout RETURNURL
  */
 public function paypalResponseSuccess()
 {
     $form_id = $_GET['ab_fid'];
     $paypal = new AB_PayPal();
     if (isset($_GET["token"]) && isset($_GET["PayerID"])) {
         $token = $_GET["token"];
         $payer_id = $_GET["PayerID"];
         // send the request to PayPal
         $response = $paypal->sendNvpRequest('GetExpressCheckoutDetails', sprintf('&TOKEN=%s', $token));
         if (strtoupper($response["ACK"]) == "SUCCESS") {
             $data = sprintf('&TOKEN=%s&PAYERID=%s&PAYMENTREQUEST_0_PAYMENTACTION=Sale', $token, $payer_id);
             // response keys containing useful data to send via DoExpressCheckoutPayment operation
             $response_data_keys_pattern = sprintf('/^(%s)/', implode('|', array('PAYMENTREQUEST_0_AMT', 'PAYMENTREQUEST_0_ITEMAMT', 'PAYMENTREQUEST_0_CURRENCYCODE', 'L_PAYMENTREQUEST_0')));
             foreach ($response as $key => $value) {
                 // collect product data from response using defined response keys
                 if (preg_match($response_data_keys_pattern, $key)) {
                     $data .= sprintf('&%s=%s', $key, $value);
                 }
             }
             //We need to execute the "DoExpressCheckoutPayment" at this point to Receive payment from user.
             $response = $paypal->sendNvpRequest('DoExpressCheckoutPayment', $data);
             if ("SUCCESS" == strtoupper($response["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($response["ACK"])) {
                 // get transaction info
                 $response = $paypal->sendNvpRequest('GetTransactionDetails', "&TRANSACTIONID=" . urlencode($response["PAYMENTINFO_0_TRANSACTIONID"]));
                 if ("SUCCESS" == strtoupper($response["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($response["ACK"])) {
                     // need session to get Total and Token
                     $token = $_SESSION['bookly'][$form_id]['paypal_response'][0]['TOKEN'];
                     $userData = new AB_UserBookingData($form_id);
                     $userData->load();
                     if ($userData->get('service_id')) {
                         $appointment = $userData->save();
                         $customer_appointment = new AB_CustomerAppointment();
                         $customer_appointment->loadBy(array('appointment_id' => $appointment->get('id'), 'customer_id' => $userData->getCustomerId()));
                         $payment = new AB_Payment();
                         $payment->set('token', urldecode($token));
                         $payment->set('total', $userData->getFinalServicePrice() * $userData->get('number_of_persons'));
                         $payment->set('customer_appointment_id', $customer_appointment->get('id'));
                         $payment->set('transaction', urlencode($response["TRANSACTIONID"]));
                         $payment->set('created', current_time('mysql'));
                         $payment->save();
                         $userData->setPayPalStatus('success');
                     }
                     @wp_redirect(remove_query_arg(array('action', 'token', 'PayerID', 'ab_fid'), AB_Utils::getCurrentPageURL()));
                     exit(0);
                 } else {
                     header('Location: ' . wp_sanitize_redirect(add_query_arg(array('action' => 'ab-paypal-errorurl', 'ab_fid' => $form_id, 'error_msg' => $response["L_LONGMESSAGE0"]), AB_Utils::getCurrentPageURL())));
                     exit;
                 }
             } else {
                 header('Location: ' . wp_sanitize_redirect(add_query_arg(array('action' => 'ab-paypal-errorurl', 'ab_fid' => $form_id, 'error_msg' => $response["L_LONGMESSAGE0"]), AB_Utils::getCurrentPageURL())));
                 exit;
             }
         } else {
             header('Location: ' . wp_sanitize_redirect(add_query_arg(array('action' => 'ab-paypal-errorurl', 'ab_fid' => $form_id, 'error_msg' => 'Invalid token provided'), AB_Utils::getCurrentPageURL())));
             exit;
         }
     } else {
         throw new Exception('Token parameter not found!');
     }
 }
 /**
  * Add product to cart
  *
  * @return string JSON
  */
 public function executeAddToWoocommerceCart()
 {
     if (!get_option('ab_woocommerce')) {
         exit(0);
     }
     $response = null;
     $userData = new AB_UserBookingData($this->getParameter('form_id'));
     if ($userData->load()) {
         $session = WC()->session;
         /** @var WC_Session_Handler $session */
         if ($session instanceof WC_Session_Handler and $session->get_session_cookie() === false) {
             $session->set_customer_session_cookie(true);
         }
         WC()->cart->add_to_cart($this->product_id, $userData->get('number_of_persons'), '', array(), array('bookly' => $userData->getData()));
         $response = array('status' => 'success');
     } else {
         $response = array('status' => 'error', 'error' => __('Session error.', 'bookly'));
     }
     // Output JSON response.
     wp_send_json($response);
 }
 /**
  * Render info text into a variable.
  *
  * @param int $booking_step
  * @param AB_UserBookingData $userData
  * @param int $preset_price
  *
  * @return string
  */
 private function _prepareInfoText($booking_step, $userData, $preset_price = null)
 {
     if ($userData->hasData()) {
         $service_name = $userData->getServiceName();
         $category_name = $userData->getCategoryName();
         $staff_name = $userData->getStaffName();
         $price = $preset_price === null ? $userData->getServicePrice() : $preset_price;
         // Convenient Time
         if ($booking_step === 2) {
             $replacement = array('[[STAFF_NAME]]' => '<b>' . $staff_name . '</b>', '[[SERVICE_NAME]]' => '<b>' . $service_name . '</b>', '[[CATEGORY_NAME]]' => '<b>' . $category_name . '</b>');
             return str_replace(array_keys($replacement), array_values($replacement), nl2br(esc_html(get_option('ab_appearance_text_info_second_step'))));
         }
         // Your Details
         if ($booking_step === 3) {
             if (get_option('ab_settings_use_client_time_zone') && $this->getParameter('client_time_zone_offset')) {
                 $service_time = date_i18n(get_option('time_format'), strtotime($userData->getBookedDatetime()) - ($this->getParameter('client_time_zone_offset') + get_option('gmt_offset') * 60) * 60);
             } else {
                 $service_time = date_i18n(get_option('time_format'), strtotime($userData->getBookedDatetime()));
             }
             $service_date = date_i18n(get_option('date_format'), strtotime($userData->getBookedDatetime()));
             $replacement = array('[[STAFF_NAME]]' => '<b>' . $staff_name . '</b>', '[[SERVICE_NAME]]' => '<b>' . $service_name . '</b>', '[[CATEGORY_NAME]]' => '<b>' . $category_name . '</b>', '[[SERVICE_TIME]]' => '<b>' . $service_time . '</b>', '[[SERVICE_DATE]]' => '<b>' . $service_date . '</b>', '[[SERVICE_PRICE]]' => '<b>' . AB_CommonUtils::formatPrice($price) . '</b>');
             return str_replace(array_keys($replacement), array_values($replacement), nl2br(esc_html(get_option('ab_appearance_text_info_third_step'))));
         }
         // Coupon Text
         if ($booking_step === 4) {
             $replacement = array('[[SERVICE_PRICE]]' => '<b>' . AB_CommonUtils::formatPrice($price) . '</b>');
             return str_replace(array_keys($replacement), array_values($replacement), nl2br(esc_html(get_option('ab_appearance_text_info_coupon'))));
         }
     }
     return '';
 }