As default, when order completed (or pending) the plugin generate a licence key or extract one from the pre-defined list of keys. This is a common set-up for the majority of sites which is very easy to achieve through the WP Software License plugin.
There are situations when the key is required to be retrieved from a 3rd API, at the order completed, which will be delivered to customer. This is easy to achieve through a programmable filer. The following code does just that:
add_action('woocommerce_order_item_meta_end', 'retrieve_custom_license_keys', 1, 3);
function retrieve_custom_license_keys( $item_id, $item, $order )
{
global $wpdb;
$order_data = new WC_Order( $order->get_ID() );
$order_products = $order_data->get_items();
$license_active_for_status = array ( 'completed' );
$time = date("Y-m-d H:i:s", time());
//iterate all order items and check for any licence
foreach( $order_products as $order_item_id => $order_data )
{
if ( ! WOO_SL_functions::is_order_item_licensed ( $order->get_ID() , $order_item_id ) )
continue;
if( in_array ( $order->get_status(), $license_active_for_status ) === FALSE )
continue;
$_woo_sl = WOO_SL_functions::get_order_item_meta($order_item_id, '_woo_sl', TRUE);
if(! is_array($_woo_sl))
continue;
foreach($_woo_sl['group_title'] as $_group_id => $_group_title)
{
$license_keys = (array)WOO_SL_functions::get_order_product_generated_keys( $order->get_ID(), $order_item_id, $_group_id );
if(count($license_keys) > 0)
continue;
//retrieve the licence key from the 3rd API
$new_licence_key = '.....';
//insert the key on database
$mysql_query = "INSERT INTO ". $wpdb->prefix . "woocommerce_software_licence ( `order_id`, `order_item_id`, `group_id`, `licence`, `created` )
VALUES ( '". $order->get_ID() ."', '". $order_item_id ."', '". $_group_id ."', '". $new_licence_key ."', '". $time ."')";
$result = $wpdb->get_results( $mysql_query );
}
}
}
The above code should be place inside theme functions.php file or a custom plugin.
Category: News