The Add to Cart form is really an order item add form, and its form state array contains the view mode it's being rendered for. It's also built via a lazy builder service, cf. ProductLazyBuilders::addToCartForm(). I was thinking we could implement this custom submit button as a general alter of the primary form, but I'm realizing there may not be a definite way to figure out who actually invoked the form build ... I think it may be safer for the custom display formatter to change the lazy builder to a service defined by this module.

Once that happens, the custom lazy builder can start just by copying the entirety of the core builder's addToCartForm() function. This will also give us a convenient way to pass into it any settings specific to the One-Click Checkout module's display formatter.

The logic of the custom form builder should be...

  1. Check to ensure the customer has a default stored payment method.
  2. Check to ensure the customer has a default billing address.
  3. If enabled and the product is shippable, check to ensure the customer has a default shipping address.

If any of the above aren't true, we really should just invoke the primary lazy builder. However, if the form is suitable for One-Click Checkout, then we should build the form with an additional submit button that reads "Buy Now" and does the following:

  1. Creates a new cart order for the customer.
  2. Sets the order's default profiles / payment method.
  3. Creates an order item based on the current Add to Cart form (i.e. respecting the selection variation, quantity, and custom fields).
  4. If applicable, calculates shipping and selects the cheapest option for the order.
  5. Redirects to the review page of the order's checkout flow.

Ultimately, we'll need to work on making this configurable, as not every site will have the same checkout flow, and some may want alternate options for determining shipping. For the POC here, though, let's just do the above in the context of a new development env't built according to the following tutorial:

https://www.centarro.io/blog/how-build-drupal-commerce-development-envir...

Comments

rszrama created an issue. See original summary.

jsacksick’s picture

I would probably just swap the AddToCartForm class. extend the default one, and override the actions method to add an additional submit button.

You could just attach a different #submit to it, which does what you need.

jsacksick’s picture

As discussed on Slack, the hook_form_alter() approach could work.

The module could provide 3rd party settings for the formatter, similar to what Commerce Wishlist is doing (See commerce_wishlist_field_formatter_third_party_settings_form()).

Then the wishlist module accesses those settings (from commerce_wishlist_form_commerce_order_item_add_to_cart_form_alter), using the following code:

  // Grab the view mode third party settings.
  $display = EntityViewDisplay::collectRenderDisplay($product, $form_state->get('view_mode'));
  $display_content = $display->get('content');
  $settings = !empty($display_content['variations']['third_party_settings']['commerce_wishlist']) ? $display_content['variations']['third_party_settings']['commerce_wishlist'] : [];
karengrey’s picture

Assigned: Unassigned » karengrey
karengrey’s picture

Version: » 1.0.x-dev
StatusFileSize
new9.63 KB

Ta da 🎉

Buy Now button is rendered for all logged in users. If the user does not have a stored payment method, then they will be redirected to the Payment step in the checkout.

I have also updated the Readme with setup instructions.

jsacksick’s picture

  1. +++ b/commerce_oneclick_checkout.module
    @@ -4,3 +4,224 @@
    +  $cart_id = $cart->get('order_id')->getString();
    

    $cart->id()?

  2. +++ b/commerce_oneclick_checkout.module
    @@ -4,3 +4,224 @@
    +  $query = $entity_type_manager->getStorage('commerce_payment_method')->getQuery()
    

    why not reusing the loadReusable() method from the payment method storage?

  3. +++ b/commerce_oneclick_checkout.module
    @@ -4,3 +4,224 @@
    +    if ($purchased_entity->hasField('weight')) {
    

    You should use the shipping order manager to determine if the order is shippable.

    (Service "commerce_shipping.order_manager").

    You should also use that service to pack the order instead of creating the shipments from here... Any reason to manually do that,

    Though this should all be wrapped into a moduleExists() check that checks if the shipping module is installed.

jsacksick’s picture

  1. +++ b/commerce_oneclick_checkout.module
    @@ -4,3 +4,224 @@
    +  $item = $add_to_cart_form->buildEntity($form, $form_state);
    

    let's rename $item to $order_item.

  2. +++ b/commerce_oneclick_checkout.module
    @@ -4,3 +4,224 @@
    +  $order_type = OrderItemType::load($order_type_id)->get('orderType');
    

    The order type should be resolved using the order type resolver.

    $order_type_resolver = \Drupal::service('commerce_order.chain_order_type_resolver');
    $order_type = $order_type_resolver->resolve($order_item);
    
  3. +++ b/commerce_oneclick_checkout.module
    @@ -4,3 +4,224 @@
    +  \Drupal::service('commerce_cart.cart_manager')->addEntity($cart, $purchased_entity, $quantity);
    

    You already have the $cart_manager available from above.

Also, I'd recommend moving all of your logic into a service, so that you can leverage the dependency injection there (instead of having all these Drupal calls()).

See the pattern used by ProfileFieldCopy for example.

from within the form_alter(), you could call your service and call

if ($one_click_checkout_form->supportsForm($form, $form_state))) {
$one_click_checkout_form->alterForm()...

You could have a submitForm() method there as well.

Regarding the service name, it could be just commerce_oneclick_checkout.oneclick_button and OneClickButton as the class name, but feel free to choose a different name :).

rszrama’s picture

Let's focus on the code changes but create a separate follow-up issue for the move of the code to a service.

karengrey’s picture

Thanks Jonathan for your feedback

1. I decided to use $query = $entity_type_manager->getStorage('commerce_payment_method')->getQuery() to get the User's Payment Methods as I only required the ID. loadReusable() required arguments I didn't have available and it essentially does the same thing, where it executes a query to get the payment methods

2. I believe using $purchased_entity->hasField('weight')) is a simpler process for what I want to do. isShippable() in the ShippingOrderManager essentially does the same thing.

I don't as yet, fully understand how Commerce Shipping works. So with limited knowledge, I saw it best to create a Shipment and ShipmentItem manually, to achieve our goal. If you know a better way of achieving this, i'm more than happy to learn what it is.

Ive applied all the other code changes.

karengrey’s picture

StatusFileSize
new4.32 KB

Added interdiff

rszrama’s picture

Reviewing this earlier this week, I noticed it doesn't meet the issue description where I specced out creating a new order so as not to blow away a customer's existing order for the One-Click Checkout purchase. As written, if I have a cart, my cart is emptied and I can't go back to it after the One-Click Checkout experience.

Unfortunately, I just discovered that it isn't possible in Commerce 2.x to have more than one cart order for for the same user / store / order type combination. I don't know what we made that decision, but it's a hard blocker here:

    if ($this->getCartId($order_type, $store, $account)) {
      // Don't allow multiple cart orders matching the same criteria.
      throw new DuplicateCartException("A cart order for type '$order_type', store '$store_id' and account '$uid' already exists.");
    }

We theoretically could use a custom order type, which may be beneficial for other reasons, but for now I'm fine proceeding with the approach in this patch as the easiest path toward something demo-able. We can create a follow-up issue either for changing the core expectation here or else to implement a custom order type in this module.