Skip to content

Instantly share code, notes, and snippets.

@iyut
Created June 24, 2021 05:05
Show Gist options
  • Save iyut/d1cbe71b681cc7869e1f46eeb609ffc5 to your computer and use it in GitHub Desktop.
Save iyut/d1cbe71b681cc7869e1f46eeb609ffc5 to your computer and use it in GitHub Desktop.

Revisions

  1. iyut created this gist Jun 24, 2021.
    28 changes: 28 additions & 0 deletions functions.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,28 @@
    function request_token() {

    $encoded_auth = base64_encode( $this->client_id . ":" . $this->client_secret );
    $args = array(
    'method' => 'POST',
    'httpversion' => '1.1',
    'headers' => array(
    'Authorization' => 'Basic '. $encoded_auth,
    'Content-Type' => 'application/x-www-form-urlencoded;charset=UTF-8',
    ),
    'body' => 'grant_type=client_credentials',
    );

    $response = wp_remote_post( $this->api_url, $args );

    // If the status code is not 200, throw an error with the raw response body
    if ( isset( $response['response'] ) && $response['response']['code'] !== 200 ) {
    throw new RuntimeException( $response['response']['message'] );
    }

    $token_response = json_decode( $response['body'] );

    if( isset( $token_response->error ) ){
    throw new RuntimeException( $token_response->error );
    }

    return $token_response;
    }