public function testFilePurchaseCheckout()
 {
     // Add file download feature to the test product.
     $filename = $this->getTestFile();
     $this->drupalLogin($this->adminUser);
     $this->drupalPostForm('node/' . $this->product->id() . '/edit/features', array('feature' => 'file'), t('Add'));
     $edit = array('uc_file_model' => '', 'uc_file_filename' => $filename);
     $this->drupalPostForm(NULL, $edit, t('Save feature'));
     // Check out with the test product.
     $method = $this->createPaymentMethod('other');
     $this->addToCart($this->product);
     $order = $this->checkout();
     uc_payment_enter($order->id(), $method['id'], $order->getTotal());
     // Test that the file was granted.
     // @todo Re-enable when Rules is available.
     // $this->assertTrue($order->getUser()->hasFile($filename), 'Existing user was granted file.');
     // Test that the email is correct.
     //    $file = entity_load('user_file', $fid);
     // @todo Re-enable when Rules is available.
     // $this->assertMailString('subject', $file->label(), 4, 'File assignment email mentions file in subject line.');
     // Delete the user.
     user_delete($order->getOwnerId());
     // Run cron to ensure deleted users are handled correctly.
     $this->cronRun();
 }
Exemple #2
0
 /**
  * {@inheritdoc}
  */
 public function orderSubmit(OrderInterface $order)
 {
     if ($order->getTotal() >= 0.01) {
         return array(array('pass' => FALSE, 'message' => t('We cannot process your order without payment.')));
     }
     uc_payment_enter($order->id(), 'free_order', 0, 0, NULL, t('Checkout completed for a free order.'));
 }
 public function testRolePurchaseCheckout()
 {
     // Add role assignment to the test product.
     $rid = $this->drupalCreateRole(array('access content'));
     $this->drupalLogin($this->adminUser);
     $this->drupalPostForm('node/' . $this->product->id() . '/edit/features', array('feature' => 'role'), t('Add'));
     $edit = array('role' => $rid, 'end_override' => TRUE, 'expire_relative_duration' => 1, 'expire_relative_granularity' => 'day');
     $this->drupalPostForm(NULL, $edit, t('Save feature'));
     // Check out with the test product.
     $method = $this->createPaymentMethod('other');
     $this->addToCart($this->product);
     $order = $this->checkout();
     uc_payment_enter($order->id(), $method['id'], $order->getTotal());
     // Test that the role was granted.
     // @todo Re-enable when Rules is available.
     // $this->assertTrue($order->getOwner()->hasRole($rid), 'Existing user was granted role.');
     // Test that the email is correct.
     $role = Role::load($rid);
     // @todo Re-enable when Rules is available.
     // $this->assertMailString('subject', $role->label(), 4, 'Role assignment email mentions role in subject line.');
     // Test that the role product / user relation is deleted with the user.
     user_delete($order->getOwnerId());
     // Run cron to ensure deleted users are handled correctly.
     $this->cronRun();
 }
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     uc_payment_enter($form_state->getValue('order_id'), 'check', $form_state->getValue('amount'), $this->currentUser()->id(), '', $form_state->getValue('comment'));
     db_insert('uc_payment_check')->fields(array('order_id' => $form_state->getValue('order_id'), 'clear_date' => mktime(12, 0, 0, $form_state->getValue('clear_month'), $form_state->getValue('clear_day'), $form_state->getValue('clear_year'))))->execute();
     drupal_set_message($this->t('Check received, expected clear date of @date.', ['@date' => uc_date_format($form_state->getValue('clear_month'), $form_state->getValue('clear_day'), $form_state->getValue('clear_year'))]));
     $form_state->setRedirect('uc_order.admin_view', ['uc_order' => $form_state->getValue('order_id')]);
 }
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     uc_payment_enter($form_state->getValue('order_id'), 'check', $form_state->getValue('amount'), $this->currentUser()->id(), '', $form_state->getValue('comment'));
     $clear_date = $form_state->getValue('clear_date')->getTimestamp();
     db_insert('uc_payment_check')->fields(array('order_id' => $form_state->getValue('order_id'), 'clear_date' => $clear_date))->execute();
     drupal_set_message($this->t('Check received, expected clear date of @date.', ['@date' => \Drupal::service('date.formatter')->format($clear_date, 'uc_store')]));
     $form_state->setRedirect('entity.uc_order.canonical', ['uc_order' => $form_state->getValue('order_id')]);
 }
 /**
  * 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;
 }
 public function testCheckoutFileDownload()
 {
     $this->drupalLogin($this->adminUser);
     $method = $this->createPaymentMethod('other');
     // Add file download to the test product.
     $filename = $this->getTestFile();
     $this->drupalPostForm('node/' . $this->product->id() . '/edit/features', array('feature' => 'file'), t('Add'));
     $this->drupalPostForm(NULL, array('uc_file_filename' => $filename), t('Save feature'));
     // Process an anonymous, shippable order.
     $order = $this->createOrder(['uid' => 0, 'payment_method' => $method['id']]);
     $order->products[1]->data->shippable = 1;
     $order->save();
     uc_payment_enter($order->id(), $method['id'], $order->getTotal());
     // Find the order uid.
     $uid = db_query('SELECT uid FROM {uc_orders} ORDER BY order_id DESC')->fetchField();
     // @todo Re-enable when Rules is available.
     // $account = User::load($uid);
     // $this->assertTrue($account->hasFile($fid), 'New user was granted file.');
     $order = Order::load($order->id());
     $this->assertEqual($order->getStatusId(), 'payment_received', 'Shippable order was set to payment received.');
     // Test that the file shows up on the user's purchased files list.
     //$this->drupalGet('user/' . $uid . '/purchased-files');
     //$this->assertText($filename, 'File found in list of purchased files.');
     // 4 e-mails: new account, customer invoice, admin invoice, file download.
     $this->assertMailString('subject', 'Account details', 4, 'New account email was sent');
     $this->assertMailString('subject', 'Your Order at Ubercart', 4, 'Customer invoice was sent');
     $this->assertMailString('subject', 'New Order at Ubercart', 4, 'Admin notification was sent');
     // @todo Re-enable when Rules is available.
     // $this->assertMailString('subject', 'File Downloads', 4, 'File download notification was sent');
     \Drupal::state()->set('system.test_email_collector', []);
     // Test again with an existing authenticated user and a non-shippable order.
     $order = $this->createOrder(array('uid' => 0, 'primary_email' => $this->customer->getEmail(), 'payment_method' => $method['id']));
     $order->products[2]->data->shippable = 0;
     $order->save();
     uc_payment_enter($order->id(), $method['id'], $order->getTotal());
     $account = User::load($this->customer->id());
     // @todo Re-enable when Rules is available.
     // $this->assertTrue($account->hasFile($fid), 'Existing user was granted file.');
     $order = Order::load($order->id());
     $this->assertEqual($order->getStatusId(), 'completed', 'Non-shippable order was set to completed.');
     // 3 e-mails: customer invoice, admin invoice, file download.
     $this->assertNoMailString('subject', 'Account details', 3, 'New account email was sent');
     $this->assertMailString('subject', 'Your Order at Ubercart', 3, 'Customer invoice was sent');
     $this->assertMailString('subject', 'New Order at Ubercart', 3, 'Admin notification was sent');
     // @todo Re-enable when Rules is available.
     // $this->assertMailString('subject', 'File Downloads', 3, 'File download notification was sent');
 }
 public function testShipmentsUI()
 {
     $this->drupalLogin($this->adminUser);
     $method = $this->createPaymentMethod('other');
     // Process an anonymous, shippable order.
     $order = Order::create(['uid' => 0, 'primary_email' => $this->randomString() . '@example.org', 'payment_method' => $method['id']]);
     // Add three more products to use for our tests.
     $products = array();
     for ($i = 1; $i <= 4; $i++) {
         $product = $this->createProduct(array('uid' => $this->adminUser->id(), 'promote' => 0));
         $order->products[$i] = OrderProduct::create(array('nid' => $product->nid->target_id, 'title' => $product->title->value, 'model' => $product->model, 'qty' => 1, 'cost' => $product->cost->value, 'price' => $product->price->value, 'weight' => $product->weight, 'data' => []));
         $order->products[$i]->data->shippable = 1;
     }
     $order->save();
     $order = Order::load($order->id());
     uc_payment_enter($order->id(), $method['id'], $order->getTotal());
     // Now quickly package all the products in this order.
     $this->drupalGet('admin/store/orders/' . $order->id() . '/packages');
     $this->drupalPostForm(NULL, array('shipping_types[small_package][table][1][checked]' => 1, 'shipping_types[small_package][table][2][checked]' => 1, 'shipping_types[small_package][table][3][checked]' => 1, 'shipping_types[small_package][table][4][checked]' => 1), t('Create one package'));
     // Test "Ship" operations for this package.
     $this->drupalGet('admin/store/orders/' . $order->id() . '/packages');
     $this->assertLink(t('Ship'));
     $this->clickLink(t('Ship'));
     $this->assertUrl('admin/store/orders/' . $order->id() . '/shipments/new?pkgs=1');
     foreach ($order->products as $sequence => $item) {
         $this->assertText($item->qty->value . ' x ' . $item->model->value, 'Product quantity x SKU found.');
         // Test for weight here too? How do we compute this?
     }
     // We're shipping a specific package, so it should already be checked.
     foreach ($order->products as $sequence => $item) {
         $this->assertFieldByName('shipping_types[small_package][table][1][checked]', 1, 'Package is available for shipping.');
     }
     $this->assertFieldByName('method', 'manual', 'Manual shipping method selected.');
     //
     // Test presence and operation of ship operation on order admin View.
     //
     $this->drupalGet('admin/store/orders/view');
     $this->assertLinkByHref('admin/store/orders/' . $order->id() . '/shipments');
     // Test action.
     $this->clickLink(t('Ship'));
     $this->assertResponse(200);
     $this->assertUrl('admin/store/orders/' . $order->id() . '/shipments/new');
     $this->assertText('No shipments have been made for this order.', 'Ship action found.');
     $this->assertText($order->products[1]->qty->value . ' x ' . $order->products[1]->model->value, 'Product quantity x SKU found.');
     $this->assertFieldByName('method', 'manual', 'Manual shipping method selected.');
     // Test reaching this through the shipments tab too ...
 }
 public function testCheckoutRoleAssignment()
 {
     // Add role assignment to the test product.
     $rid = $this->drupalCreateRole(array('access content'));
     $this->drupalLogin($this->adminUser);
     $this->drupalPostForm('node/' . $this->product->id() . '/edit/features', array('feature' => 'role'), t('Add'));
     $this->drupalPostForm(NULL, array('uc_role_role' => $rid), t('Save feature'));
     // Process an anonymous, shippable order.
     $order = $this->createOrder();
     $order->products[1]->data->shippable = 1;
     $order->save();
     uc_payment_enter($order->id(), 'SimpleTest', $order->getTotal());
     // Find the order uid.
     $uid = db_query('SELECT uid FROM {uc_orders} ORDER BY order_id DESC')->fetchField();
     $account = User::load($uid);
     // @todo Re-enable when Rules is available.
     // $this->assertTrue($account->hasRole($rid), 'New user was granted role.');
     $order = Order::load($order->id());
     $this->assertEqual($order->getStatusId(), 'payment_received', 'Shippable order was set to payment received.');
     // 4 e-mails: new account, customer invoice, admin invoice, role assignment
     $this->assertMailString('subject', 'Account details', 4, 'New account email was sent');
     $this->assertMailString('subject', 'Your Order at Ubercart', 4, 'Customer invoice was sent');
     $this->assertMailString('subject', 'New Order at Ubercart', 4, 'Admin notification was sent');
     // @todo Re-enable when Rules is available.
     // $this->assertMailString('subject', 'role granted', 4, 'Role assignment notification was sent');
     \Drupal::state()->set('system.test_email_collector', []);
     // Test again with an existing authenticated user and a non-shippable order.
     $order = $this->createOrder(array('primary_email' => $this->customer->getEmail()));
     $order->products[2]->data->shippable = 0;
     $order->save();
     uc_payment_enter($order->id(), 'SimpleTest', $order->getTotal());
     $account = User::load($this->customer->id());
     // @todo Re-enable when Rules is available.
     // $this->assertTrue($account->hasRole($rid), 'Existing user was granted role.');
     $order = Order::load($order->id());
     $this->assertEqual($order->getStatusId(), 'completed', 'Non-shippable order was set to completed.');
     // 3 e-mails: customer invoice, admin invoice, role assignment
     $this->assertNoMailString('subject', 'Account details', 4, 'New account email was sent');
     $this->assertMailString('subject', 'Your Order at Ubercart', 4, 'Customer invoice was sent');
     $this->assertMailString('subject', 'New Order at Ubercart', 4, 'Admin notification was sent');
     // @todo Re-enable when Rules is available.
     // $this->assertMailString('subject', 'role granted', 4, 'Role assignment notification was sent');
 }
 /**
  * Tests packaging and shipping a simple order with the "Manual" plugin.
  */
 public function testFulfillmentProcess()
 {
     // Log on as administrator to fulfill order.
     $this->drupalLogin($this->adminUser);
     // A payment method for the order.
     $method = $this->createPaymentMethod('other');
     // Create an anonymous, shippable order.
     $order = $this->createOrder(['uid' => 0, 'payment_method' => $method['id']]);
     $order->products[1]->data->shippable = 1;
     $order->save();
     // Check out with the test product.
     uc_payment_enter($order->id(), $method['id'], $order->getTotal());
     // Check for Packages tab and Shipments tab. BOTH should
     // redirect us to $order->id()/packages/new at this point,
     // because we have no packages or shipments yet.
     // Test Packages tab.
     $this->drupalGet('admin/store/orders/' . $order->id());
     // Test presence of tab to package products.
     $this->assertLinkByHref('admin/store/orders/' . $order->id() . '/packages');
     // Go to packages tab.
     $this->clickLink(t('Packages'));
     $this->assertResponse(200);
     // Check redirected path.
     $this->assertUrl('admin/store/orders/' . $order->id() . '/packages/new');
     $this->assertText('This order\'s products have not been organized into packages.', 'Packages tab found.');
     // Test Shipments tab.
     $this->drupalGet('admin/store/orders/' . $order->id());
     // Test presence of tab to make shipments.
     $this->assertLinkByHref('admin/store/orders/' . $order->id() . '/shipments');
     // Go to Shipments tab.
     $this->clickLink(t('Shipments'));
     $this->assertResponse(200);
     // Check redirected path.
     $this->assertUrl('admin/store/orders/' . $order->id() . '/packages/new');
     $this->assertText('This order\'s products have not been organized into packages.', 'Shipments tab found.');
     // Now package the products in this order.
     $this->drupalGet('admin/store/orders/' . $order->id() . '/packages');
     $this->assertText($order->products[1]->title->value, 'Product title found.');
     $this->assertText($order->products[1]->model->value, 'Product sku found.');
     $this->assertFieldByName('shipping_types[small_package][table][' . $order->id() . '][checked]', 0, 'Product is available for packaging.');
     // Select product and create one package.
     $this->drupalPostForm(NULL, array('shipping_types[small_package][table][' . $order->id() . '][checked]' => 1), t('Create one package'));
     // Check that we're now on the package list page.
     $this->assertUrl('admin/store/orders/' . $order->id() . '/packages');
     $this->assertText($order->products[1]->qty->value . ' x ' . $order->products[1]->model->value, 'Product quantity x SKU found.');
     // Test the Shipments tab.
     $this->drupalGet('admin/store/orders/' . $order->id());
     $this->clickLink(t('Shipments'));
     $this->assertResponse(200);
     // Check redirected path.
     $this->assertUrl('admin/store/orders/' . $order->id() . '/shipments/new');
     $this->assertText('No shipments have been made for this order.', 'New shipments page reached.');
     $this->assertText($order->products[1]->qty->value . ' x ' . $order->products[1]->model->value, 'Product quantity x SKU found.');
     $this->assertFieldByName('method', 'manual', 'Manual shipping method selected.');
     // Select all packages and create shipment using the default "Manual" method..
     $this->drupalPostForm(NULL, array('shipping_types[small_package][table][' . $order->id() . '][checked]' => 1), t('Ship packages'));
     // Check that we're now on the shipment details page.
     $this->assertUrl('admin/store/orders/' . $order->id() . '/ship?method_id=manual&0=1');
     $this->assertText('Origin address', 'Origin address pane found.');
     $this->assertText('Destination address', 'Destination address pane found.');
     $this->assertText('Package 1', 'Packages data pane found.');
     $this->assertText('Shipment data', 'Shipment data pane found.');
     // Fill in the details and make the shipment.
     // If we filled the addresses in when we created the order,
     // those values should already be set here.
     //    $this->drupalPostForm(
     //      NULL,
     //      array(
     //        'pickup_address[pickup_address][first_name]' =>
     //        'pickup_address[pickup_address][last_name]' =>
     //        'pickup_address[pickup_address][company]' =>
     //        'pickup_address[pickup_address][street1]' =>
     //        'pickup_address[pickup_address][street2]' =>
     //        'pickup_address[pickup_address][city]' =>
     //        'pickup_address[pickup_address][zone]' =>
     //        'pickup_address[pickup_address][country]' =>
     //        'pickup_address[pickup_address][postal_code]' =>
     //        'delivery_address[pickup_address][first_name]' =>
     //        'delivery_address[pickup_address][last_name]' =>
     //        'delivery_address[pickup_address][company]' =>
     //        'delivery_address[pickup_address][street1]' =>
     //        'delivery_address[pickup_address][street2]' =>
     //        'delivery_address[pickup_address][city]' =>
     //        'delivery_address[pickup_address][zone]' =>
     //        'delivery_address[pickup_address][country]' =>
     //        'delivery_address[pickup_address][postal_code]' =>
     //        'packages[1][pkg_type]' =>
     //        'packages[1][declared_value]' =>
     //        'packages[1][tracking_number]' =>
     //        'packages[1][weight][weight]' =>
     //        'packages[1][weight][units]' =>
     //        'packages[1][dimensions][length]' =>
     //        'packages[1][dimensions][width]' =>
     //        'packages[1][dimensions][height]' =>
     //        'carrier' => 'FedEx',
     //        'accessorials' => 'Standard Overnight',
     //        'transaction_id' =>
     //        'tracking_number' => '1234567890ABCD',
     //        'ship_date[date]' => '1985-10-26',
     //        'expected_deliver[date]' => '2015-10-21',
     //        'cost' => '12.34',
     //      ),
     //      t('Save shipment')
     //    );
     // Check that we're now on the ? page
     //$this->assertUrl('admin/store/orders/' . $order->id() . '/ship?method_id=manual&0=1');
     //$this->assertText(
     //  'Shipment data',
     //  'Shipment data pane found.'
     //);
     // Check View, Edit, Delete, Print, and Packing Slip actions and tabs.
     // Check for "Tracking" order pane after this order has
     // been shipped and a tracking number entered.
     $this->drupalGet('admin/store/orders/' . $order->id());
     $this->assertText(t('Tracking numbers:'), 'Fulfillment order pane found.');
     //$this->assertText(
     //  '1234567890ABCD',
     //  'Tracking number found.'
     //);
 }
Exemple #12
0
 /**
  * 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'));
         }
     }
 }
 /**
  * Finalizes 2Checkout transaction.
  *
  * @param int $cart_id
  *   The cart identifier.
  * @param \Symfony\Component\HttpFoundation\Request $request
  *   The request of the page.
  */
 public function complete($cart_id = 0, Request $request)
 {
     $cart_config = $this->config('uc_cart.settings');
     $module_config = $this->config('uc_2checkout.settings');
     \Drupal::logger('uc_2checkout')->notice('Receiving new order notification for order @order_id.', ['@order_id' => SafeMarkup::checkPlain($request->request->get('merchant_order_id'))]);
     $order = Order::load($request->request->get('merchant_order_id'));
     if (!$order || $order->getStateId() != 'in_checkout') {
         return $this->t('An error has occurred during payment.  Please contact us to ensure your order has submitted.');
     }
     $key = $request->request->get('key');
     $order_number = $module_config->get('demo') ? 1 : $request->request->get('order_number');
     $valid = md5($module_config->get('secret_word') . $request->request->get('sid') . $order_number . $request->request->get('total'));
     if (Unicode::strtolower($key) != Unicode::strtolower($valid)) {
         uc_order_comment_save($order->id(), 0, $this->t('Attempted unverified 2Checkout completion for this order.'), 'admin');
         throw new AccessDeniedHttpException();
     }
     if ($request->request->get('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::fromRoute('entity.uc_order.canonical', ['uc_order' => $order->id()])->toString(), '@order_id' => $order->id(), '%flag' => $request->request->get('demo') == 'Y' ? 'Y' : 'N', '%mode' => $module_config->get('demo') ? 'Y' : 'N'));
         if (!$module_config->get('demo')) {
             throw new AccessDeniedHttpException();
         }
     }
     //@todo: Check if this is the right way to save the order
     $order->billing_street1 = $request->request->get('street_address');
     $order->billing_street2 = $request->request->get('street_address2');
     $order->billing_city = $request->request->get('city');
     $order->billing_postal_code = $request->request->get('zip');
     $order->billing_phone = $request->request->get('phone');
     $order->billing_zone = $request->request->get('state');
     $order->billing_country = $request->request->get('country');
     $order->save();
     if (Unicode::strtolower($request->request->get('email')) !== Unicode::strtolower($order->getEmail())) {
         uc_order_comment_save($order->id(), 0, $this->t('Customer used a different e-mail address during payment: @email', ['@email' => SafeMarkup::checkPlain($request->request->get('email'))]), 'admin');
     }
     if ($request->request->get('credit_card_processes') == 'Y' && is_numeric($request->request->get('total'))) {
         $comment = $this->t('Paid by @type, 2Checkout.com order #@order.', ['@type' => $request->request->get('pay_method') == 'CC' ? $this->t('credit card') : $this->t('echeck'), '@order' => SafeMarkup::checkPlain($request->request->get('order_number'))]);
         uc_payment_enter($order->id(), '2Checkout', $request->request->get('total'), 0, NULL, $comment);
     } else {
         drupal_set_message($this->t('Your order will be processed as soon as your payment clears at 2Checkout.com.'));
         uc_order_comment_save($order->id(), 0, $this->t('@type payment is pending approval at 2Checkout.com.', ['@type' => $request->request->get('pay_method') == 'CC' ? $this->t('Credit card') : $this->t('eCheck')]), 'admin');
     }
     // Empty that cart...
     $cart = $this->cartManager->get($cart_id);
     $cart->emptyCart();
     // 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');
     $build = $cart->completeSale($order, $cart_config->get('new_customer_login'));
     return $build;
 }
<?php

define('DRUPAL_ROOT', dirname(__FILE__) . '/../../../../../../');
chdir(DRUPAL_ROOT);
require './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
if (isset($_POST['SIGN'])) {
    $sign = strtoupper(md5(md5($_POST['SHOP_ID']) . '&' . md5($_POST["ORDER_ID"]) . '&' . md5($_POST['STATE'])));
    if ($_POST['SIGN'] == $sign) {
        switch ($_POST['STATE']) {
            case 'paid':
                $order = uc_order_load($_POST["ORDER_ID"]);
                uc_payment_enter($_POST["ORDER_ID"], 'uc_ubrir', $order->order_total, 0, NULL, $_POST["ORDER_ID"]);
                uc_cart_complete_sale($order, variable_get('uc_new_customer_login', FALSE));
                break;
        }
    }
}
 /**
  * Process a payment through the credit card gateway.
  *
  * @param $order
  *   The order that is being processed.
  * @param $amount
  *   The amount of the payment we're attempting to collect.
  * @param $txn_type
  *   The transaction type, one of the UC_CREDIT_* constants.
  * @param $reference
  *   (optional) The payment reference, where needed for specific transaction
  *   types.
  *
  * @return bool
  *   TRUE or FALSE indicating whether or not the payment was processed.
  */
 public function processPayment($order, $amount, $txn_type, $reference = NULL)
 {
     // Ensure the cached details are loaded.
     // @todo Figure out which parts of this call are strictly necessary.
     $this->orderLoad($order);
     $result = $this->chargeCard($order, $amount, $txn_type, $reference);
     // If the payment processed successfully...
     if ($result['success'] === TRUE) {
         // Log the payment to the order if not disabled.
         if (!isset($result['log_payment']) || $result['log_payment'] !== FALSE) {
             uc_payment_enter($order->id(), $this->getPluginDefinition()['id'], $amount, empty($result['uid']) ? 0 : $result['uid'], empty($result['data']) ? '' : $result['data'], empty($result['comment']) ? '' : $result['comment']);
         }
     } else {
         // Otherwise display the failure message in the logs.
         \Drupal::logger('uc_payment')->warning('Payment failed for order @order_id: @message', ['@order_id' => $order->id(), '@message' => $result['message'], 'link' => Link::createFromRoute(t('view order'), 'entity.uc_order.canonical', ['uc_order' => $order->id()])->toString()]);
     }
     return $result['success'];
 }
 public function testCheckoutComplete()
 {
     // Payment notification is received first.
     $order_data = ['uid' => 0, 'primary_email' => '*****@*****.**'];
     $order = $this->createOrder($order_data);
     uc_payment_enter($order->id(), 'SimpleTest', $order->getTotal());
     $output = $this->cartManager->completeSale($order);
     // Check that a new account was created.
     $this->assertTrue(strpos($output['#message']['#markup'], 'new account has been created') !== FALSE, 'Checkout message mentions new account.');
     // 3 e-mails: new account, customer invoice, admin invoice
     $this->assertMailString('subject', 'Account details', 3, 'New account email was sent');
     $this->assertMailString('subject', 'Your Order at Ubercart', 3, 'Customer invoice was sent');
     $this->assertMailString('subject', 'New Order at Ubercart', 3, 'Admin notification was sent');
     $mails = $this->drupalGetMails();
     $password = $mails[0]['params']['account']->password;
     $this->assertTrue(!empty($password), 'New password is not empty.');
     \Drupal::state()->set('system.test_email_collector', []);
     // Different user, sees the checkout page first.
     $order_data = ['uid' => 0, 'primary_email' => '*****@*****.**'];
     $order = $this->createOrder($order_data);
     $output = $this->cartManager->completeSale($order, TRUE);
     uc_payment_enter($order->id(), 'SimpleTest', $order->getTotal());
     // 3 e-mails: new account, customer invoice, admin invoice
     $this->assertMailString('subject', 'Account details', 3, 'New account email was sent');
     $this->assertMailString('subject', 'Your Order at Ubercart', 3, 'Customer invoice was sent');
     $this->assertMailString('subject', 'New Order at Ubercart', 3, 'Admin notification was sent');
     $mails = $this->drupalGetMails();
     $password = $mails[0]['params']['account']->password;
     $this->assertTrue(!empty($password), 'New password is not empty.');
     \Drupal::state()->set('system.test_email_collector', []);
     // Same user, new order.
     $order = $this->createOrder($order_data);
     $output = $this->cartManager->completeSale($order, TRUE);
     uc_payment_enter($order->id(), 'SimpleTest', $order->getTotal());
     // Check that no new account was created.
     $this->assertTrue(strpos($output['#message']['#markup'], 'order has been attached to the account') !== FALSE, 'Checkout message mentions existing account.');
     // 2 e-mails: customer invoice, admin invoice
     $this->assertNoMailString('subject', 'Account details', 3, 'New account email was sent');
     $this->assertMailString('subject', 'Your Order at Ubercart', 3, 'Customer invoice was sent');
     $this->assertMailString('subject', 'New Order at Ubercart', 3, 'Admin notification was sent');
 }
 public function testPackagesUI()
 {
     $this->drupalLogin($this->adminUser);
     $method = $this->createPaymentMethod('other');
     // Process an anonymous, shippable order.
     $order = Order::create(['uid' => 0, 'primary_email' => $this->randomString() . '@example.org', 'payment_method' => $method['id']]);
     // Add three more products to use for our tests.
     $products = array();
     for ($i = 1; $i <= 4; $i++) {
         $product = $this->createProduct(array('uid' => $this->adminUser->id(), 'promote' => 0));
         $order->products[$i] = OrderProduct::create(array('nid' => $product->nid->target_id, 'title' => $product->title->value, 'model' => $product->model, 'qty' => 1, 'cost' => $product->cost->value, 'price' => $product->price->value, 'weight' => $product->weight, 'data' => []));
         $order->products[$i]->data->shippable = 1;
     }
     $order->save();
     $order = Order::load($order->id());
     uc_payment_enter($order->id(), $method['id'], $order->getTotal());
     // Order with 4 products shippable products. (where do we test not-shippable?)
     // Check all, make one package, verify we're on packages page with only one packge.
     // Try create package link, should see there are no products message.
     // Delete package.
     // Check all, make shipment, verify we're on packages page with N packages.
     // Delete packages.
     // How does Sep work? how does making 2 packages out of 4 products work?
     // Check all, cancel, verify we're on order page.
     // After packages made and check for # (check make one and make shipment, use sep. as well)
     // Can use edit/delete actions to package then start over with the same order.
     // and check for full table at /packages and check for action on /packages page,
     // goto shipments tab and look for No shipments have been made for this order.  as well as a list of all the packages.
     //
     // Test presence and operation of package operation on order admin View.
     //
     $this->drupalGet('admin/store/orders/view');
     $this->assertLinkByHref('admin/store/orders/' . $order->id() . '/packages');
     // Test action.
     $this->clickLink(t('Package'));
     $this->assertResponse(200);
     $this->assertText('This order\'s products have not been organized into packages.', 'Package action found.');
     // Now package the products in this order.
     $this->drupalGet('admin/store/orders/' . $order->id() . '/packages');
     $this->assertUrl('admin/store/orders/' . $order->id() . '/packages/new');
     // First time through we'll be verbose - skip this on subsequent tests.
     foreach ($order->products as $sequence => $item) {
         $this->assertText($item->title->value, 'Product title found.');
         $this->assertText($item->model->value, 'Product SKU found.');
         $this->assertFieldByName('shipping_types[small_package][table][' . $sequence . '][checked]', 0, 'Product is available for packaging.');
     }
     // Select all products and test the "Cancel" button.
     $this->drupalPostForm(NULL, array('shipping_types[small_package][table][1][checked]' => 1, 'shipping_types[small_package][table][2][checked]' => 1, 'shipping_types[small_package][table][3][checked]' => 1, 'shipping_types[small_package][table][4][checked]' => 1), t('Cancel'));
     // Go back to Packages tab and try something else.
     $this->assertUrl('admin/store/orders/' . $order->id());
     $this->clickLink(t('Packages'));
     $this->assertUrl('admin/store/orders/' . $order->id() . '/packages/new');
     $this->assertText('This order\'s products have not been organized into packages.', 'Package action found.');
     // Now test the "Create one package" button without selecting anything.
     $this->drupalPostForm(NULL, array(), t('Create one package'));
     $this->assertUrl('admin/store/orders/' . $order->id() . '/packages/new');
     $this->assertText('Packages must contain at least one product.', 'Validation that there must be products in a package.');
     // Now test the "Create one package" button with all products selected.
     $this->drupalPostForm(NULL, array('shipping_types[small_package][table][1][checked]' => 1, 'shipping_types[small_package][table][2][checked]' => 1, 'shipping_types[small_package][table][3][checked]' => 1, 'shipping_types[small_package][table][4][checked]' => 1), t('Create one package'));
     // Check that we're now on the package list page.
     $this->assertUrl('admin/store/orders/' . $order->id() . '/packages');
     foreach ($order->products as $sequence => $item) {
         $this->assertText($item->qty->value . ' x ' . $item->model->value, 'Product quantity x SKU found.');
     }
     // The "Create packages" local action should now be available too.
     $this->assertLink(t('Create packages'));
     $this->clickLink(t('Create packages'));
     $this->assertUrl('admin/store/orders/' . $order->id() . '/packages/new');
     // But we've already packaged everything...
     $this->assertText('There are no products available for this type of package.', 'Create packages local action found.');
     //
     // Test "Ship", "Edit", and "Delete" operations for this package.
     //
     // First "Ship".
     $this->drupalGet('admin/store/orders/' . $order->id() . '/packages');
     $this->assertLink(t('Ship'));
     $this->clickLink(t('Ship'));
     $this->assertUrl('admin/store/orders/' . $order->id() . '/shipments/new?pkgs=1');
     foreach ($order->products as $sequence => $item) {
         $this->assertText($item->qty->value . ' x ' . $item->model->value, 'Product quantity x SKU found.');
     }
     // Second, "Edit".
     $this->drupalGet('admin/store/orders/' . $order->id() . '/packages');
     // (Use Href to distinguish Edit operation from Edit tab.)
     $this->assertLinkByHref('admin/store/orders/' . $order->id() . '/packages/1/edit');
     $this->drupalGet('admin/store/orders/' . $order->id() . '/packages/1/edit');
     // We're editing the package we already made, so all the
     // products should be checked.
     foreach ($order->products as $sequence => $item) {
         $this->assertFieldByName('products[' . $sequence . '][checked]', 1, 'Product is available for packaging.');
     }
     // Third, "Delete".
     $this->drupalGet('admin/store/orders/' . $order->id() . '/packages');
     $this->assertLink(t('Delete'));
     $this->clickLink(t('Delete'));
     // Delete takes us to confirm page.
     $this->assertUrl('admin/store/orders/' . $order->id() . '/packages/1/delete');
     $this->assertText('The products it contains will be available for repackaging.', 'Deletion confirm question found.');
     // "Cancel" returns to the package list page.
     $this->clickLink(t('Cancel'));
     $this->assertLinkByHref('admin/store/orders/' . $order->id() . '/packages');
     // Again with the "Delete".
     $this->clickLink(t('Delete'));
     $this->drupalPostForm(NULL, array(), t('Delete'));
     // Delete returns to new packages page with all packages unchecked.
     $this->assertUrl('admin/store/orders/' . $order->id() . '/packages/new');
     $this->assertText('Package 1 has been deleted.', 'Package deleted message found.');
     foreach ($order->products as $sequence => $item) {
         $this->assertFieldByName('shipping_types[small_package][table][' . $sequence . '][checked]', 0, 'Product is available for packaging.');
     }
     // Back to no packages. Now test making more than one package.
     // Now test the "Create one package" button with all products selected.
     $this->drupalPostForm(NULL, array('shipping_types[small_package][table][1][checked]' => 1, 'shipping_types[small_package][table][2][checked]' => 1), t('Create one package'));
     // Check that we're now on the package list page.
     $this->assertUrl('admin/store/orders/' . $order->id() . '/packages');
     $this->assertText($order->products[1]->qty->value . ' x ' . $order->products[1]->model->value, 'Product quantity x SKU found.');
     $this->assertText($order->products[2]->qty->value . ' x ' . $order->products[2]->model->value, 'Product quantity x SKU found.');
     $this->assertNoText($order->products[3]->qty->value . ' x ' . $order->products[3]->model->value, 'Product quantity x SKU not found.');
     $this->assertNoText($order->products[4]->qty->value . ' x ' . $order->products[4]->model->value, 'Product quantity x SKU not found.');
     // Use "Create packages" to create a second package.
     $this->assertLink(t('Create packages'));
     $this->clickLink(t('Create packages'));
     $this->assertUrl('admin/store/orders/' . $order->id() . '/packages/new');
     $this->assertNoText($order->products[1]->model->value, 'Product SKU not found.');
     $this->assertNoText($order->products[2]->model->value, 'Product SKU not found.');
     $this->assertText($order->products[3]->model->value, 'Product SKU found.');
     $this->assertText($order->products[4]->model->value, 'Product SKU found.');
     $this->drupalPostForm(NULL, array('shipping_types[small_package][table][3][checked]' => 1, 'shipping_types[small_package][table][4][checked]' => 1), t('Create one package'));
     $this->assertLinkByHref('admin/store/orders/' . $order->id() . '/packages');
     foreach ($order->products as $sequence => $item) {
         $this->assertText($item->qty->value . ' x ' . $item->model->value, 'Product quantity x SKU found.');
     }
     // How do we test for two packages? Look for two "Ship" links
     $this->assertLinkByHref('admin/store/orders/' . $order->id() . '/shipments/new?pkgs=2');
     $this->assertLinkByHref('admin/store/orders/' . $order->id() . '/shipments/new?pkgs=3');
     // Now delete both packages.
     $this->clickLink(t('Delete'));
     $this->drupalPostForm(NULL, array(), t('Delete'));
     $this->assertText('Package 2 has been deleted.', 'Package deleted message found.');
     // There's still one left to delete...
     $this->clickLink(t('Delete'));
     $this->drupalPostForm(NULL, array(), t('Delete'));
     $this->assertUrl('admin/store/orders/' . $order->id() . '/packages/new');
     $this->assertText('Package 3 has been deleted.', 'Package deleted message found.');
     // Back to no packages. Now test "Make packages" button.
     $this->drupalPostForm(NULL, array('shipping_types[small_package][table][1][checked]' => 1, 'shipping_types[small_package][table][2][checked]' => 1, 'shipping_types[small_package][table][3][checked]' => 1, 'shipping_types[small_package][table][4][checked]' => 1), t('Make packages'));
     // Check that we're now on the package list page.
     $this->assertUrl('admin/store/orders/' . $order->id() . '/packages');
     foreach ($order->products as $sequence => $item) {
         $this->assertText($item->qty->value . ' x ' . $item->model->value, 'Product quantity x SKU found.');
     }
 }
 /**
  * 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;
     }
 }
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     $payment = $form_state->getValue(['payments', 'new']);
     $received = strtotime($payment['received']['year'] . '-' . $payment['received']['month'] . '-' . $payment['received']['day'] . ' 00:00:00');
     // If the value entered is today, use the exact timestamp instead
     $startofday = mktime(0, 0, 0);
     if ($received == $startofday) {
         $received = REQUEST_TIME;
     }
     uc_payment_enter($this->order->id(), $payment['method'], $payment['amount'], \Drupal::currentUser()->id(), '', $payment['comment'], $received);
     drupal_set_message(t('Payment entered.'));
 }