/**
  * 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);
 }
Beispiel #3
0
 /**
  * Set array of customers associated with this appointment.
  *
  * @param array $data  Array of customer IDs, custom_fields and number_of_persons
  */
 public function setCustomers(array $data)
 {
     // Prepare array of customers.
     $customers = array();
     foreach ($data as $customer) {
         $customers[$customer['id']] = $customer;
     }
     // Retrieve customer IDs currently associated with this appointment.
     $current_ids = array_map(function ($ca) {
         return $ca->customer->get('id');
     }, $this->getCustomerAppointments());
     // Remove redundant customers.
     $customer_appointment = new AB_CustomerAppointment();
     foreach (array_diff($current_ids, array_keys($customers)) as $id) {
         if ($customer_appointment->loadBy(array('appointment_id' => $this->get('id'), 'customer_id' => $id))) {
             $customer_appointment->delete();
         }
     }
     // Add new customers.
     foreach (array_diff(array_keys($customers), $current_ids) as $id) {
         $customer_appointment = new AB_CustomerAppointment();
         $customer_appointment->set('appointment_id', $this->get('id'));
         $customer_appointment->set('customer_id', $id);
         $customer_appointment->set('custom_fields', json_encode($customers[$id]['custom_fields']));
         $customer_appointment->set('number_of_persons', $customers[$id]['number_of_persons']);
         $customer_appointment->save();
     }
     // Update existing customers.
     foreach (array_intersect($current_ids, array_keys($customers)) as $id) {
         $customer_appointment = new AB_CustomerAppointment();
         $customer_appointment->loadBy(array('appointment_id' => $this->get('id'), 'customer_id' => $id));
         $customer_appointment->set('custom_fields', json_encode($customers[$id]['custom_fields']));
         $customer_appointment->set('number_of_persons', $customers[$id]['number_of_persons']);
         $customer_appointment->save();
     }
 }
 /**
  * Save all data and create appointment.
  *
  * @return AB_Appointment
  */
 public function save()
 {
     $user_id = get_current_user_id();
     $customer = new AB_Customer();
     if ($user_id) {
         // Try to find customer by WP user ID.
         $customer->loadBy(array('wp_user_id' => $user_id));
     }
     if (!$customer->isLoaded()) {
         // If customer with such name & e-mail exists, append new booking to him, otherwise - create new customer
         $customer->loadBy(array('name' => $this->get('name'), 'email' => $this->get('email')));
     }
     $customer->set('name', $this->get('name'));
     $customer->set('email', $this->get('email'));
     $customer->set('phone', $this->get('phone'));
     if (get_option('ab_settings_create_account', 0) && !$customer->get('wp_user_id')) {
         // Create WP user and link it to customer.
         $customer->setWPUser($user_id ?: null);
     }
     $customer->save();
     $this->customer_id = $customer->get('id');
     $service = $this->getService();
     /**
      * Get appointment, with same params.
      * If it is -> create connection to this appointment,
      * otherwise create appointment and connect customer to new appointment
      */
     $appointment = new AB_Appointment();
     $appointment->loadBy(array('staff_id' => $this->getStaffId(), 'service_id' => $this->get('service_id'), 'start_date' => $this->get('appointment_datetime')));
     if ($appointment->isLoaded() == false) {
         $appointment->set('staff_id', $this->getStaffId());
         $appointment->set('service_id', $this->get('service_id'));
         $appointment->set('start_date', $this->get('appointment_datetime'));
         $endDate = new DateTime($this->get('appointment_datetime'));
         $di = "+ {$service->get('duration')} sec";
         $endDate->modify($di);
         $appointment->set('end_date', $endDate->format('Y-m-d H:i:s'));
         $appointment->save();
     }
     $customer_appointment = new AB_CustomerAppointment();
     $customer_appointment->loadBy(array('customer_id' => $customer->get('id'), 'appointment_id' => $appointment->get('id')));
     if ($customer_appointment->isLoaded()) {
         // Add number of persons to existing booking.
         $customer_appointment->set('number_of_persons', $customer_appointment->get('number_of_persons') + $this->get('number_of_persons'));
     } else {
         $customer_appointment->set('customer_id', $customer->get('id'));
         $customer_appointment->set('appointment_id', $appointment->get('id'));
         $customer_appointment->set('number_of_persons', $this->get('number_of_persons'));
     }
     $customer_appointment->set('custom_fields', $this->get('custom_fields'));
     $customer_appointment->set('time_zone_offset', $this->get('time_zone_offset'));
     $coupon = $this->getCoupon();
     if ($coupon) {
         $customer_appointment->set('coupon_code', $coupon->get('code'));
         $customer_appointment->set('coupon_discount', $coupon->get('discount'));
         $customer_appointment->set('coupon_deduction', $coupon->get('deduction'));
         $coupon->claim();
         $coupon->save();
     }
     $customer_appointment->save();
     // Create fake payment record for 100% discount coupons.
     if ($coupon && $coupon->get('discount') == '100') {
         $payment = new AB_Payment();
         $payment->set('total', '0.00');
         $payment->set('type', 'coupon');
         $payment->set('created', current_time('mysql'));
         $payment->set('customer_appointment_id', $customer_appointment->get('id'));
         $payment->save();
     }
     // Google Calendar.
     $appointment->handleGoogleCalendar();
     // Send email notifications.
     AB_NotificationSender::send(AB_NotificationSender::INSTANT_NEW_APPOINTMENT, $customer_appointment);
     return $appointment;
 }
 /**
  * Cancel Appointment using token.
  */
 public function executeCancelAppointment()
 {
     $customer_appointment = new AB_CustomerAppointment();
     if ($customer_appointment->loadBy(array('token' => $this->getParameter('token')))) {
         // Send email.
         AB_NotificationSender::send(AB_NotificationSender::INSTANT_CANCELLED_APPOINTMENT, $customer_appointment);
         $customer_appointment->delete();
         $appointment = new AB_Appointment();
         $appointment->load($customer_appointment->get('appointment_id'));
         // Delete appointment, if there aren't customers.
         $count = AB_CustomerAppointment::query('ca')->where('ca.appointment_id', $customer_appointment->get('appointment_id'))->count();
         if (!$count) {
             $appointment->delete();
         } else {
             $appointment->handleGoogleCalendar();
         }
         if ($this->url = get_option('ab_settings_cancel_page_url')) {
             wp_redirect($this->url);
             $this->render('cancel_appointment');
             exit(0);
         }
     }
     $this->url = home_url();
     if (isset($_SERVER['HTTP_REFERER'])) {
         if (parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST) == parse_url($this->url, PHP_URL_HOST)) {
             // Redirect back if user came from our site.
             $this->url = $_SERVER['HTTP_REFERER'];
         }
     }
     wp_redirect($this->url);
     $this->render('cancel_appointment');
     exit(0);
 }
 /**
  * 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!');
     }
 }