Skip to content

Instantly share code, notes, and snippets.

@gundamew
Created March 5, 2020 07:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gundamew/afccb319d35acefd584cb7c987db5988 to your computer and use it in GitHub Desktop.
Save gundamew/afccb319d35acefd584cb7c987db5988 to your computer and use it in GitHub Desktop.
<?php
defined( 'ABSPATH' ) || exit;
class WC_REST_API_Key {
// See WC_Auth::create_keys
public static function create( $user_id, $description, $permissions = 'read' ) {
global $wpdb;
if ( ! in_array( $permissions, array( 'read', 'write', 'read_write' ), true ) ) {
$permissions = 'read';
}
$consumer_key = 'ck_' . wc_rand_hash();
$consumer_secret = 'cs_' . wc_rand_hash();
$wpdb->insert(
$wpdb->prefix . 'woocommerce_api_keys',
array(
'user_id' => $user_id,
'description' => $description,
'permissions' => $permissions,
'consumer_key' => wc_api_hash( $consumer_key ),
'consumer_secret' => $consumer_secret,
'truncated_key' => substr( $consumer_key, -7 ),
),
array(
'%d',
'%s',
'%s',
'%s',
'%s',
'%s',
)
);
return array(
'key_id' => $wpdb->insert_id,
'consumer_key' => $consumer_key,
'consumer_secret' => $consumer_secret,
'permissions' => $permissions,
);
}
public static function remove( $key_id ) {
global $wpdb;
return $wpdb->delete(
$wpdb->prefix . 'woocommerce_api_keys',
array( 'key_id' => $key_id ),
array( '%d' )
);
}
public static function remove_by_user( $user_id ) {
global $wpdb;
return $wpdb->delete(
$wpdb->prefix . 'woocommerce_api_keys',
array( 'user_id' => $user_id ),
array( '%d' )
);
}
public static function update_last_access( $key_id ) {
global $wpdb;
return $wpdb->update(
$wpdb->prefix . 'woocommerce_api_keys',
array( 'last_access' => current_time( 'mysql' ) ),
array( 'key_id' => $key_id ),
array( '%s' ),
array( '%d' )
);
}
}
new WC_REST_API_Key();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment