Skip to content

Instantly share code, notes, and snippets.

@DavidHernandez
Last active August 29, 2015 14:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DavidHernandez/9e7fce631e30ef5c84e4 to your computer and use it in GitHub Desktop.
Save DavidHernandez/9e7fce631e30ef5c84e4 to your computer and use it in GitHub Desktop.
Drupal Commerce instant buy link
<?php
/**
* @file
*
* This super small module adds a page that creates an order with a product
* and redirects to the payment platform.
*
* It can be used as sample or base for simple commerce workflows. It
* doesn't need to be a menu item, can be done in a form submit callback.
*
* If you have different payment methods, you can change the checkout_payment
* status to checkout_review so the user can select the payment method or add
* some logic to select each payment method.
*
* We use it to have buttons with each payment method that we can put in a
* block in different pages.
*/
/**
* Implements hook_menu().
*/
function instant_buy_menu() {
$menu['product/%'] = array(
'title' => 'Instant buy',
'page callback' => 'instant_buy_create_order',
'page arguments' => array(1),
'access arguments' => array('access checkout'),
'type' => MENU_CALLBACK,
);
return $menu;
}
/**
* Page callback that creates an order and redirects to the payment redirect page.
*/
function instant_buy_create_order($sku) {
global $user;
$product = commerce_product_load_by_sku($sku);
$order = ($user->uid) ? commerce_order_new($user->uid, 'checkout_checkout') : commerce_cart_order_new();
// Save to get the Order ID.
commerce_order_save($order);
$line_item = commerce_product_line_item_new($product, 1, $order->order_id);
commerce_line_item_save($line_item);
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
$order_wrapper->commerce_line_items[] = $line_item;
// Select here the payment method. Usually something like:
// [module_name]|commerce_payment_[module_name]
$order->data['payment_method'] = 'commerce_sermepa|commerce_payment_commerce_sermepa';
commerce_order_save($order);
// Set status to order checkout to go to the payment platform redirect.
commerce_order_status_update($order, 'checkout_payment');
drupal_goto('checkout/' . $order->order_id);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment