Last active
May 2, 2018 12:17
-
-
Save alanef/f462ed649d1a27eef2060e9fcd916fff to your computer and use it in GitHub Desktop.
Example API call snippets using tokens and transients
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
| private function api_call( $url ) { | |
| // a transient is used to store the token, this token in this API expires in 60 minute | |
| if ( false === ( $this->api_token = get_transient( 'my_api_token' ) ) ) { | |
| $response = $this->api_get_token( $url ); | |
| $response_code = wp_remote_retrieve_response_code( $response ); | |
| } else { | |
| $args = array( | |
| 'headers' => array( | |
| 'Authorization' => 'Basic ' . $this->api_token, | |
| ), | |
| 'timeout' => 25, | |
| ); | |
| $response = wp_remote_get( $url, $args ); | |
| if ( is_wp_error( $response ) ) { | |
| die( sprintf( esc_html__( 'Failed getting %1$s %2$s', 'fullworks' ), $url, print_r( $response, true ) ) ); | |
| } | |
| $response_code = wp_remote_retrieve_response_code( $response ); | |
| if ( $response_code == 401 ) { | |
| // token not valid | |
| $response = $this->api_get_token( $url ); | |
| } | |
| } | |
| $body = wp_remote_retrieve_body( $response ); | |
| // this api returns xml response | |
| return array( | |
| 'response_code' => $response_code, | |
| 'body' => simplexml_load_string( $body ), | |
| ); | |
| } | |
| private function api_get_token( $url ) { | |
| // called if basic auth not worked | |
| // user name and apsswords stored in settings | |
| $args = array( | |
| 'headers' => array( | |
| 'Authorization' => 'Basic ' . base64_encode( $this->get_setting( 'api', 'username' ) . ':' . $this->get_setting( 'api', 'password' ) ) | |
| ), | |
| 'timeout' => 25, | |
| ); | |
| $response = wp_remote_get( $url, $args ); | |
| if ( is_wp_error( $response ) ) { | |
| die( sprintf( esc_html__( 'Failed getting %1$s %2$s', 'fullworks' ), $url, print_r( $response, true ) ) ); | |
| } | |
| $response_code = wp_remote_retrieve_response_code( $response ); | |
| if ( ( $response_code != 200 ) && ( $response_code != 304 ) ) { | |
| die( sprintf( esc_html__( 'Failed getting %1$s with code %2$s', 'fullworks' ), $url, print_r( $response_code, true ) ) ); | |
| } | |
| // could add check for 401 and sleep 10 minutes if this becomes a problem. | |
| $this->api_token = base64_encode( wp_remote_retrieve_header( $response, 'Token' ) ); | |
| set_transient( 'my_api_token', $this->api_token, HOUR_IN_SECONDS ); | |
| return $response; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment