Developer: How to add more details in serial key validation response

WooCommerce Serial Key gives the store power to validate all generated serial keys against orders & products. The validation process also checks download limit & expired download.

Currently, the validation process only provides 2 information: whether the validation has passed or not & a human-readable message. But the Serial Key plugin also provides a hook/filter that can be used to add more details to the validation response.

Let’s see how it can be done with an example:

In this example, we will add the serial key, product SKU & expiry details in the validation response. With the following custom PHP code, this can be achieved. You can put this PHP code in the functions.php file of your website’s child theme.

/**
 * Function to add more details in serial key validation response
 *
 * @param string $response JSON encoded response.
 * @param string $serial_key The serial key.
 * @param string $product_sku The product SKU.
 * @param string $current_uuid The current UUID.
 * @return string
 * 
 * @author StoreApps.org
 */
 function storeapps_serial_key_validation_response( $response = '', $serial_key = '', $product_sku = '', $current_uuid = '' ) {
	global $wpdb;

	if ( empty( $serial_key ) || empty( $product_sku ) ) {
		return $response;
	}

	$decoded_response = ( ! empty( $response ) ) ? json_decode( $response, true ) : array();

	$decoded_response['serial_key']  = $serial_key;
	$decoded_response['product_sku'] = $product_sku;

	$query  = $wpdb->prepare(
		"SELECT MAX(`order_id`) AS order_id,
			`product_id`
			FROM {$wpdb->prefix}woocommerce_serial_key
			WHERE serial_key = %s 
			GROUP BY `serial_key`",
		$serial_key
	);
	$result = $wpdb->get_row( $query, ARRAY_A );

	if ( ! is_wp_error( $result ) && ! empty( $result ) ) {
		$product_id = ( ! empty( $result['product_id'] ) ) ? absint( $result['product_id'] ) : 0;
		$order_id = ( ! empty( $result['order_id'] ) ) ? absint( $result['order_id'] ) : 0;
		if ( ! empty( $product_id ) && ! empty( $order_id ) ) {
			$download_status_query = $wpdb->prepare(
				"SELECT downloads_remaining, access_expires
					FROM {$wpdb->prefix}woocommerce_downloadable_product_permissions
					WHERE order_id = %d
						AND product_id = %d
					ORDER BY permission_id DESC",
				$order_id,
				$product_id
			);
			$download_status       = $wpdb->get_row( $download_status_query, ARRAY_A );

			$decoded_response['access_expires'] = ( ! empty( $download_status['access_expires'] ) ) ? $download_status['access_expires'] : '';
		}
	}

	return wp_json_encode( $decoded_response );
}
add_filter( 'wsk_validation_response', 'storeapps_serial_key_validation_response', 10, 4 );
« Back to WooCommerce Serial Key