/** * Creates an order for the specified user, and redirects to the edit page. * * @param \Drupal\user\UserInterface $user * The user to create the order for. */ public function createForUser(UserInterface $user) { $order = Order::create(['uid' => $user->id(), 'order_status' => uc_order_state_default('post_checkout')]); $order->save(); uc_order_comment_save($order->id(), \Drupal::currentUser()->id(), $this->t('Order created by the administration.'), 'admin'); return $this->redirect('entity.uc_order.edit_form', ['uc_order' => $order->id()]); }
/** * {@inheritdoc} */ public function submitForm(OrderInterface $order, array &$form, FormStateInterface $form_state) { if (!$form_state->isValueEmpty('admin_comment')) { $uid = \Drupal::currentUser()->id(); uc_order_comment_save($form_state->getValue('order_id'), $uid, $form_state->getValue('admin_comment')); } }
public static function isPaymentValid($oplataSettings, $response) { list($orderId, ) = explode(self::ORDER_SEPARATOR, $response['order_id']); $order = uc_order_load($orderId); if ($order === FALSE || uc_order_status_data($order->order_status, 'state') != 'in_checkout') { return t('An error has occurred during payment. Please contact us to ensure your order has submitted.'); } if ($oplataSettings->merchant_id != $response['merchant_id']) { return t('An error has occurred during payment. Merchant data is incorrect.'); } $originalResponse = $response; foreach ($response as $k => $v) { if (!in_array($k, self::$responseFields)) { unset($response[$k]); } } if (self::getSignature($response, $oplataSettings->secret_key) != $originalResponse['signature']) { return t('An error has occurred during payment. Signature is not valid.'); } if (drupal_strtolower($originalResponse['sender_email']) !== drupal_strtolower($order->primary_email)) { uc_order_comment_save($order->order_id, 0, t('Customer used a different e-mail address during payment: !email', array('!email' => check_plain($originalResponse['sender_email']))), 'admin'); } uc_order_comment_save($order->order_id, 0, "Order status: {$response['order_status']}", 'admin'); return true; }
/** * {@inheritdoc} */ public function process(OrderInterface $order, array $form, FormStateInterface $form_state) { db_delete('uc_order_comments')->condition('order_id', $order->id())->execute(); if (!$form_state->isValueEmpty(['panes', 'comments', 'comments'])) { uc_order_comment_save($order->id(), 0, $form_state->getValue(['panes', 'comments', 'comments']), 'order', uc_order_state_default('post_checkout'), TRUE); } return TRUE; }
/** * Processes a payment POST from the CyberSource Hosted Order Page API. */ public static function post() { if (!uc_cybersource_hop_include()) { \Drupal::logger('uc_cybersource_hop')->error('Unable to receive HOP POST due to missing or unreadable HOP.php file.'); drupal_add_http_header('Status', '503 Service unavailable'); print $this->t('The site was unable to receive a HOP post because of a missing or unreadble HOP.php'); exit; } $verify = VerifyTransactionSignature($_POST); \Drupal::logger('uc_cybersource_hop')->notice('Receiving payment notification at URL for order @orderNumber', array('@orderNumber' => $_POST['orderNumber'])); if (!isset($_POST['orderNumber'])) { \Drupal::logger('uc_cybersource_hop')->error('CS HOP attempted with invalid order number.'); return; } if (!$verify) { \Drupal::logger('uc_cybersource_hop')->notice('Receiving invalid payment notification at URL for order @orderNumber. <pre>@debug</pre>', array('@orderNumber' => $_POST['orderNumber'], '@debug' => print_r($_POST, TRUE))); return; } // Assign posted variables to local variables. $decision = SafeMarkup::checkPlain($_POST['decision']); $reason_code = SafeMarkup::checkPlain($_POST['reasonCode']); $reason = _parse_cs_reason_code($reason_code); $payment_amount = SafeMarkup::checkPlain($_POST['orderAmount']); $payment_currency = SafeMarkup::checkPlain($_POST['paymentCurrency']); $request_id = SafeMarkup::checkPlain($_POST['requestID']); $request_token = SafeMarkup::checkPlain($_POST['orderPage_requestToken']); $reconciliation_id = SafeMarkup::checkPlain($_POST['reconciliationID']); $order_id = SafeMarkup::checkPlain($_POST['orderNumber']); $payer_email = SafeMarkup::checkPlain($_POST['billTo_email']); $order = Order::load($_POST['orderNumber']); switch ($decision) { case 'ACCEPT': \Drupal::logger('uc_cybersource_hop')->notice('CyberSource verified successful payment.'); $duplicate = (bool) db_query_range('SELECT 1 FROM {uc_payment_cybersource_hop_post} WHERE order_id = :order_id AND decision = :decision', 0, 1, array(':order_id' => $order_id, ':decision' => 'ACCEPT'))->fetchField(); if ($duplicate) { \Drupal::logger('uc_cybersource_hop')->notice('CS HOP transaction for order @order-id has been processed before.', array('@order_id' => $order_id)); return; } db_insert('uc_payment_cybersource_hop_post')->fields(array('order_id' => $order_id, 'request_id' => $request_id, 'request_token' => $request_token, 'reconciliation_id' => $reconciliation_id, 'gross' => $payment_amount, 'decision' => $decision, 'reason_code' => $reason_code, 'payer_email' => $payer_email, 'received' => REQUEST_TIME))->execute(); $comment = $this->t('CyberSource request ID: @txn_id', array('@txn_id' => $request_id)); uc_payment_enter($order_id, 'cybersource_hop', $payment_amount, $order->getUserId(), NULL, $comment); uc_cart_complete_sale($order); uc_order_comment_save($order_id, 0, $this->t('Payment of @amount @currency submitted through CyberSource with request ID @rid.', array('@amount' => $payment_amount, '@currency' => $payment_currency, '@rid' => $request_id)), 'order', 'payment_received'); break; case 'ERROR': uc_order_comment_save($order_id, 0, $this->t("Payment error:@reason with request ID @rid", array('@reason' => $reason, '@rid' => '@request_id')), 'admin'); break; case 'REJECT': uc_order_comment_save($order_id, 0, $this->t("Payment is rejected:@reason with request ID @rid", array('@reason' => $reason, '@rid' => '@request_id')), 'admin'); break; case 'REVIEW': $order->setStatusId('review')->save(); uc_order_comment_save($order_id, 0, $this->t('Payment is in review & not complete: @reason. Request ID @rid', array('@reason' => $reason, '@rid' => '@request_id')), 'admin'); break; } }
/** * Finalizes 2checkout transaction. */ public function complete($cart_id = 0) { $cart_config = \Drupal::config('uc_cart.settings'); $module_config = \Drupal::config('uc_2checkout.settings'); \Drupal::logger('2Checkout')->notice('Receiving new order notification for order !order_id.', array('!order_id' => SafeMarkup::checkPlain($_REQUEST['merchant_order_id']))); $order = Order::load($_REQUEST['merchant_order_id']); if (!$order || $order->getStateId() != 'in_checkout') { return t('An error has occurred during payment. Please contact us to ensure your order has submitted.'); } $key = $_REQUEST['key']; $order_number = $module_config->get('demo') ? 1 : $_REQUEST['order_number']; $valid = md5($module_config->get('secret_word') . $_REQUEST['sid'] . $order_number . $_REQUEST['total']); if (Unicode::strtolower($key) != Unicode::strtolower($valid)) { uc_order_comment_save($order->id(), 0, t('Attempted unverified 2Checkout completion for this order.'), 'admin'); throw new AccessDeniedHttpException(); } if ($_REQUEST['demo'] == 'Y' xor $module_config->get('demo')) { \Drupal::logger('uc_2checkout')->error('The 2checkout payment for order <a href="@order_url">@order_id</a> demo flag was set to %flag, but the module is set to %mode mode.', array('@order_url' => url('admin/store/orders/' . $order->id()), '@order_id' => $order->id(), '%flag' => $_REQUEST['demo'] == 'Y' ? 'Y' : 'N', '%mode' => $module_config->get('demo') ? 'Y' : 'N')); if (!$module_config->get('demo')) { throw new AccessDeniedHttpException(); } } $order->billing_street1 = $_REQUEST['street_address']; $order->billing_street2 = $_REQUEST['street_address2']; $order->billing_city = $_REQUEST['city']; $order->billing_postal_code = $_REQUEST['zip']; $order->billing_phone = $_REQUEST['phone']; $order->billing_zone = $_REQUEST['state']; $order->billing_country = $_REQUEST['country']; $order->save(); if (Unicode::strtolower($_REQUEST['email']) !== Unicode::strtolower($order->getEmail())) { uc_order_comment_save($order->id(), 0, t('Customer used a different e-mail address during payment: !email', array('!email' => SafeMarkup::checkPlain($_REQUEST['email']))), 'admin'); } if ($_REQUEST['credit_card_processed'] == 'Y' && is_numeric($_REQUEST['total'])) { $comment = t('Paid by !type, 2Checkout.com order #!order.', array('!type' => $_REQUEST['pay_method'] == 'CC' ? t('credit card') : t('echeck'), '!order' => SafeMarkup::checkPlain($_REQUEST['order_number']))); uc_payment_enter($order->id(), '2checkout', $_REQUEST['total'], 0, NULL, $comment); } else { drupal_set_message(t('Your order will be processed as soon as your payment clears at 2Checkout.com.')); uc_order_comment_save($order->id(), 0, t('!type payment is pending approval at 2Checkout.com.', array('!type' => $_REQUEST['pay_method'] == 'CC' ? t('Credit card') : t('eCheck'))), 'admin'); } // Empty that cart... uc_cart_empty($cart_id); // Add a comment to let sales team know this came in through the site. uc_order_comment_save($order->id(), 0, t('Order created through website.'), 'admin'); $build = uc_cart_complete_sale($order, $cart_config->get('new_customer_login')); return $build; }
/** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { $uid = $this->currentUser()->id(); if (!$form_state->isValueEmpty('order_comment')) { uc_order_comment_save($form_state->getValue('order_id'), $uid, $form_state->getValue('order_comment'), 'order', $form_state->getValue('status'), $form_state->getValue('notify')); } if (!$form_state->isValueEmpty('admin_comment')) { uc_order_comment_save($form_state->getValue('order_id'), $uid, $form_state->getValue('admin_comment')); } if ($form_state->getValue('status') != $form_state->getValue('current_status')) { Order::load($form_state->getValue('order_id'))->setStatusId($form_state->getValue('status'))->save(); if ($form_state->isValueEmpty('order_comment')) { uc_order_comment_save($form_state->getValue('order_id'), $uid, '-', 'order', $form_state->getValue('status'), $form_state->getValue('notify')); } } // Let Rules send email if requested. // if ($form_state->getValue('notify')) { // $order = Order::load($form_state->getValue('order_id')); // rules_invoke_event('uc_order_status_email_update', $order); // } drupal_set_message($this->t('Order updated.')); }
/** * Processes Instant Payment Notifications from PayPal. * * @param array $ipn * The IPN data. */ protected function processIpn($ipn) { $amount = $ipn['mc_gross']; $email = !empty($ipn['business']) ? $ipn['business'] : $ipn['receiver_email']; $txn_id = $ipn['txn_id']; if (!isset($ipn['invoice'])) { \Drupal::logger('uc_paypal')->error('IPN attempted with invalid order ID.'); return; } // Extract order and cart IDs. $order_id = $ipn['invoice']; if (strpos($order_id, '-') > 0) { list($order_id, $cart_id) = explode('-', $order_id); \Drupal::service('session')->set('uc_cart_id', $cart_id); } $order = Order::load($order_id); if (!$order) { \Drupal::logger('uc_paypal')->error('IPN attempted for non-existent order @order_id.', ['@order_id' => $order_id]); return; } // @todo Send method name and order ID in the IPN URL? $config = \Drupal::service('plugin.manager.uc_payment.method')->createFromOrder($order)->getConfiguration(); // Optionally log IPN details. if (!empty($config['wps_debug_ipn'])) { \Drupal::logger('uc_paypal')->notice('Receiving IPN at URL for order @order_id. <pre>@debug</pre>', ['@order_id' => $order_id, '@debug' => print_r($ipn, TRUE)]); } // Express Checkout IPNs may not have the WPS email stored. But if it is, // make sure that the right account is being paid. if (!empty($config['wps_email']) && Unicode::strtolower($email) != Unicode::strtolower($config['wps_email'])) { \Drupal::logger('uc_paypal')->error('IPN for a different PayPal account attempted.'); return; } // Determine server. if (empty($data['test_ipn'])) { $host = 'https://www.paypal.com/cgi-bin/webscr'; } else { $host = 'https://www.sandbox.paypal.com/cgi-bin/webscr'; } // POST IPN data back to PayPal to validate. try { $response = \Drupal::httpClient()->request('POST', $host, ['form_params' => ['cmd' => '_notify-validate'] + $ipn]); } catch (TransferException $e) { \Drupal::logger('uc_paypal')->error('IPN validation failed with HTTP error %error.', ['%error' => $e->getMessage()]); return; } // Check IPN validation response to determine if the IPN was valid.. if ($response->getBody() != 'VERIFIED') { \Drupal::logger('uc_paypal')->error('IPN transaction failed verification.'); uc_order_comment_save($order_id, 0, $this->t('An IPN transaction failed verification for this order.'), 'admin'); return; } // Check for a duplicate transaction ID. $duplicate = (bool) db_query_range('SELECT 1 FROM {uc_payment_paypal_ipn} WHERE txn_id = :id AND status <> :status', 0, 1, [':id' => $txn_id, ':status' => 'Pending'])->fetchField(); if ($duplicate) { if ($order->getPaymentMethodId() != 'credit') { \Drupal::logger('uc_paypal')->notice('IPN transaction ID has been processed before.'); } return; } db_insert('uc_payment_paypal_ipn')->fields(array('order_id' => $order_id, 'txn_id' => $txn_id, 'txn_type' => $ipn['txn_type'], 'mc_gross' => $amount, 'status' => $ipn['payment_status'], 'receiver_email' => $email, 'payer_email' => $ipn['payer_email'], 'received' => REQUEST_TIME))->execute(); switch ($ipn['payment_status']) { case 'Canceled_Reversal': uc_order_comment_save($order_id, 0, $this->t('PayPal has canceled the reversal and returned @amount @currency to your account.', ['@amount' => uc_currency_format($amount, FALSE), '@currency' => $ipn['mc_currency']]), 'admin'); break; case 'Completed': if (abs($amount - $order->getTotal()) > 0.01) { \Drupal::logger('uc_paypal')->warning('Payment @txn_id for order @order_id did not equal the order total.', ['@txn_id' => $txn_id, '@order_id' => $order->id(), 'link' => Link::createFromRoute($this->t('view'), 'entity.uc_order.canonical', ['uc_order' => $order->id()])->toString()]); } $comment = $this->t('PayPal transaction ID: @txn_id', ['@txn_id' => $txn_id]); uc_payment_enter($order_id, 'paypal_wps', $amount, $order->getOwnerId(), NULL, $comment); uc_order_comment_save($order_id, 0, $this->t('PayPal IPN reported a payment of @amount @currency.', ['@amount' => uc_currency_format($amount, FALSE), '@currency' => $ipn['mc_currency']])); break; case 'Denied': uc_order_comment_save($order_id, 0, $this->t("You have denied the customer's payment."), 'admin'); break; case 'Expired': uc_order_comment_save($order_id, 0, $this->t('The authorization has failed and cannot be captured.'), 'admin'); break; case 'Failed': uc_order_comment_save($order_id, 0, $this->t("The customer's attempted payment from a bank account failed."), 'admin'); break; case 'Pending': $order->setStatusId('paypal_pending')->save(); uc_order_comment_save($order_id, 0, $this->t('Payment is pending at PayPal: @reason', ['@reason' => $this->pendingMessage($ipn['pending_reason'])]), 'admin'); break; // You, the merchant, refunded the payment. // You, the merchant, refunded the payment. case 'Refunded': $comment = $this->t('PayPal transaction ID: @txn_id', ['@txn_id' => $txn_id]); uc_payment_enter($order_id, 'paypal_wps', $amount, $order->getOwnerId(), NULL, $comment); break; case 'Reversed': \Drupal::logger('uc_paypal')->error('PayPal has reversed a payment!'); uc_order_comment_save($order_id, 0, $this->t('Payment has been reversed by PayPal: @reason', ['@reason' => $this->reversalMessage($ipn['reason_code'])]), 'admin'); break; case 'Processed': uc_order_comment_save($order_id, 0, $this->t('A payment has been accepted.'), 'admin'); break; case 'Voided': uc_order_comment_save($order_id, 0, $this->t('The authorization has been voided.'), 'admin'); break; } }
/** * Submit handler for the "Cancel" button on the checkout form. */ public function cancel(array &$form, FormStateInterface $form_state) { $order = $form_state->get('order'); $session = \Drupal::service('session'); if ($session->has('cart_order') && $session->get('cart_order') == $order->id()) { uc_order_comment_save($session->get('cart_order'), 0, $this->t('Customer canceled this order from the checkout form.')); $session->remove('cart_order'); } unset($_SESSION['uc_checkout'][$order->id()]); $form_state->setRedirect('uc_cart.cart'); }
/** * Builds and processes an order pane defined by hook_uc_order_pane(). * * @param $op * The operation the pane is performing. Possible values are "view", * "customer", "edit-form", "edit-theme" or "edit-process". * @param $order * The order being viewed or edited. * @param $form * The order's edit form. NULL for non-edit ops. * @param &$form_state * The form state array of the edit form. NULL for non-edit ops. * * @return * Varies according to the value of $op: * - view: A render array showing admin-visible order data. * - customer: A render array showing customer-visible order data. * - edit-form: $form with the pane grafted in. * - edit-theme: The rendered portion of the $form that the pane added. * - edit-process: An array of values to be modified on the order object, * keyed by the object's property, or NULL to signify no change on the order * object. */ function uc_order_pane_callback($op, $order, &$form = NULL, &$form_state = NULL) { global $user; switch ($op) { case 'view': $comments = uc_order_comments_load($order->order_id, TRUE); return tapir_get_table('uc_op_admin_comments_view_table', $comments); case 'edit-form': $form['admin_comment_field'] = array('#type' => 'fieldset', '#title' => t('Add an admin comment'), '#collapsible' => TRUE, '#collapsed' => TRUE); $form['admin_comment_field']['admin_comment'] = array('#type' => 'textarea', '#description' => t('Admin comments are only seen by store administrators.')); return $form; case 'edit-theme': $comments = uc_order_comments_load($form['order_id']['#value'], TRUE); if (is_array($comments) && count($comments) > 0) { foreach ($comments as $comment) { $items[] = '[' . theme('uc_uid', array('uid' => $comment->uid)) . '] ' . filter_xss_admin($comment->message); } } else { $items = array(t('No admin comments have been entered for this order.')); } $output = theme('item_list', array('items' => $items)) . drupal_render($form['admin_comment_field']); return $output; case 'edit-process': if (!empty($order['admin_comment'])) { uc_order_comment_save($order['order_id'], $user->uid, $order['admin_comment']); } return; } }
/** * Completes the sale and finishes checkout. */ public function complete() { if (!$this->session->has('cart_order') || !$this->session->has('uc_checkout_complete_' . $this->session->get('cart_order'))) { return $this->redirect('uc_cart.cart'); } $order = $this->loadOrder(); if (empty($order)) { // Display messages to customers and the administrator if the order was lost. drupal_set_message($this->t("We're sorry. An error occurred while processing your order that prevents us from completing it at this time. Please contact us and we will resolve the issue as soon as possible."), 'error'); $this->logger('uc_cart')->error('An empty order made it to checkout! Cart order ID: @cart_order', ['@cart_order' => $this->session->get('cart_order')]); return $this->redirect('uc_cart.cart'); } $cart_config = $this->config('uc_cart.settings'); $build = $this->cartManager->completeSale($order, $cart_config->get('new_customer_login')); $this->session->remove('uc_checkout_complete_' . $this->session->get('cart_order')); $this->session->remove('cart_order'); // Add a comment to let sales team know this came in through the site. uc_order_comment_save($order->id(), 0, $this->t('Order created through website.'), 'admin'); return $build; }
/** * Builds and proceses a pane defined by hook_uc_checkout_pane(). * * @param $op * The operation the pane is performing. Possible values are "view", * "process", "review", and "settings". * @param $order * The order being viewed or edited. * @param $form * The order's edit form. NULL for non-edit ops. * @param &$form_state * The form state array of the edit form. NULL for non-edit ops. * * @return * Varies according to the value of $op: * - view: An array with two keys, "contents" and an optional "description". * "contents" is a form array to collect the checkout data for the pane. The * description provides help text for the pane as a whole. * - process: A boolean indicating that checkout should continue. During this * op, $order should be modified with the values in * $form_state['values']['panes'][PANE_ID]. * - review: An array containing review sections. A review section contains * "title" and "data" keys which have HTML to be displayed on the checkout * review page. * - settings: A settings form which can be used with system_settings_form(). */ function uc_checkout_pane_callback($op, $order, $form = NULL, &$form_state = NULL) { // uc_checkout_pane_comments() switch ($op) { case 'view': $description = t('Use this area for special instructions or questions regarding your order.'); if (!empty($order->order_id)) { $default = db_query("SELECT message FROM {uc_order_comments} WHERE order_id = :id", array(':id' => $order->order_id))->fetchField(); } else { $default = NULL; } $contents['comments'] = array('#type' => 'textarea', '#title' => t('Order comments'), '#default_value' => $default); return array('description' => $description, 'contents' => $contents); case 'process': if ($form_state['values']['panes']['comments']['comments']) { db_delete('uc_order_comments')->condition('order_id', $order->order_id)->execute(); uc_order_comment_save($order->order_id, 0, $form_state['values']['panes']['comments']['comments'], 'order', uc_order_state_default('post_checkout'), TRUE); } return TRUE; case 'review': $review = NULL; $result = db_query("SELECT message FROM {uc_order_comments} WHERE order_id = :id", array(':id' => $order->order_id)); if ($comment = $result->fetchObject()) { $review[] = array('title' => t('Comment'), 'data' => check_plain($comment->message)); } return $review; } }
public function wppCharge($order_id, $amount, $data) { $order = Order::load($order_id); $paypal_config = $this->config('uc_paypal.settings'); if ($data['txn_type'] == UC_CREDIT_PRIOR_AUTH_CAPTURE) { $nvp_request = array('METHOD' => 'DoCapture', 'AUTHORIZATIONID' => $data['auth_id'], 'AMT' => uc_currency_format($amount, FALSE, FALSE, '.'), 'CURRENCYCODE' => $order->getCurrency(), 'COMPLETETYPE' => 'Complete'); } else { list($desc, $subtotal) = _uc_paypal_product_details($order->products); if (intval($order->payment_details['cc_exp_month']) < 10) { $expdate = '0' . $order->payment_details['cc_exp_month'] . $order->payment_details['cc_exp_year']; } else { $expdate = $order->payment_details['cc_exp_month'] . $order->payment_details['cc_exp_year']; } $cc_type = NULL; if (isset($order->payment_details['cc_type'])) { switch (strtolower($order->payment_details['cc_type'])) { case 'amex': case 'american express': $cc_type = 'Amex'; break; case 'visa': $cc_type = 'Visa'; break; case 'mastercard': case 'master card': $cc_type = 'MasterCard'; break; case 'discover': $cc_type = 'Discover'; break; } } if (is_null($cc_type)) { $cc_type = $this->cardType($order->payment_details['cc_number']); if ($cc_type === FALSE) { drupal_set_message(t('The credit card type did not pass validation.'), 'error'); \Drupal::logger('uc_paypal')->error('Could not figure out cc type: @number / @type', ['@number' => $order->payment_details['cc_number'], '@type' => $order->payment_details['cc_type']]); return array('success' => FALSE); } } // PayPal doesn't accept IPv6 addresses. $ip_address = ltrim(\Drupal::request()->getClientIp(), '::ffff:'); $nvp_request = array('METHOD' => 'DoDirectPayment', 'PAYMENTACTION' => $data['txn_type'] == UC_CREDIT_AUTH_ONLY ? 'Authorization' : 'Sale', 'IPADDRESS' => $ip_address, 'AMT' => uc_currency_format($amount, FALSE, FALSE, '.'), 'CREDITCARDTYPE' => $cc_type, 'ACCT' => $order->payment_details['cc_number'], 'EXPDATE' => $expdate, 'CVV2' => $order->payment_details['cc_cvv'], 'FIRSTNAME' => substr($order->billing_first_name, 0, 25), 'LASTNAME' => substr($order->billing_last_name, 0, 25), 'STREET' => substr($order->billing_street1, 0, 100), 'STREET2' => substr($order->billing_street2, 0, 100), 'CITY' => substr($order->billing_city, 0, 40), 'STATE' => $order->billing_zone, 'ZIP' => $order->billing_postal_code, 'COUNTRYCODE' => $order->billing_country, 'CURRENCYCODE' => $order->getCurrency(), 'DESC' => substr($desc, 0, 127), 'INVNUM' => $order_id . '-' . REQUEST_TIME, 'BUTTONSOURCE' => 'Ubercart_ShoppingCart_DP_US', 'NOTIFYURL' => Url::fromRoute('uc_paypal.ipn', [], ['absolute' => TRUE])->toString(), 'EMAIL' => substr($order->getEmail(), 0, 127), 'PHONENUM' => substr($order->billing_phone, 0, 20)); if ($order->isShippable() && !empty($order->delivery_first_name)) { $shipdata = array('SHIPTONAME' => substr($order->delivery_first_name . ' ' . $order->delivery_last_name, 0, 25), 'SHIPTOSTREET' => substr($order->delivery_street1, 0, 100), 'SHIPTOSTREET2' => substr($order->delivery_street2, 0, 100), 'SHIPTOCITY' => substr($order->delivery_city, 0, 40), 'SHIPTOSTATE' => $order->delivery_zone, 'SHIPTOZIP' => $order->delivery_postal_code, 'SHIPTOCOUNTRYCODE' => $order->delivery_country); $nvp_request += $shipdata; } if ($paypal_config->get('uc_credit_cvv_enabled')) { $nvp_request['CVV2'] = $order->payment_details['cc_cvv']; } } $nvp_response = uc_paypal_api_request($nvp_request, $paypal_config->get('wpp_server')); $types = uc_credit_transaction_types(); switch ($nvp_response['ACK']) { case 'SuccessWithWarning': \Drupal::logger('uc_paypal')->warning('<b>@type succeeded with a warning.</b>@paypal_message', array('@paypal_message' => $this->buildErrorMessages($nvp_response), '@type' => $types[$data['txn_type']], 'link' => Link::createFromRoute(t('view order'), 'entity.uc_order.canonical', ['uc_order' => $order_id])->toString())); // Fall through. // Fall through. case 'Success': $message = t('<b>@type</b><br /><b>Success: </b>@amount @currency', ['@type' => $types[$data['txn_type']], '@amount' => uc_currency_format($nvp_response['AMT'], FALSE), '@currency' => $nvp_response['CURRENCYCODE']]); if ($data['txn_type'] != UC_CREDIT_PRIOR_AUTH_CAPTURE) { $message .= '<br />' . t('<b>Address:</b> @avscode', ['@avscode' => $this->avscodeMessage($nvp_response['AVSCODE'])]); if ($paypal_config->get('uc_credit_cvv_enabled')) { $message .= '<br />' . t('<b>CVV2:</b> @cvvmatch', ['@cvvmatch' => $this->cvvmatchMessage($nvp_response['CVV2MATCH'])]); } } $result = array('success' => TRUE, 'comment' => t('PayPal transaction ID: @transactionid', ['@transactionid' => $nvp_response['TRANSACTIONID']]), 'message' => $message, 'data' => SafeMarkup::checkPlain($nvp_response['TRANSACTIONID']), 'uid' => $this->currentUser()->id()); // If this was an authorization only transaction... if ($data['txn_type'] == UC_CREDIT_AUTH_ONLY) { // Log the authorization to the order. uc_credit_log_authorization($order_id, $nvp_response['TRANSACTIONID'], $nvp_response['AMT']); } elseif ($data['txn_type'] == UC_CREDIT_PRIOR_AUTH_CAPTURE) { uc_credit_log_prior_auth_capture($order_id, $data['auth_id']); } // Log the IPN to the database. db_insert('uc_payment_paypal_ipn')->fields(array('order_id' => $order->id(), 'txn_id' => $nvp_response['TRANSACTIONID'], 'txn_type' => 'web_accept', 'mc_gross' => $amount, 'status' => 'Completed', 'payer_email' => $order->getEmail(), 'received' => REQUEST_TIME))->execute(); break; case 'FailureWithWarning': // Fall through. // Fall through. case 'Failure': $message = t('<b>@type failed.</b>', ['@type' => $types[$data['txn_type']]]) . $this->buildErrorMessages($nvp_response); $result = array('success' => FALSE, 'message' => $message, 'uid' => $this->currentUser()->id()); break; default: $message = t('Unexpected acknowledgement status: @status', ['@status' => $nvp_response['ACK']]); $result = array('success' => NULL, 'message' => $message, 'uid' => $this->currentUser()->id()); break; } uc_order_comment_save($order_id, $this->currentUser()->id(), $message, 'admin'); // Don't log this as a payment money wasn't actually captured. if (in_array($data['txn_type'], array(UC_CREDIT_AUTH_ONLY))) { $result['log_payment'] = FALSE; } return $result; }
/** * Handler when cart/icepay_result is callback * * @return string */ public function runPageCartResult() { $logger = \Icepay_Api_Logger::getInstance(); $logger->enableLogging()->setLoggingLevel(\Icepay_Api_Logger::LEVEL_ERRORS_AND_TRANSACTION)->logToFunction("logWrapper", "log"); $config = \Drupal::config("uc_icepay.settings"); /* postback */ if ($_SERVER['REQUEST_METHOD'] == 'POST') { $icepay = \Icepay_Project_Helper::getInstance()->postback(); $icepay->setMerchantID($config->get("merchant_id"))->setSecretCode($config->get("secret_code"))->doIPCheck(true); if ($config->get("ipcheck") && $config->get("ipcheck_list") != '') { $ipRanges = explode(",", $config->get("ipcheck_list")); foreach ($ipRanges as $ipRange) { $ip = explode("-", $ipRange); $icepay->setIPRange($ip[0], $ip[1]); } } if ($icepay->validate()) { $data = $icepay->GetPostback(); $orderID = $data->reference; $order = uc_order_load($orderID); if (!$order) { return t("Order not exists"); } $firstPostback = Database::getConnection()->select('uc_payment_icepay', 'i')->fields('i', array('transaction_id'))->condition('transaction_id', $data->transactionID, '=')->execute()->fetchAssoc(); $paymentDetails = IcepayApi::getPaymentDetailsByOrderId($orderID); if ($icepay->canUpdateStatus($paymentDetails->icepay_status)) { $order->icepay_status = $data->status; $order->transaction_id = $data->transactionID; IcepayApi::enterPayment($order); // updating order status, this one is deprecated //uc_order_update_status($orderID, IcepayApi::getUbercartStatusCode($data->status)); // updating order status, using direct save into order $order->setStatusId(IcepayApi::getUbercartStatusCode($data->status))->save(); } // adding new comment order uc_order_comment_save($orderID, 1, t($data->statusCode), 'order', IcepayApi::getUbercartStatusCode($data->status), true); // need to save into order payment if postback from Icepay is confirming payment received // @see Drupal/uc_payment/Form/OrderPaymentsForm::submitForm() if (strtoupper($data->status) == "OK" || strtoupper($data->status) == "REFUND") { $orderTotal = $order->getTotal(); // when refund, means order total is requested back if (strtoupper($data->status) == "REFUND") { $orderTotal *= -1; } uc_payment_enter($orderID, $paymentDetails->payment_method, $orderTotal, \Drupal::currentUser()->id(), '', $data->statusCode, REQUEST_TIME); } // best to record this into watch log // https://drupalize.me/blog/201510/how-log-messages-drupal-8 \Drupal::logger('uc_icepay')->info('Icepay Postback :: ' . $data->statusCode); // need to send notification due to order status update if (isset($firstPostback['transaction_id'])) { // this rules invoke to send order status update by email is deprecated //rules_invoke_event('uc_order_status_email_update', $order); } } else { if ($icepay->isVersionCheck()) { $dump = array("module" => sprintf(t("Version %s using PHP API 2 version %s"), ICEPAY_VERSION, Icepay_Project_Helper::getInstance()->getReleaseVersion()), "notice" => "Checksum validation passed!"); if ($icepay->validateVersion()) { $name = "uc_cart"; $path = drupal_get_path('module', $name) . '/' . $name . '.info'; $data = drupal_parse_info_file($path); $dump["additional"] = array("Drupal" => VERSION, "Ubercart" => $data["version"]); } else { $dump["notice"] = "Checksum failed! Merchant ID and Secret code probably incorrect."; } var_dump($dump); exit; } } return t("Postback script functions properly"); } else { $icepay = \Icepay_Project_Helper::getInstance()->result(); $icepay->setMerchantID($config->get("merchant_id"))->setSecretCode($config->get("secret_code")); if (!$icepay->validate()) { $data = $icepay->getResultData(); //$output = $data->statusCode; //return $output; drupal_set_message($data->statusCode, 'error'); $response = new RedirectResponse(\Drupal::url('uc_cart.checkout')); $response->send(); } else { $data = $icepay->getResultData(); if ($data->status == 'ERR') { //$output = $data->statusCode; //return $output; drupal_set_message($data->statusCode, 'error'); return new RedirectResponse(\Drupal::url('uc_cart.checkout')); } $order = uc_order_load($data->reference); if (!$order) { return t("Order with id :orderId not exist", array(":orderId" => $data->reference)); } $session = \Drupal::service('session'); if (!$session->get('cart_order')) { drupal_set_message(t("Cart is currently empty."), 'error'); return new RedirectResponse(\Drupal::url('uc_cart.checkout')); } //$order->icepay_status = \ICEPAY_STATUSCODE::SUCCESS; $order->icepay_status = $data->status; $order->transaction_id = $data->transactionID; IcepayApi::enterPayment($order); // update order status $order->setStatusId(IcepayApi::getUbercartStatusCode($data->status))->save(); $_SESSION['uc_checkout'][$session->get('cart_order')]['do_complete'] = TRUE; // $response = new RedirectResponse(Url::fromRoute('uc_cart.checkout_complete')->toString()); // $response->send(); return new RedirectResponse(\Drupal::url('uc_cart.checkout_complete')); } } }
/** * React on INS messages from 2Checkout. * * @param \Symfony\Component\HttpFoundation\Request $request * The request of the page. */ public function notification(Request $request) { $values = $request->request; \Drupal::logger('uc_2checkout')->notice('Received 2Checkout notification with following data: @data', ['@data' => print_r($values->all(), TRUE)]); $module_config = $this->config('uc_2checkout.settings'); if ($values->has('message_type') && $values->has('md5_hash') && $values->has('message_id')) { // Validate the hash $secret_word = $module_config->get('secret_word'); $sid = $module_config->get('sid'); $twocheckout_order_id = $values->get('sale_id'); $twocheckout_invoice_id = $values->get('invoice_id'); $hash = strtoupper(md5($twocheckout_order_id . $sid . $twocheckout_invoice_id . $secret_word)); if ($hash != $values->get('md5_hash')) { \Drupal::logger('uc_2checkout')->notice('2Checkout notification #@num had a wrong hash.', ['@num' => $values->get('message_id')]); die('Hash Incorrect'); } $order_id = $values->get('vendor_order_id'); $order = Order::load($order_id); if ($values->get('message_type') == 'FRAUD_STATUS_CHANGED') { switch ($values->get('fraud_status')) { // @todo: I think this still needs a lot of work, I don't see anywhere that it // validates the INS against an order in the DB then changes order status if the // payment was successful, like PayPal IPN does ... case 'pass': break; case 'wait': break; case 'fail': // @todo uc_order_update_status($order_id, uc_order_state_default('canceled')); $order->setStatusId('canceled')->save(); uc_order_comment_save($order_id, 0, $this->t('Order have not passed 2Checkout fraud review.')); die('fraud'); break; } } elseif ($values->get('message_type') == 'REFUND_ISSUED') { // @todo uc_order_update_status($order_id, uc_order_state_default('canceled')); $order->setStatusId('canceled')->save(); uc_order_comment_save($order_id, 0, $this->t('Order have been refunded through 2Checkout.')); die('refund'); } } die('ok'); }
/** * {@inheritdoc} */ protected function chargeCard($order, $amount, $txn_type, $reference = NULL) { $user = \Drupal::currentUser(); // cc_exp_month and cc_exp_year are also validated by // _uc_credit_valid_card_expiration() on the checkout form. $month = $order->payment_details['cc_exp_month']; $year = $order->payment_details['cc_exp_year']; if ($year < 100) { $year = $year + 2000; } // Card is expired at 0:00 on the first day of the next month. $expiration_date = mktime(0, 0, 0, $month + 1, 1, $year); // Conditions for failure are described in file documentation block above. // All other transactions will succeed. if ($order->payment_details['cc_number'] == '0000000000000000' || isset($order->payment_details['cc_cvv']) && $order->payment_details['cc_cvv'] == '000' || $expiration_date - REQUEST_TIME <= 0 || $amount == 12.34 || $order->billing_first_name == 'Fictitious' || $order->billing_phone == '8675309') { $success = FALSE; } else { $success = TRUE; } // The information for the payment is in the $order->payment_details array. if ($this->configuration['debug']) { \Drupal::logger('uc_credit')->notice('Test gateway payment details @details.', ['@details' => print_r($order->payment_details, TRUE)]); } if ($success) { $message = $this->t('Credit card charged: @amount', ['@amount' => uc_currency_format($amount)]); uc_order_comment_save($order->id(), $user->id(), $message, 'admin'); } else { $message = $this->t('Credit card charge failed.'); uc_order_comment_save($order->id(), $user->id(), $message, 'admin'); } $result = array('success' => $success, 'comment' => $this->t('Card charged, resolution code: 0022548315'), 'message' => $success ? $this->t('Credit card payment processed successfully.') : $this->t('Credit card charge failed.'), 'uid' => $user->id()); return $result; }
/** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { $paypal_config = $this->config('uc_paypal.settings'); $session = \Drupal::service('session'); $order = Order::load($session->get('cart_order')); if (!$form_state->isValueEmpty('shippable')) { $quote_option = explode('---', $form_state->getValue(['quotes', 'quote_option'])); $order->quote['method'] = $quote_option[0]; $order->quote['accessorials'] = $quote_option[1]; $method = ShippingQuoteMethod::load($quote_option[0]); $label = $method['quote']['accessorials'][$quote_option[1]]; // $label = $method->label(); $quote_option = $form_state->getValue(['quotes', 'quote_option']); $order->quote['rate'] = $form_state->getValue(['quotes', $quote_option, 'rate']); $result = db_query("SELECT line_item_id FROM {uc_order_line_items} WHERE order_id = :id AND type = :type", [':id' => $order->id(), ':type' => 'shipping']); if ($lid = $result->fetchField()) { uc_order_update_line_item($lid, $label, $order->quote['rate']); } else { uc_order_line_item_add($order->id(), 'shipping', $label, $order->quote['rate']); } } if ($paypal_config->get('ec_review_company')) { $order->delivery_company = $form_state->getValue('delivery_company'); } if ($paypal_config->get('ec_review_phone')) { $order->delivery_phone = $form_state->getValue('delivery_phone'); } if ($paypal_config->get('ec_review_comment')) { db_delete('uc_order_comments')->condition('order_id', $order->id())->execute(); uc_order_comment_save($order->id(), 0, $form_state->getValue('order_comments'), 'order'); } $order->save(); $form_state->setRedirect('uc_paypal.ec_submit'); }
/** * Submit handler for the "Cancel" button on the checkout form. */ public function cancel(array &$form, FormStateInterface $form_state) { $order = $form_state->get('order'); if ($this->session->get('cart_order') == $order->id()) { uc_order_comment_save($order->id(), 0, $this->t('Customer canceled this order from the checkout form.')); $this->session->remove('cart_order'); } $this->session->remove('uc_checkout_review_' . $order->id()); $this->session->remove('uc_checkout_complete_' . $order->id()); $form_state->setRedirect('uc_cart.cart'); }
/** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { switch ($form_state->getValue('customer_type')) { case 'search': $uid = $form_state->getValue(['customer', 'uid']); break; case 'create': // Create new account. $email = trim($form_state->getValue(['customer', 'email'])); $fields = array('name' => uc_store_email_to_username($email), 'mail' => $email, 'pass' => user_password(), 'status' => $this->config('uc_cart.settings')->get('new_customer_status_active') ? 1 : 0); $account = \Drupal\user\Entity\User::create($fields); $account->save(); $uid = $account->id(); if ($form_state->getValue(['customer', 'sendmail'])) { // Manually set the password so it appears in the e-mail. $account->password = $fields['pass']; \Drupal::service('plugin.manager.mail')->mail('user', 'register_admin_created', $email, uc_store_mail_recipient_langcode($email), array('account' => $account), uc_store_email_from()); drupal_set_message(t('A welcome message has been e-mailed to the new user.')); } break; default: $uid = 0; } $order = \Drupal\uc_order\Entity\Order::create(array('uid' => $uid, 'order_status' => uc_order_state_default('post_checkout'))); $order->save(); uc_order_comment_save($order->id(), \Drupal::currentUser()->id(), t('Order created by the administration.'), 'admin'); $form_state->setRedirect('entity.uc_order.edit_form', ['uc_order' => $order->id()]); }
protected function ucCreateOrder($customer) { $order = Order::create(array('uid' => $customer->id())); $order->save(); uc_order_comment_save($order->id(), 0, t('Order created programmatically.'), 'admin'); $order_ids = \Drupal::entityQuery('uc_order')->condition('order_id', $order->id())->execute(); $this->assertTrue(in_array($order->id(), $order_ids), SafeMarkup::format('Found order ID @order_id', ['@order_id' => $order->id()])); $country_manager = \Drupal::service('country_manager'); $country = array_rand($country_manager->getEnabledList()); $zones = $country_manager->getZoneList($country); $delivery_address = new Address(); $delivery_address->first_name = $this->randomMachineName(12); $delivery_address->last_name = $this->randomMachineName(12); $delivery_address->street1 = $this->randomMachineName(12); $delivery_address->street2 = $this->randomMachineName(12); $delivery_address->city = $this->randomMachineName(12); $delivery_address->zone = array_rand($zones); $delivery_address->postal_code = mt_rand(10000, 99999); $delivery_address->country = $country; $billing_address = new Address(); $billing_address->first_name = $this->randomMachineName(12); $billing_address->last_name = $this->randomMachineName(12); $billing_address->street1 = $this->randomMachineName(12); $billing_address->street2 = $this->randomMachineName(12); $billing_address->city = $this->randomMachineName(12); $billing_address->zone = array_rand($zones); $billing_address->postal_code = mt_rand(10000, 99999); $billing_address->country = $country; $order->setAddress('delivery', $delivery_address)->setAddress('billing', $billing_address)->save(); // Force the order to load from the DB instead of the entity cache. $db_order = \Drupal::entityManager()->getStorage('uc_order')->loadUnchanged($order->id()); // Compare delivery and billing addresses to those loaded from the database. $db_delivery_address = $db_order->getAddress('delivery'); $db_billing_address = $db_order->getAddress('billing'); $this->assertEqual($delivery_address, $db_delivery_address, 'Delivery address is equal to delivery address in database.'); $this->assertEqual($billing_address, $db_billing_address, 'Billing address is equal to billing address in database.'); return $order; }