get_user_id() public method

Alias for get_customer_id().
public get_user_id ( string $context = 'view' ) : integer
$context string
return integer
Exemplo n.º 1
0
 public static function get_role_price($product)
 {
     global $post, $woocommerce;
     if (is_admin()) {
         //admin screen
         if (!empty($_POST['selected_user_id'])) {
             $user = get_user_by('id', $_POST['selected_user_id']);
         } else {
             //!empty($_POST['order_id'])
             $order = new WC_Order($_POST['order_id']);
             $user_id = $order->get_user_id();
             $user = get_user_by('id', $user_id);
         }
     } else {
         // user screen
         $user = wp_get_current_user();
     }
     $user_roles = $user->roles;
     if ($user_roles == null) {
         return null;
     }
     $user_role = array_shift($user_roles);
     if ($user_role !== null) {
         $role_price = get_post_meta($product->variation_id, $user_role, true);
         if (!empty($role_price)) {
             return $role_price;
         }
     }
     return null;
 }
 /**
  * Get the user ID for an order
  *
  * @since 3.0.0
  * @param \WC_Order $order
  * @return int
  */
 public static function get_order_user_id(WC_Order $order)
 {
     if (self::is_wc_version_gte_2_2()) {
         return $order->get_user_id();
     } else {
         return $order->customer_user ? $order->customer_user : 0;
     }
 }
 /**
  * Helper method to return required profile data when working with customer profiles
  *
  * @since 2.0.0
  * @param WC_Order $order the order object
  * @param array $additional_data optional additional data to be set, like payment profile data
  * @return array profile data
  */
 protected function get_profile_data(WC_Order $order, $additional_data = array())
 {
     $data = array('merchantCustomerId' => $order->get_user_id(), 'email' => is_email($this->order->billing_email) ? $this->order->billing_email : '');
     if ($additional_data) {
         $data = array_merge($data, $additional_data);
     }
     return $data;
 }
function sendCustomerInvoice($order_id)
{
    PlexLog::addLog(' Info =>@sendCustomerInvoice order_id=' . $order_id);
    $wooCommerceOrderObject = new WC_Order($order_id);
    $user_id = $wooCommerceOrderObject->get_user_id();
    $customerMailId = $wooCommerceOrderObject->billing_email;
    $invoice_mail_content = '';
    $invoice_mail_content .= '
	<table border="0" cellpadding="0" cellspacing="0" width="600" id="template_container">
		<tbody>
			<tr>
				<td align="center" valign="top">
					<font face="Arial" style="font-weight:bold;background-color:#8fd1c8;color:#202020;"></font>
					<table border="0" cellpadding="0" cellspacing="0" width="600" id="template_header" bgcolor="#8fd1c8">
						<tbody>
							<tr >
					            <td width="20" height="20"  bgcolor="#8fd1c8">&nbsp;</td>
					            <td bgcolor="#8fd1c8">&nbsp;</td>
					            <td width="20" bgcolor="#8fd1c8">&nbsp;</td>
					        </tr>
					        <tr >
					            <td width="20"  bgcolor="#8fd1c8">&nbsp;</td>
					            <td bgcolor="#8fd1c8" style="font-weight:bold;font-size:24px;color:#ffffff;" ><h2 style="margin:0;">Welcome to ' . get_option('blogname') . '! <br>Thank you for your order. We\'ll be in touch shortly with additional order and shipping information.</h2></td>
					            <td width="20" bgcolor="#8fd1c8">&nbsp;</td>
					        </tr>
					        <tr >
					            <td width="20" height="20"  bgcolor="#8fd1c8">&nbsp;</td>
					            <td bgcolor="#8fd1c8">&nbsp;</td>
					            <td width="20" bgcolor="#8fd1c8">&nbsp;</td>
					        </tr>
                        </tbody>
                    </table>
                </td>
            </tr>
            <tr>
            	<td align="center" valign="top">
            		<table border="0" cellpadding="0" cellspacing="0" width="600" id="template_body">
            			<tbody>
            				<tr>
            					<td valign="top">
            						<font style="background-color:#f9f9f9">
            							<table border="0" cellpadding="20" cellspacing="0" width="100%">
            								<tbody>
            									<tr>
	            									<td valign="top">
	            										<div>
	            											<font face="Arial" align="left" style="font-size:18px;color:#8a8a8a">
	            												<p>Your order #' . get_post_meta($order_id, "plexOrderId", true) . ' has been received and is now being processed. Your order details are shown below for your reference:</p>
																<table cellspacing="0" cellpadding="6" border="1" style="width:100%;">
																	<thead>
																		<tr>
																			<th scope="col">
																				<font align="left">Product</font>
																			</th>
																			<th scope="col">
																				<font align="left">Quantity</font>
																			</th>
																			<th scope="col">
																				<font align="left">Price</font>
																			</th>
																		</tr>
																	</thead>
																	<tbody>';
    $allItems = $wooCommerceOrderObject->get_items();
    foreach ($allItems as $key => $value) {
        $invoice_mail_content .= '
																				<tr>
																					<td>
																						<font align="left">' . $value["name"] . '<br><small></small></font>
																					</td>
																					<td>
																						<font align="left">' . $value["qty"] . '</font>
																					</td>
																					<td>
																						<font align="left">
																							<span class="amount">$' . $value["line_subtotal"] . '</span>
																						</font>
																					</td>
																				</tr>';
    }
    $invoice_mail_content .= '																		
																	</tbody>
																	<tfoot style="text-align: left;">
																		<tr>
																			<th scope="row" colspan="2">
																				<font align="left">Cart Subtotal:</font>
																			</th>
																			<td>
																				<font align="left">
																					<span class="amount">$' . sprintf('%0.2f', $wooCommerceOrderObject->get_subtotal()) . '</span>
																				</font>
																			</td>
																		</tr>';
    if ($wooCommerceOrderObject->get_total_discount() > 0.0) {
        $invoice_mail_content .= '<tr>
																			<th scope="row" colspan="2">
																				<font align="left">Discount:</font>
																			</th>
																			<td>
																				<font align="left">
																					<span class="amount">$' . sprintf('%0.2f', $wooCommerceOrderObject->get_total_discount()) . '</span>
																				</font>
																			</td>
																		</tr>';
    }
    $invoice_mail_content .= '<tr>
																			<th scope="row" colspan="2">
																				<font align="left">Tax:</font>
																			</th>
																			<td>
																				<font align="left">
																					<span class="amount">$' . sprintf('%0.2f', $wooCommerceOrderObject->get_cart_tax() + $wooCommerceOrderObject->get_shipping_tax()) . '</span>
																				</font>
																			</td>
																		</tr>
																		<tr>
																			<th scope="row" colspan="2">
																				<font align="left">Shipping:</font>
																			</th>
																			<td>
																				<font align="left">
																					<span class="amount">$' . $wooCommerceOrderObject->get_total_shipping() . '</span>&nbsp;<small>via ' . $wooCommerceOrderObject->get_shipping_method() . '</small>
																				</font>
																			</td>
																		</tr>
																		<tr>
																			<th scope="row" colspan="2">
																				<font align="left">Payment Method:</font>
																			</th>
																			<td>
																				<font align="left">' . $wooCommerceOrderObject->payment_method_title . '</font>
																			</td>
																		</tr>
																		<tr>
																			<th scope="row" colspan="2">
																				<font align="left">Order Total:</font>
																			</th>
																			<td>
																				<font align="left">
																					<span class="amount">$' . sprintf('%0.2f', $wooCommerceOrderObject->get_total()) . '</span>
																				</font>
																			</td>
																		</tr>
																	</tfoot>
																</table>
																<h2>
																	<font face="Arial" align="left" style="font-weight:bold;font-size:30px;color:#6d6d6d">Customer details</font>
																</h2>
																<p><strong>Email:</strong> ' . $customerMailId . '</p>
																<p><strong>Tel:</strong> ' . $wooCommerceOrderObject->billing_phone . '</p>
																<table cellspacing="0" cellpadding="0" border="0">
																	<tbody>
																		<tr>
																			<td valign="top" width="50%">
																				<h3>
																					<font face="Arial" align="left" style="font-weight:bold;font-size:26px;color:#6d6d6d">Billing address</font>
																				</h3>
																				<p>' . $wooCommerceOrderObject->get_formatted_billing_address() . '</p>

																			</td>
																			<td valign="top" width="50%">
																				<h3>
																					<font face="Arial" align="left" style="font-weight:bold;font-size:26px;color:#6d6d6d">Shipping address</font>
																				</h3>
																				<p>' . $wooCommerceOrderObject->get_formatted_shipping_address() . '</p>
																			</td>
																		</tr>
																	</tbody>
																</table>
															</font>
														</div>
													</td>
												</tr>
											</tbody>
										</table>
									</font>
								</td>
							</tr>
						</tbody>
					</table>
				</td>
			</tr>
			<tr>
				<td align="center" valign="top">
					<table border="0" cellpadding="10" cellspacing="0" width="600" id="template_footer">
						<tbody>
							<tr>
								<td valign="top">
	                                <table border="0" cellpadding="4" cellspacing="0" width="100%">
	                                	<tbody>
	                                		<tr>
	                                			<td colspan="2" valign="middle" id="credit" style="background-color: #777;">
	                                				<font face="Arial" align="center" style="font-size:12px;color:#bce3de">
	                                					<p>' . site_url() . '</p>
	                                                </font>
	                                            </td>
	                                        </tr>
	                                    </tbody>
	                                </table>
	                            </td>
	                        </tr>
	                    </tbody>
	                </table>
	            </td>
	        </tr>
	    </tbody>
	</table>';
    $emailHeader = "Content-type: text/html";
    // To send HTML mail, the Content-type header must be set
    $emailHeader = 'MIME-Version: 1.0' . "\r\n";
    $emailHeader .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
    // Additional emailHeader
    $emailHeader .= 'From: ' . get_bloginfo('name') . ' <*****@*****.**>' . "\r\n";
    $emailSubject = "Your plexuser order receipt from " . date_i18n(wc_date_format(), strtotime($wooCommerceOrderObject->order_date));
    wp_mail($customerMailId, $emailSubject, $invoice_mail_content, $emailHeader);
}
 /**
  * Render the payment method used for a subscription in the "My Subscriptions" table
  *
  * @since 4.1.0
  * @param string $payment_method_to_display the default payment method text to display
  * @param array $subscription_details the subscription details
  * @param WC_Order $order the order containing the subscription
  * @return string the subscription payment method
  */
 public function maybe_render_payment_method_1_5($payment_method_to_display, $subscription_details, $order)
 {
     // bail for other payment methods
     if ($this->get_gateway()->get_id() !== $order->recurring_payment_method) {
         return $payment_method_to_display;
     }
     $token = $this->get_gateway()->get_payment_token($order->get_user_id(), $this->get_gateway()->get_order_meta($order->id, 'payment_token'));
     if (is_object($token)) {
         $payment_method_to_display = sprintf(_x('Via %s ending in %s', 'Supports direct payment method subscriptions', $this->get_gateway()->get_text_domain()), $token->get_type_full(), $token->get_last_four());
     }
     return $payment_method_to_display;
 }
 /**
  * Helper method to set/update the billing & shipping addresses for an order.
  *
  * @since 2.5.0
  * @param WC_Order $order
  * @param array $data
  */
 protected function set_order_addresses($order, $data)
 {
     $address_fields = array('first_name', 'last_name', 'company', 'email', 'phone', 'address_1', 'address_2', 'city', 'state', 'postcode', 'country');
     $billing_address = $shipping_address = array();
     // billing address.
     if (isset($data['billing_address']) && is_array($data['billing_address'])) {
         foreach ($address_fields as $field) {
             if (isset($data['billing_address'][$field])) {
                 $billing_address[$field] = wc_clean($data['billing_address'][$field]);
             }
         }
         unset($address_fields['email']);
         unset($address_fields['phone']);
     }
     // shipping address.
     if (isset($data['shipping_address']) && is_array($data['shipping_address'])) {
         foreach ($address_fields as $field) {
             if (isset($data['shipping_address'][$field])) {
                 $shipping_address[$field] = wc_clean($data['shipping_address'][$field]);
             }
         }
     }
     $order->set_address($billing_address, 'billing');
     $order->set_address($shipping_address, 'shipping');
     // update user meta
     if ($order->get_user_id()) {
         foreach ($billing_address as $key => $value) {
             update_user_meta($order->get_user_id(), 'billing_' . $key, $value);
         }
         foreach ($shipping_address as $key => $value) {
             update_user_meta($order->get_user_id(), 'shipping_' . $key, $value);
         }
     }
 }
 /**
  * Add customer data as part of the add payment method transaction, primarily
  * customer ID
  *
  * @since 4.0.0
  * @param WC_Order $order mock order
  * @param SV_WC_Payment_Gateway_API_Create_Payment_Token_Response $response
  */
 protected function add_add_payment_method_customer_data($order, $response)
 {
     $user_id = $order->get_user_id();
     // set customer ID from response if available
     if ($this->supports_customer_id() && method_exists($response, 'get_customer_id') && $response->get_customer_id()) {
         $order->customer_id = $customer_id = $response->get_customer_id();
     } else {
         // default to the customer ID on "order"
         $customer_id = $order->customer_id;
     }
     // update the user
     if (0 != $user_id) {
         $this->update_customer_id($user_id, $customer_id);
     }
 }
 /**
  * Render the payment method used for a subscription in the "My Subscriptions" table
  *
  * @since 4.1.0
  * @param string $payment_method_to_display the default payment method text to display
  * @param array $subscription_details the subscription details
  * @param WC_Order $order the order containing the subscription
  * @return string the subscription payment method
  */
 public function maybe_render_payment_method_1_5($payment_method_to_display, $subscription_details, $order)
 {
     // bail for other payment methods
     if ($this->get_gateway()->get_id() !== $order->recurring_payment_method) {
         return $payment_method_to_display;
     }
     $token = $this->get_gateway()->get_payment_tokens_handler()->get_token($order->get_user_id(), $this->get_gateway()->get_order_meta($order->id, 'payment_token'));
     if (is_object($token)) {
         $payment_method_to_display = sprintf(__('Via %s ending in %s', 'woocommerce-plugin-framework'), $token->get_type_full(), $token->get_last_four());
     }
     return $payment_method_to_display;
 }
Exemplo n.º 9
0
 /**
  * @param $order_id
  */
 public function last_buy($order_id)
 {
     $order = new \WC_Order($order_id);
     $user_id = $order->get_user_id();
     update_user_meta($user_id, 'hl_last_buy', Carbon::now()->toDateString());
 }
Exemplo n.º 10
0
 /**
  * sensei_woocommerce_complete_order description
  * @since   1.0.3
  * @access  public
  * @param   int $order_id WC order ID
  * @return  void
  */
 public static function complete_order($order_id = 0)
 {
     $order_user = array();
     // Check for WooCommerce
     if (Sensei_WC::is_woocommerce_active() && 0 < $order_id) {
         // Get order object
         $order = new WC_Order($order_id);
         $user = get_user_by('id', $order->get_user_id());
         $order_user['ID'] = $user->ID;
         $order_user['user_login'] = $user->user_login;
         $order_user['user_email'] = $user->user_email;
         $order_user['user_url'] = $user->user_url;
         // Run through each product ordered
         if (0 < sizeof($order->get_items())) {
             foreach ($order->get_items() as $item) {
                 $product_type = '';
                 if (isset($item['variation_id']) && 0 < $item['variation_id']) {
                     $item_id = $item['variation_id'];
                     $product_type = 'variation';
                 } else {
                     $item_id = $item['product_id'];
                 }
                 // End If Statement
                 $_product = Sensei_WC::get_product_object($item_id, $product_type);
                 // Get courses that use the WC product
                 $courses = Sensei()->course->get_product_courses($_product->id);
                 // Loop and update those courses
                 foreach ($courses as $course_item) {
                     $update_course = Sensei()->woocommerce_course_update($course_item->ID, $order_user);
                 }
                 // End For Loop
             }
             // End For Loop
         }
         // End If Statement
         // Add meta to indicate that payment has been completed successfully
         update_post_meta($order_id, 'sensei_payment_complete', '1');
     }
     // End If Statement
 }
 /**
  * process_payment
  *
  * Completes the initial payment on the subscription order
  *
  * Although PayPal Braintree supports subscription products (they call them plans),
  * they don't support the wide variety of intervals we do, nor multiple subscription
  * products in a single order.
  *
  * So, this extension does all the subscription work itself, storing a customer
  * in the vault on the first payment, and using those stored credentials for
  * renewal orders
  *
  * @param  int $order_id
  * @return mixed
  */
 public function process_payment($order_id)
 {
     // If the order contains no subscriptions, just let the parent process it
     if (!$this->order_contains_subscription($order_id)) {
         return parent::process_payment($order_id);
     }
     $order = new WC_Order($order_id);
     $this->log(__FUNCTION__, "Info: Beginning processing of payment for (subscription) order {$order_id} for the amount of {$order->order_total}");
     $this->log(__FUNCTION__, "Info: Merchant ID = {$this->merchant_id}");
     $paypal_braintree_nonce = self::get_posted_variable('paypalbraintree_nonce');
     if (empty($paypal_braintree_nonce)) {
         $this->log(__FUNCTION__, 'Error: The paypal_braintree_nonce was unexpectedly empty');
         wc_add_notice(__('Error: PayPal Powered by Braintree did not supply a payment nonce. Please try again later or use another means of payment.', 'woocommerce-gateway-paypal-braintree'), 'error');
         return false;
     }
     $user_id = $order->get_user_id();
     if (!is_user_logged_in()) {
         $this->log(__FUNCTION__, 'Error: No user logged in / being created for the initial subscription payment');
         wc_add_notice(__('Error: You must login or create an account before you can purchase a subscription.', 'woocommerce-gateway-paypal-braintree'), 'error');
         return false;
     }
     // Create the gateway instance up front
     require_once dirname(__FILE__) . '/../braintree_sdk/lib/Braintree.php';
     $gateway = new Braintree_Gateway(array('accessToken' => $this->merchant_access_token));
     // Check their user meta for a stored braintree customer id
     $braintree_customer_id = get_user_meta($user_id, '_wc_paypal_braintree_customer_id', true);
     if (empty($braintree_customer_id)) {
         $this->log(__FUNCTION__, 'Info: Did not find braintree customer id on user meta. Need to create customer');
         // Create a new customer id, passing the nonce so we can add the card to the vault
         // ref https://developers.braintreepayments.com/reference/request/customer/create/php
         $customer_args = array('firstName' => $order->billing_first_name, 'lastName' => $order->billing_last_name, 'company' => $order->billing_company, 'phone' => $order->billing_phone, 'email' => $order->billing_email, 'paymentMethodNonce' => $paypal_braintree_nonce);
         try {
             $result = $gateway->customer()->create($customer_args);
         } catch (Exception $e) {
             $this->log(__FUNCTION__, 'Error: Unable to create customer. Reason: ' . $e->getMessage());
             wc_add_notice(__('Error: PayPal Powered by Braintree was unable to create a customer record for you. Please try again later or use another means of payment.', 'woocommerce-gateway-paypal-braintree'), 'error');
             return false;
         }
         if (!$result->success) {
             $this->log(__FUNCTION__, "Error: Unable to create customer: {$result->message}");
             wc_add_notice(__('Error: PayPal Powered by Braintree was unable to create a customer record for you. Please try again later or use another means of payment.', 'woocommerce-gateway-paypal-braintree'), 'error');
             return false;
         }
         $braintree_customer_id = $result->customer->id;
         update_user_meta($user_id, '_wc_paypal_braintree_customer_id', $braintree_customer_id);
         $this->log(__FUNCTION__, "Info: Created customer successfully - braintree customer id = {$braintree_customer_id}");
         $payment_methods = $result->customer->paymentMethods;
         $payment_method_token = '';
         foreach ((array) $payment_methods as $payment_method) {
             if ($payment_method->default) {
                 $payment_method_token = $payment_method->token;
             }
         }
         $authentication = array('paymentMethodToken' => $payment_method_token);
     } else {
         // We found the braintree customer id in the customer's meta
         $this->log(__FUNCTION__, "Info: Found a braintree customer id in the users meta - customer id = {$braintree_customer_id}");
         $authentication = array('paymentMethodNonce' => $paypal_braintree_nonce);
     }
     $sale_args = $this->generate_sales_args($order, $braintree_customer_id);
     $sale_args = array_merge($sale_args, $authentication);
     $transaction_id = '';
     // Process trial periods and possible coupon discounts.
     if (isset($sale_args['amount']) && 0.0 === doubleval($sale_args['amount'])) {
         $user_id = $order->get_user_id();
         $this->log(__FUNCTION__, "Zero payment amount for trial or coupon. Order ID: {$order_id}, User ID:  {$user_id}");
         $customer = $gateway->customer()->find($braintree_customer_id);
         $payment_method_token = '';
         foreach ((array) $customer->paymentMethods as $payment_method) {
             if ($payment_method->default) {
                 $payment_method_token = $payment_method->token;
             }
         }
     } else {
         // charges more than zero should be sent away
         // We have a customer id now, so let's do the sale and store the payment method in the vault.
         $result = $gateway->transaction()->sale($sale_args);
         if (!$result->success) {
             $notice = sprintf(__('Error: PayPal Powered by Braintree was unable to complete the transaction. Please try again later or use another means of payment. Reason: %s', 'woocommerce-gateway-paypal-braintree'), $error_message);
             wc_add_notice($notice, 'error');
             $this->log(__FUNCTION__, "Error: Unable to complete transaction. Reason: {$result->message}");
             return false;
         }
         $transaction_id = $result->transaction->id;
         $this->log(__FUNCTION__, "Info: Successfully processed initial payment, transaction id = {$transaction_id}");
         $credit_card_meta = $result->transaction->creditCard;
         $payment_method_token = $credit_card_meta['token'];
         if (empty($payment_method_token)) {
             $this->log(__FUNCTION__, 'Info: Customer used the paypal subflow');
             $paypal_meta = $result->transaction->paypal;
             $payment_method_token = $paypal_meta['token'];
         } else {
             $this->log(__FUNCTION__, 'Info: Customer used the credit card subflow');
         }
         $braintree_customer_id = $result->transaction->customer['id'];
     }
     if (empty($payment_method_token)) {
         $this->log(__FUNCTION__, 'Warning: Initial payment succeeded, but no token was provided by the gateway for recurring payments.');
     }
     // Save the customer ID in each subscription for this order for later use during renewal
     if (empty($braintree_customer_id)) {
         $this->log(__FUNCTION__, 'Warning: Initial payment succeeded, but no braintree customer ID was provided by the gateway for recurring payments.');
     } else {
         $this->log(__FUNCTION__, "Info: Saving to subscription(s) recurring payment braintree customer ID {$braintree_customer_id}");
     }
     // Note: A single order may contain multiple subscriptions
     // Save the token in each subscription for this order for later use during renewal
     foreach (wcs_get_subscriptions_for_order($order->id) as $subscription) {
         update_post_meta($subscription->id, '_wc_paypal_braintree_payment_method_token', $payment_method_token);
         update_post_meta($subscription->id, '_wc_paypal_braintree_customer_id', $braintree_customer_id);
     }
     $order->payment_complete($transaction_id);
     $this->log(__FUNCTION__, "Info: Completed processing of payment for order {$order_id}");
     return array('result' => 'success', 'redirect' => $this->get_return_url($order));
 }
Exemplo n.º 12
0
 /**
  * Runs when an subscription is re-activated after suspension.
  * @since   1.3.3
  * @access  public
  * @param   integer $user_id User ID
  * @param   integer $subscription_key Subscription Unique Key
  * @return  void
  */
 public function sensei_woocommerce_reactivate_subscription($user_id, $subscription_key)
 {
     $subscription = WC_Subscriptions_Manager::get_users_subscription($user_id, $subscription_key);
     $order = new WC_Order($subscription['order_id']);
     $user = get_user_by('id', $order->get_user_id());
     $order_user = array();
     $order_user['ID'] = $user->ID;
     $order_user['user_login'] = $user->user_login;
     $order_user['user_email'] = $user->user_email;
     $order_user['user_url'] = $user->user_url;
     $courses = $this->post_types->course->get_product_courses($subscription['product_id']);
     foreach ($courses as $course_item) {
         $update_course = $this->woocommerce_course_update($course_item->ID, $order_user);
     }
     // End For Loop
 }
Exemplo n.º 13
0
 /**
  * Get customer ID.
  *
  * @param  WC_Order $order Order data.
  *
  * @return string          Customer ID.
  */
 public function get_customer_id($order)
 {
     $user_id = $order->get_user_id();
     // Try get a saved customer ID.
     if (0 < $user_id) {
         $customer_id = get_user_meta($user_id, '_iugu_customer_id', true);
         if ($customer_id) {
             return $customer_id;
         }
     }
     // Create customer in Iugu.
     $customer_id = $this->create_customer($order);
     // Save the customer ID.
     if (0 < $user_id) {
         update_user_meta($user_id, '_iugu_customer_id', $customer_id);
     }
     return $customer_id;
 }
Exemplo n.º 14
0
 /**
  * Process an standard auth/vault transaction
  *
  * @param Realex_API $realex_client realex api client
  * @param WC_Order $order the order
  * @param array $data optional post data to use in place of $_POST
  * @param boolean $increment_retry_count optional whether to increment the retry
  *        count to avoid order number clashes, defaults to true.  It's important
  *        that this be true for, and only for, the first request of any transaction
  */
 public function authorize($realex_client, $order, $data = null, $increment_retry_count = true)
 {
     // paying with a tokenized cc?
     $vault_card_ref = $this->get_post('realex_card_ref', $data);
     // subscription support, this is a scheduled subscription payment, and not a live payment
     // TODO: this is terrible, refactor all this when possible
     $subscription = false;
     if (get_post_meta($order->id, '_realex_cardref')) {
         $vault_card_ref = get_post_meta($order->id, '_realex_cardref', true);
         $subscription = true;
     }
     // user in the vault?
     $vault_payer_ref = null;
     if ($order->get_user_id()) {
         $vault_payer_ref = get_user_meta($order->get_user_id(), 'woocommerce_realex_payerref', true);
     }
     // create/update the customer in the vault as needed
     if ($this->vault_available() && !$subscription) {
         if ($vault_payer_ref) {
             // update the vault payer info
             $this->update_vault_payer($realex_client, $vault_payer_ref, $order);
         }
         // new vault payer (non-guest checkout)
         if (!$vault_payer_ref && $this->get_post('realex_vault_new', $data) && $order->get_user_id()) {
             $vault_payer_ref = $this->get_new_payer_ref($order->get_user_id());
             $this->create_new_vault_payer($realex_client, $vault_payer_ref, $order);
         }
         // add a new card?
         if ($vault_payer_ref && $this->get_post('realex_vault_new', $data) && !$vault_card_ref) {
             $card_type = $this->get_post('realex_cardType', $data);
             // generate a unique vault card ref and add the card
             $vault_card_ref = $this->get_new_card_ref($order->get_user_id(), $card_type);
             $vault_new_card_response = $this->create_new_vault_card($realex_client, $vault_payer_ref, $vault_card_ref, $order, $data);
             if ($vault_new_card_response && $vault_new_card_response->result == '501' && stripos($vault_new_card_response->message, 'There is no such payer ref') !== false) {
                 // the payerref we have on file is invalid: delete it and attempt to create a new one and add this card to it
                 $this->delete_payer_ref($order->get_user_id());
                 $vault_payer_ref = $this->get_new_payer_ref($order->get_user_id());
                 $this->create_new_vault_payer($realex_client, $vault_payer_ref, $order);
                 if ($vault_payer_ref) {
                     // if vault payer was added try one last time to add the card
                     $vault_card_ref = $this->get_new_card_ref($order->get_user_id(), $card_type);
                     $this->create_new_vault_card($realex_client, $vault_payer_ref, $vault_card_ref, $order, $data);
                 }
             }
         }
     }
     // with subscriptions, the payment total can be zero for the initial setup
     if ($order->payment_total == 0) {
         if ($vault_card_ref) {
             // record the card token used for this order
             update_post_meta($order->id, '_realex_cardref', (string) $vault_card_ref);
         }
         return;
     }
     $cards = null;
     if ($vault_card_ref) {
         // paying using an existing token
         $cards = get_user_meta($order->get_user_id(), 'woocommerce_realex_cc', true);
         // validate the input
         if (!isset($cards[$vault_card_ref])) {
             SV_WC_Helper::wc_add_notice(__("An error occurred, try an alternate form of payment", 'woocommerce-gateway-realex'), 'error');
             return;
         }
         // perform the auth transaction using the supplied token (never 3DSecure)
         $response = $this->vault_auth_request($realex_client, $vault_payer_ref, $cards[$vault_card_ref]['type'], $vault_card_ref, $order);
     } else {
         // perform the regular auth transaction
         $response = $this->auth_request($realex_client, $order, $data, $increment_retry_count);
     }
     if (!$response) {
         SV_WC_Helper::wc_add_notice(__('Connection error', 'woocommerce-gateway-realex'), 'error');
         return;
     }
     if ('00' == $response->result) {
         // Successful payment
         if (!$realex_client->verify_transaction_signature($response)) {
             // response was not properly signed by realex
             SV_WC_Helper::wc_add_notice(__('Error - invalid transaction signature, check your Realex settings.', 'woocommerce-gateway-realex'), 'error');
             // if debug mode load the response into the messages object
             if ($this->is_debug_mode()) {
                 $this->response_debug_message($response, $vault_card_ref ? "Response: receipt-in" : "Response: auth", 'error');
             }
             return;
         }
         // if debug mode load the response into the messages object
         if ($this->is_debug_mode()) {
             $this->response_debug_message($response, $vault_card_ref ? "Response: receipt-in" : "Response: auth", 'message', true);
         }
         // collect the credit card information used for this transaction, whether it was a vaulted transaction or a regular
         if ($vault_card_ref) {
             $card = (object) $cards[$vault_card_ref];
             $card_type = $card->type;
             $last4 = $card->last4;
             $expiration_month = $card->expiration_month;
             $expiration_year = $card->expiration_year;
         } else {
             $card_type = $this->get_post('realex_cardType', $data);
             $last4 = substr($this->get_post('realex_accountNumber', $data), -4);
             $expiration_month = $this->get_post('realex_expirationMonth', $data);
             $expiration_year = $this->get_post('realex_expirationYear', $data);
         }
         // update the order record with success
         /* translators: Placeholders: %1$s - credit card type, %2$s - credit card last 4, %3$s - credit card expiration MM/YY */
         $order_note = sprintf(__('Credit Card Transaction Approved: %1$s ending in %2$s (%3$s).', 'woocommerce-gateway-realex'), $this->card_type_options[$card_type], $last4, $expiration_month . '/' . $expiration_year);
         $order_note = apply_filters('wc_gateway_realex_order_note', $order_note, $order, $data, $card_type, $cards);
         // avs response, if check was performed.
         if ($this->avs_check()) {
             // There's also 'M' for Matched, and 'X' if AVS check was not performed
             $avs_response_codes = array('N' => 'Not matched', 'I' => 'Problem with check', 'U' => 'Unable to check', 'P' => 'Partial match');
             $code = (string) $response->avspostcoderesponse;
             if (isset($avs_response_codes[$code])) {
                 $order_note .= "\n" . sprintf(__('AVS post code response: %s', 'woocommerce-gateway-realex'), $avs_response_codes[$code]);
             }
             $code = (string) $response->avsaddressresponse;
             if (isset($avs_response_codes[$code])) {
                 $order_note .= "\n" . sprintf(__('AVS address response: %s', 'woocommerce-gateway-realex'), $avs_response_codes[$code]);
             }
         }
         if (!$subscription) {
             // normal execution
             $order->add_order_note($order_note);
             $order->payment_complete();
             // store the payment reference in the order (add_post_meta not update_post_meta)
             add_post_meta($order->id, '_realex_payment_reference', (string) $response->pasref);
             if ($vault_card_ref) {
                 // record the card token used for this order (add_post_meta not update_post_meta)
                 add_post_meta($order->id, '_realex_cardref', (string) $vault_card_ref);
             }
             WC()->cart->empty_cart();
             // Return thank you redirect
             return array('result' => 'success', 'redirect' => $this->get_return_url($order));
         } else {
             // special subscription handling
             return $response;
         }
     } else {
         // Failure: it's important that the order status be set to 'failed' so that a new order number can be generated,
         // because Realex does not allow the same order number to be used once a payment attempt has failed
         /* translators: Placeholders: %1$s - response result, %2$s - failure message */
         $error_note = sprintf(__('Realex Credit Card payment failed (Result: %1$s - "%2$s").', 'woocommerce-gateway-realex'), $response->result, $response->message);
         if (!$subscription) {
             $this->order_failed($order, $error_note);
         }
         $message = __('The transaction has been declined by your bank, please contact your bank for more details, or try an alternative payment method.  Your order has been recorded, please contact us if you wish to provide payment over the phone.', 'woocommerce-gateway-realex');
         if ($vault_card_ref && $response->result == 520) {
             if (stripos($response->message, 'There is no such Payer') !== false) {
                 // payerref does not exist
                 $this->delete_payer_ref($order->get_user_id());
                 $message = __("Internal error, please use an alternate form of payment", 'woocommerce-gateway-realex');
             } elseif (stripos($response->message, 'There is no such Payment Method') !== false) {
                 // card ref does not exist
                 $this->delete_card_ref($vault_card_ref);
                 $message = __("Unknown card, please use an alternate form of payment", 'woocommerce-gateway-realex');
             }
         }
         // provide some default error message
         if (SV_WC_Helper::wc_notice_count('error') == 0) {
             if ($message) {
                 SV_WC_Helper::wc_add_notice($message, 'error');
             } else {
                 SV_WC_Helper::wc_add_notice(__("An error occurred, please try again or try an alternate form of payment", 'woocommerce-gateway-realex'), 'error');
             }
         }
         // if debug mode load the response into the messages object
         if ($this->is_debug_mode()) {
             $this->response_debug_message($response, $vault_card_ref ? "Response: receipt-in" : "Response: auth", 'error');
         }
         // special subscription handling
         if ($subscription) {
             return $response;
         }
     }
 }
 /**
  * Uses the details of an order to create a pending subscription on the customers account
  * for a subscription product, as specified with $product_id.
  *
  * @param int|WC_Order $order The order ID or WC_Order object to create the subscription from.
  * @param int $product_id The ID of the subscription product on the order, if a variation, it must be the variation's ID.
  * @param array $args An array of name => value pairs to customise the details of the subscription, including:
  * 			'start_date' A MySQL formatted date/time string on which the subscription should start, in UTC timezone
  * 			'expiry_date' A MySQL formatted date/time string on which the subscription should expire, in UTC timezone
  * @since 1.1
  */
 public static function create_pending_subscription_for_order($order, $product_id, $args = array())
 {
     _deprecated_function(__METHOD__, '2.0', 'wcs_create_subscription()');
     if (!is_object($order)) {
         $order = new WC_Order($order);
     }
     if (!WC_Subscriptions_Product::is_subscription($product_id)) {
         return;
     }
     $args = wp_parse_args($args, array('start_date' => get_gmt_from_date($order->order_date), 'expiry_date' => ''));
     $billing_period = WC_Subscriptions_Product::get_period($product_id);
     $billing_interval = WC_Subscriptions_Product::get_interval($product_id);
     // Support passing timestamps
     $args['start_date'] = is_numeric($args['start_date']) ? date('Y-m-d H:i:s', $args['start_date']) : $args['start_date'];
     $product = wc_get_product($product_id);
     // Check if there is already a subscription for this product and order
     $subscriptions = wcs_get_subscriptions(array('order_id' => $order->id, 'product_id' => $product_id));
     if (!empty($subscriptions)) {
         $subscription = array_pop($subscriptions);
         // Make sure the subscription is pending and start date is set correctly
         wp_update_post(array('ID' => $subscription->id, 'post_status' => 'wc-' . apply_filters('woocommerce_default_subscription_status', 'pending'), 'post_date' => get_date_from_gmt($args['start_date'])));
     } else {
         $subscription = wcs_create_subscription(array('start_date' => get_date_from_gmt($args['start_date']), 'order_id' => $order->id, 'customer_id' => $order->get_user_id(), 'billing_period' => $billing_period, 'billing_interval' => $billing_interval, 'customer_note' => $order->customer_note));
         if (is_wp_error($subscription)) {
             throw new Exception(__('Error: Unable to create subscription. Please try again.', 'woocommerce-subscriptions'));
         }
         $item_id = $subscription->add_product($product, 1, array('variation' => method_exists($product, 'get_variation_attributes') ? $product->get_variation_attributes() : array(), 'totals' => array('subtotal' => $product->get_price(), 'subtotal_tax' => 0, 'total' => $product->get_price(), 'tax' => 0, 'tax_data' => array('subtotal' => array(), 'total' => array()))));
         if (!$item_id) {
             throw new Exception(__('Error: Unable to add product to created subscription. Please try again.', 'woocommerce-subscriptions'));
         }
     }
     // Make sure some of the meta is copied form the order rather than the store's defaults
     update_post_meta($subscription->id, '_order_currency', $order->order_currency);
     update_post_meta($subscription->id, '_prices_include_tax', $order->prices_include_tax);
     // Adding a new subscription so set the expiry date/time from the order date
     if (!empty($args['expiry_date'])) {
         if (is_numeric($args['expiry_date'])) {
             $args['expiry_date'] = date('Y-m-d H:i:s', $args['expiry_date']);
         }
         $expiration = $args['expiry_date'];
     } else {
         $expiration = WC_Subscriptions_Product::get_expiration_date($product_id, $args['start_date']);
     }
     // Adding a new subscription so set the expiry date/time from the order date
     $trial_expiration = WC_Subscriptions_Product::get_trial_expiration_date($product_id, $args['start_date']);
     $dates_to_update = array();
     if ($trial_expiration > 0) {
         $dates_to_update['trial_end'] = $trial_expiration;
     }
     if ($expiration > 0) {
         $dates_to_update['end'] = $expiration;
     }
     if (!empty($dates_to_update)) {
         $subscription->update_dates($dates_to_update);
     }
     // Set the recurring totals on the subscription
     $subscription->set_total(0, 'tax');
     $subscription->set_total($product->get_price(), 'total');
     $subscription->add_order_note(__('Pending subscription created.', 'woocommerce-subscriptions'));
     do_action('pending_subscription_created_for_order', $order, $product_id);
 }
Exemplo n.º 16
0
/**
 * Grant downloadable product access to the file identified by $download_id.
 *
 * @access public
 * @param string $download_id file identifier
 * @param int $product_id product identifier
 * @param WC_Order $order the order
 * @param  int $qty purchased
 * @return int|bool insert id or false on failure
 */
function wc_downloadable_file_permission($download_id, $product_id, $order, $qty = 1)
{
    global $wpdb;
    $user_email = sanitize_email($order->get_billing_email());
    $limit = trim(get_post_meta($product_id, '_download_limit', true));
    $expiry = trim(get_post_meta($product_id, '_download_expiry', true));
    $limit = empty($limit) ? '' : absint($limit) * $qty;
    // Default value is NULL in the table schema
    $expiry = empty($expiry) ? null : absint($expiry);
    if ($expiry) {
        $order_completed_date = date_i18n("Y-m-d", strtotime($order->completed_date));
        $expiry = date_i18n("Y-m-d", strtotime($order_completed_date . ' + ' . $expiry . ' DAY'));
    }
    $data = apply_filters('woocommerce_downloadable_file_permission_data', array('download_id' => $download_id, 'product_id' => $product_id, 'user_id' => absint($order->get_user_id()), 'user_email' => $user_email, 'order_id' => $order->get_id(), 'order_key' => $order->get_order_key(), 'downloads_remaining' => $limit, 'access_granted' => current_time('mysql'), 'download_count' => 0));
    $format = apply_filters('woocommerce_downloadable_file_permission_format', array('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d'), $data);
    if (!is_null($expiry)) {
        $data['access_expires'] = $expiry;
        $format[] = '%s';
    }
    // Downloadable product - give access to the customer
    $result = $wpdb->insert($wpdb->prefix . 'woocommerce_downloadable_product_permissions', $data, $format);
    do_action('woocommerce_grant_product_download_access', $data);
    return $result ? $wpdb->insert_id : false;
}
 /**
  * Prepare links for the request.
  *
  * @param WC_Order $order Order object.
  * @return array Links for the given order.
  */
 protected function prepare_links($order)
 {
     $links = array('self' => array('href' => rest_url(sprintf('/%s/%s/%d', $this->namespace, $this->rest_base, $order->get_id()))), 'collection' => array('href' => rest_url(sprintf('/%s/%s', $this->namespace, $this->rest_base))));
     if (0 !== (int) $order->get_user_id()) {
         $links['customer'] = array('href' => rest_url(sprintf('/%s/customers/%d', $this->namespace, $order->get_user_id())));
     }
     if (0 !== (int) $order->get_parent_id()) {
         $links['up'] = array('href' => rest_url(sprintf('/%s/orders/%d', $this->namespace, $order->get_parent_id())));
     }
     return $links;
 }
 private function get_user_id(WC_Order $order)
 {
     if ($order->get_user_id() === 0) {
         return 'SINGLE_ORDER_' . $order->post->ID;
     }
     return 'REGISTERED_USER_' . $order->get_user_id();
 }
 /**
  * Add customer data to an order/user if the gateway supports the customer ID
  * response
  *
  * @since 4.0.0
  * @param \WC_Order $order order
  * @param \SV_WC_Payment_Gateway_API_Customer_Response $response
  */
 protected function add_customer_data($order, $response = null)
 {
     $user_id = $order->get_user_id();
     if ($response && method_exists($response, 'get_customer_id') && $response->get_customer_id()) {
         $order->customer_id = $customer_id = $response->get_customer_id();
     } else {
         // default to the customer ID set on the order
         $customer_id = $order->customer_id;
     }
     // update the order with the customer ID, note environment is not appended here because it's already available
     // on the `environment` order meta
     $this->update_order_meta($order->id, 'customer_id', $customer_id);
     // update the user
     if (0 != $user_id) {
         $this->update_customer_id($user_id, $customer_id);
     }
 }
 /**
  * Create a new subscription from a cart item on checkout.
  *
  * The function doesn't validate whether the cart item is a subscription product, meaning it can be used for any cart item,
  * but the item will need a `subscription_period` and `subscription_period_interval` value set on it, at a minimum.
  *
  * @param WC_Order $order
  * @param WC_Cart $cart
  * @since 2.0
  */
 public static function create_subscription($order, $cart)
 {
     global $wpdb;
     try {
         // Start transaction if available
         $wpdb->query('START TRANSACTION');
         // Set the recurring line totals on the subscription
         $variation_id = wcs_cart_pluck($cart, 'variation_id');
         $product_id = empty($variation_id) ? wcs_cart_pluck($cart, 'product_id') : $variation_id;
         // We need to use the $order->order_date value because the post_date_gmt isn't always set
         $order_date_gmt = get_gmt_from_date($order->order_date);
         $subscription = wcs_create_subscription(array('start_date' => $cart->start_date, 'order_id' => $order->id, 'customer_id' => $order->get_user_id(), 'billing_period' => wcs_cart_pluck($cart, 'subscription_period'), 'billing_interval' => wcs_cart_pluck($cart, 'subscription_period_interval'), 'customer_note' => $order->customer_note));
         if (is_wp_error($subscription)) {
             throw new Exception($subscription->get_error_message());
         }
         // Set the subscription's billing and shipping address
         $subscription = wcs_copy_order_address($order, $subscription);
         $subscription->update_dates(array('trial_end' => $cart->trial_end_date, 'next_payment' => $cart->next_payment_date, 'end' => $cart->end_date));
         // Store trial period for PayPal
         if (wcs_cart_pluck($cart, 'subscription_trial_length') > 0) {
             update_post_meta($subscription->id, '_trial_period', wcs_cart_pluck($cart, 'subscription_trial_period'));
         }
         // Set the payment method on the subscription
         $available_gateways = WC()->payment_gateways->get_available_payment_gateways();
         if ($cart->needs_payment() && isset($available_gateways[$order->payment_method])) {
             $subscription->set_payment_method($available_gateways[$order->payment_method]);
         }
         if (!$cart->needs_payment() || 'yes' == get_option(WC_Subscriptions_Admin::$option_prefix . '_turn_off_automatic_payments', 'no')) {
             $subscription->update_manual('true');
         } elseif (!isset($available_gateways[$order->payment_method]) || !$available_gateways[$order->payment_method]->supports('subscriptions')) {
             $subscription->update_manual('true');
         }
         wcs_copy_order_meta($order, $subscription, 'subscription');
         // Store the line items
         foreach ($cart->get_cart() as $cart_item_key => $cart_item) {
             $item_id = self::add_cart_item($subscription, $cart_item, $cart_item_key);
         }
         // Store fees (although no fees recur by default, extensions may add them)
         foreach ($cart->get_fees() as $fee_key => $fee) {
             $item_id = $subscription->add_fee($fee);
             if (!$item_id) {
                 // translators: placeholder is an internal error number
                 throw new Exception(sprintf(__('Error %d: Unable to create subscription. Please try again.', 'woocommerce-subscriptions'), 403));
             }
             // Allow plugins to add order item meta to fees
             do_action('woocommerce_add_order_fee_meta', $order->id, $item_id, $fee, $fee_key);
         }
         self::add_shipping($subscription, $cart);
         // Store tax rows
         foreach (array_keys($cart->taxes + $cart->shipping_taxes) as $tax_rate_id) {
             if ($tax_rate_id && !$subscription->add_tax($tax_rate_id, $cart->get_tax_amount($tax_rate_id), $cart->get_shipping_tax_amount($tax_rate_id)) && apply_filters('woocommerce_cart_remove_taxes_zero_rate_id', 'zero-rated') !== $tax_rate_id) {
                 // translators: placeholder is an internal error number
                 throw new Exception(sprintf(__('Error %d: Unable to add tax to subscription. Please try again.', 'woocommerce-subscriptions'), 405));
             }
         }
         // Store coupons
         foreach ($cart->get_coupons() as $code => $coupon) {
             if (!$subscription->add_coupon($code, $cart->get_coupon_discount_amount($code), $cart->get_coupon_discount_tax_amount($code))) {
                 // translators: placeholder is an internal error number
                 throw new Exception(sprintf(__('Error %d: Unable to create order. Please try again.', 'woocommerce-subscriptions'), 406));
             }
         }
         // Set the recurring totals on the subscription
         $subscription->set_total($cart->shipping_total, 'shipping');
         $subscription->set_total($cart->get_cart_discount_total(), 'cart_discount');
         $subscription->set_total($cart->get_cart_discount_tax_total(), 'cart_discount_tax');
         $subscription->set_total($cart->tax_total, 'tax');
         $subscription->set_total($cart->shipping_tax_total, 'shipping_tax');
         $subscription->set_total($cart->total);
         // If we got here, the subscription was created without problems
         $wpdb->query('COMMIT');
     } catch (Exception $e) {
         // There was an error adding the subscription
         $wpdb->query('ROLLBACK');
         return new WP_Error('checkout-error', $e->getMessage());
     }
     return $subscription;
 }
 /**
  * Update address.
  *
  * @param WC_Order $order
  * @param array $posted
  * @param string $type
  */
 protected function update_address($order, $posted, $type = 'billing')
 {
     $fields = $order->get_address($type);
     foreach (array_keys($fields) as $field) {
         if (isset($posted[$field])) {
             $fields[$field] = $posted[$field];
         }
     }
     // Set address.
     $order->set_address($fields, $type);
     // Update user meta.
     if ($order->get_user_id()) {
         foreach ($fields as $key => $value) {
             update_user_meta($order->get_user_id(), $type . '_' . $key, $value);
         }
     }
 }
 /**
  * Handle a duplicate payment profile error when trying to add a payment
  * profile to an existing customer profile. Authorize.Net does not return
  * which profile it considers a duplicate, so we use the payment hash
  * saved on the local token and compare it against the generated hash for
  * the payment method that is being added.
  *
  * The process is to remove the duplicate payment profile in CIM and re-add the
  * current payment profile, rather than simply updating it. If we incorrectly
  * identify the duplicate profile, it's better to delete it in error rather
  * than partially update it with information from *different* profile.
  *
  * @since 2.0.0
  * @param WC_Order $order the order with associated payment and customer info
  * @return \WC_Authorize_Net_CIM_API_Payment_Profile_Response
  * @throws \SV_WC_Payment_Gateway_Exception
  */
 protected function handle_duplicate_payment_profile(WC_Order $order)
 {
     // get the current tokens
     $tokens = $this->get_gateway()->get_payment_tokens_handler()->get_tokens($order->get_user_id());
     foreach ($tokens as $token) {
         // if an existing payment profile is duplicate of the one we're trying to add...
         if ($token->is_duplicate_of($order)) {
             // remove the duplicate profile from CIM
             $this->get_gateway()->get_payment_tokens_handler()->remove_token($order->get_user_id(), $token);
             // safety flag
             $order->auth_net_cim_removed_duplicate_payment_profile = true;
             // attempt to re-add the payment profile that was previously considered a duplicate
             return $this->tokenize_payment_method($order);
         }
     }
     return false;
 }