Last active
August 31, 2020 19:13
-
-
Save topher1kenobe/36ce7580fb22ea8c9a7f8686065a6471 to your computer and use it in GitHub Desktop.
Class method that gets an authenitcation token from BigCommerce
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Get the auth token from BigCommerce | |
* | |
* @access public | |
* @return string $token | |
*/ | |
public function get_remote_auth_token() { | |
// Set up the REST authentication headers | |
$headers[ 'X-Auth-Token' ] = $this->access_token; | |
$headers[ 'X-Auth-Client' ] = $this->client_id; | |
$headers[ 'content-type' ] = 'application/json'; | |
// The token needs an expiration. You can either set it short | |
// and manage recreation, or set it very long and never change | |
// Regardless it needs to be a UTC timestamp | |
$expires = date('U') + 100000000; | |
// Set up the query to get the token. Formatted in JSON, requires | |
// the channel ID, the expiration, and CORS allowance. | |
$query = ' | |
{ | |
"channel_id": ' . $this->channel_id . ', | |
"expires_at": ' . $expires . ', | |
"allowed_cors_origins": [ | |
"' . get_home_url() . '" | |
] | |
} | |
'; | |
// set up the POST args | |
$args[ 'method'] = 'POST'; | |
$args[ 'headers'] = $headers; | |
$args[ 'body' ] = $query; | |
// The request gets sent to the token API endpoint with your | |
// store hash in the URL. | |
$url = 'https://api.bigcommerce.com/stores/' . $this->store_hash . '/v3/storefront/api-token'; | |
// send the query | |
$request = wp_safe_remote_post( $url, $args ); | |
// get the body out of the result | |
$body = json_decode( $request['body'] ); | |
// get the token out of the body | |
$token = $body->data->token; | |
return $token; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment