oauth2 api

tech2023-01-10  134

oauth2 api

In previous tutorials, we took a deep dive into the WordPress HTTP API. We even went as far as building the following plugins to demonstrate real-world examples of its usage: domain whois and social data widget; CAPTCHA protection plugin for WordPress login, registration & comment; and plugin for stopping disposable email address signup.

在以前的教程中,我们深入研究了WordPress HTTP API 。 我们甚至还开发了以下插件来演示其用法的真实示例: 域whois和社交数据小部件 ; CAPTCHA保护插件,用于WordPress 登录 , 注册和评论 ; 和停止一次性电子邮件地址注册的插件 。

In this tutorial, we’ll be introduced to the world of OAuth, how Twitter uses it for authorizing HTTP requests to its API and finally, building a PHP class powered by WordPress HTTP API that plugins can take advantage of when consuming Twitter.

在本教程中,我们将向您介绍OAuth的世界,Twitter如何使用它来授权对其API的HTTP请求,最后建立一个由WordPress HTTP API驱动PHP类,插件在使用Twitter时可以利用。

OAuth简介 (Introduction to OAuth)

OAuth is an authentication protocol that provides a simple, safer and more secure way to publish and interact with protected data. It allows users to approve applications to act on their behalf without sharing their password.

OAuth是一种身份验证协议,它提供了一种简单,更安全,更安全的方式来发布受保护的数据并与之交互。 它允许用户批准应用程序代表他们执行操作而无需共享密码。

If you’re storing protected data on your users’ behalf, they shouldn’t be spreading their passwords around the web to get access to it. Instead, you can use OAuth to give your users access to their data, while protecting their account credentials.

如果您代表用户存储受保护的数据,则不应在网络上散布密码以获取访问权限。 相反,您可以使用OAuth授予用户访问其数据的权限,同时保护其帐户凭据。

编写PHP类 (Coding the PHP Class)

A run-down on how HTTP requests to Twitter are made with OAuth authentication will be explained as we code the PHP class.

在我们编写PHP class代码时,将说明如何通过OAuth身份验证向Twitter发出HTTP请求。

First off, head over to Twitter’s Application management center; create an application to grab your keys and access token.

首先,前往Twitter的应用程序管理中心 ; 创建一个应用程序以获取您的密钥并访问令牌。

A step-by-step guide on creating Twitter applications and getting the API keys can be found at hostoople.com

在hostoople.com上可以找到有关创建Twitter应用程序和获取API密钥的分步指南。

Create the PHP class and include the properties that will store the various parameters. These are outlined below.

创建PHP类,并包含将存储各种参数的属性。 这些概述如下。

class Twitter_API_WordPress { /** @var string OAuth access token */ private $oauth_access_token; /** @var string OAuth access token secrete */ private $oauth_access_token_secret; /** @var string Consumer key */ private $consumer_key; /** @var string consumer secret */ private $consumer_secret; /** @var array POST parameters */ private $post_fields; /** @var string GET parameters */ private $get_field; /** @var array OAuth credentials */ private $oauth_details; /** @var string Twitter's request URL */ private $request_url; /** @var string Request method or HTTP verb */ private $request_method;

The constructor will accept an array of your Twitter’s application consumer (or API) key and secret, as well as access token and access token secret and save them to their respective properties.

构造函数将接受您的Twitter应用程序使用者(或API)密钥和密钥以及访问令牌和访问令牌密钥的数组,并将它们保存到各自的属性中。

/** Class constructor */ public function __construct( $settings ) { if ( ! isset( $settings['oauth_access_token'] ) || ! isset( $settings['oauth_access_token_secret'] ) || ! isset( $settings['consumer_key'] ) || ! isset( $settings['consumer_secret'] ) ) { return new WP_Error( 'twitter_param_incomplete', 'Make sure you are passing in the correct parameters' ); } $this->oauth_access_token = $settings['oauth_access_token']; $this->oauth_access_token_secret = $settings['oauth_access_token_secret']; $this->consumer_key = $settings['consumer_key']; $this->consumer_secret = $settings['consumer_secret']; }

Next are the methods that will accept the GET or POST parameters for the HTTP request.

接下来是将接受HTTP请求的GET或POST参数的方法。

/** * Store the POST parameters * * @param array $array array of POST parameters * * @return $this */ public function set_post_fields( array $array ) { $this->post_fields = $array; return $this; } /** * Store the GET parameters * * @param $string * * @return $this */ public function set_get_field( $string ) { $this->getfield = $string; return $this; }

The private method _build_signature_base_string() accepts the following arguments to create the signature base string: the request URL, the request method or HTTP verb and the OAuth credentials (consumer key and secret; access token and secret; and the GET parameters if it is a GET request).

私有方法_build_signature_base_string()接受以下参数来创建签名基本字符串:请求URL,请求方法或HTTP动词以及OAuth凭据(消费者密钥和机密;访问令牌和机密;以及GET参数,如果它是GET请求)。

/** * Create a signature base string from list of arguments * * @param string $request_url request url or endpoint * @param string $method HTTP verb * @param array $oauth_params Twitter's OAuth parameters * * @return string */ private function _build_signature_base_string( $request_url, $method, $oauth_params ) { // save the parameters as key value pair bounded together with '&' $string_params = array(); ksort( $oauth_params ); foreach ( $oauth_params as $key => $value ) { // convert oauth parameters to key-value pair $string_params[] = "$key=$value"; } return "$method&" . rawurlencode( $request_url ) . '&' . rawurlencode( implode( '&', $string_params ) ); }

The _generate_oauth_signature() private method accepts the created signature base string to generate the OAuth signature.

_generate_oauth_signature()私有方法接受创建的签名基本字符串以生成OAuth签名。

private function _generate_oauth_signature( $data ) { // encode consumer and token secret keys and subsequently combine them using & to a query component $hash_hmac_key = rawurlencode( $this->consumer_secret ) . '&' . rawurlencode( $this->oauth_access_token_secret ); $oauth_signature = base64_encode( hash_hmac( 'sha1', $data, $hash_hmac_key, true ) ); return $oauth_signature; }

The build_oauth() creates an array containing the following data and saves it to the oauth_details property, which will be use later by authorization_header() to generate the authorization header.

build_oauth()创建一个包含以下数据的数组,并将其保存到oauth_details属性,该属性稍后将由authorization_header()以生成授权标头。

oauth_consumer_key – Twitter application consumer key.

oauth_consumer_key -Twitter应用程序使用者密钥。

oauth_nonce – a random string, uniquely generated by the client to allow the server to verify that a request has never been made before often created using time() or mt_rand().

oauth_nonce –随机字符串,由客户端唯一生成,以允许服务器验证是否经常在使用time()或mt_rand()创建之前从未提出过请求。

oauth_signature_method – the signature method which is often times “HMAC-SHA1”

oauth_signature_method –签名方法,通常乘以“ HMAC-SHA1”

oauth_token – application OAuth token.

oauth_token –应用程序OAuth令牌。

oauth_timestamp – current timestamp created with time()

oauth_timestamp –使用time()创建的当前时间戳

oauth_version – Twitter uses version 1.0

oauth_version – Twitter使用版本1.0

oauth_signature – OAuth signature generated by _generate_oauth_signature()

oauth_signature – _generate_oauth_signature()生成的OAuth签名

The request method or HTTP verb is also saved to request_method property.

请求方法或HTTP动词也保存到request_method属性。

/** * Build, generate and include the OAuth signature to the OAuth credentials * * @param string $request_url Twitter endpoint to send the request to * @param string $request_method Request HTTP verb eg GET or POST * * @return $this */ public function build_oauth( $request_url, $request_method ) { if ( ! in_array( strtolower( $request_method ), array( 'post', 'get' ) ) ) { return new WP_Error( 'invalid_request', 'Request method must be either POST or GET' ); } $oauth_credentials = array( 'oauth_consumer_key' => $this->consumer_key, 'oauth_nonce' => time(), 'oauth_signature_method' => 'HMAC-SHA1', 'oauth_token' => $this->oauth_access_token, 'oauth_timestamp' => time(), 'oauth_version' => '1.0' ); if ( ! is_null( $this->get_field ) ) { // remove question mark(?) from the query string $get_fields = str_replace( '?', '', explode( '&', $this->get_field ) ); foreach ( $get_fields as $field ) { // split and add the GET key-value pair to the post array. // GET query are always added to the signature base string $split = explode( '=', $field ); $oauth_credentials[ $split[0] ] = $split[1]; } } // convert the oauth credentials (including the GET QUERY if it is used) array to query string. $signature = $this->_build_signature_base_string( $request_url, $request_method, $oauth_credentials ); $oauth_credentials['oauth_signature'] = $this->_generate_oauth_signature( $signature ); // save the request url for use by WordPress HTTP API $this->request_url = $request_url; // save the OAuth Details $this->oauth_details = $oauth_credentials; $this->request_method = $request_method; return $this; }

Here is the code for the authorization_header() method we talked about.

这是我们讨论过的authorization_header()方法的代码。

/** * Generate the authorization HTTP header * @return string */ public function authorization_header() { $header = 'OAuth '; $oauth_params = array(); foreach ( $this->oauth_details as $key => $value ) { $oauth_params[] = "$key=\"" . rawurlencode( $value ) . '"'; } $header .= implode( ', ', $oauth_params ); return $header; }

The process_request() will send the GET or POST request using wp_remote_get() or wp_remote_post() depending on the request method and subsequently return the response using wp_remote_retrieve_body().

process_request()将根据请求方法使用wp_remote_get()或wp_remote_post()发送GET或POST请求,并随后使用wp_remote_retrieve_body()返回响应。

/** * Process and return the JSON result. * * @return string */ public function process_request() { $header = $this->authorization_header(); $args = array( 'headers' => array( 'Authorization' => $header ), 'timeout' => 45, 'sslverify' => false ); if ( ! is_null( $this->post_fields ) ) { $args['body'] = $this->post_fields; $response = wp_remote_post( $this->request_url, $args ); return wp_remote_retrieve_body( $response ); } else { // add the GET parameter to the Twitter request url or endpoint $url = $this->request_url . $this->get_field; $response = wp_remote_get( $url, $args ); return wp_remote_retrieve_body( $response ); } }

See this tutorial for a better understanding of the WordPress HTTP API and how it works.

请参阅本教程 ,以更好地了解WordPress HTTP API及其工作方式。

And finally, we close the class.

最后,我们关闭班级。

} // Twitter_API_WordPress

Please note: In set_post_fields(), set_get_field() and build_oauth(), the object $this is returned in each method in order to support method chaining.

请注意:在set_post_fields() , set_get_field()和build_oauth() ,每个方法中都会返回对象$this ,以支持方法链接。

Example:

例:

$SomeObject->getObjectOne()->getObjectTwo()

See the class usage below for a better understanding.

请参阅下面的类用法以获得更好的理解。

如何使用课堂 (How to Use the Class)

This class must be used within the context of a WordPress plugin. It won’t work as a standalone class because it requires the WordPress HTTP API for it to work.

此类必须在WordPress插件的上下文中使用。 它不能作为独立类工作,因为它需要WordPress HTTP API才能工作。

To get a list or collection of your most recent tweets, follow the guide below. Note: https://api.twitter.com/1.1/statuses/user_timeline.json is the resource URL for retrieving the recent tweet data.

要获取最新推文的列表或集合,请遵循以下指南。 注意: https : //api.twitter.com/1.1/statuses/user_timeline.json是用于检索最新tweet数据的资源URL。

First, create an array of your access keys and tokens.

首先,创建访问密钥和令牌的数组。

$settings = array( 'oauth_access_token' => "211978035-tcdnwn5GlzeY9tKiMqTvkSLNPAgcwO5ABtqwgx18", 'oauth_access_token_secret' => "rS0CMxoVNmcUYG5nWi2OhY8bJdFnK3p4W99KSyJ5BU7Iv", 'consumer_key' => "qFt8kyGlietTJoduRItBAU2oJ", 'consumer_secret' => "YWlaR5amBQWlwB62Uah8hjNoCnYYme7tMcrUDg0Z9SKaFvh4eC" );

Set the request URL and Method where w3guy is your Twitter username.

设置请求URL和方法,其中w3guy是您的Twitter用户名。

$url = 'https://api.twitter.com/1.1/statuses/user_timeline.json'; $getfield = '?screen_name=w3guy'; $request_method = 'GET';

Finally, process the request like so.

最后,像这样处理请求。

$twitter_instance = new Twitter_API_WordPress( $settings ); $result = $twitter_instance ->set_get_field( $getfield ) ->build_oauth( $url, $request_method ) ->process_request();

If all goes well, the variable $result will be populated with a JSON data of your recent tweets.

如果一切顺利,变量$result将使用您最近的鸣叫的JSON数据填充。

For a POST request, for example, say you want to update your profile description.

例如,对于POST请求,说您想更新您的个人资料描述。

$settings = array( 'oauth_access_token' => "211978035-tcdnwn5GlzeY9tKiMqTvkSLNPAgcwO5ABtqwgx18", 'oauth_access_token_secret' => "rS0CMxoVNmcUYG5nWi2OhY8bJdFnK3p4W99KSyJ5BU7Iv", 'consumer_key' => "qFt8kyGlietTJoduRItBAU2oJ", 'consumer_secret' => "YWlaR5amBQWlwB62Uah8hjNoCnYYme7tMcrUDg0Z9SKaFvh4eC" ); /** POST fields required by the URL above. See relevant docs as above **/ $url = 'https://api.twitter.com/1.1/account/update_profile.json'; $postField = array( 'description' => 'Web Developer, Writer, Geek' ); $request_method = 'POST'; $instance = new Twitter_API_WordPress( $settings ); $update = $instance ->set_post_fields( $postField ) ->build_oauth( $url, $request_method ) ->process_request();

信贷与资源 (Credit & Resources)

The structure and code of this class was inspired by James Mallison’s PHP Twitter client.

该类的结构和代码受James Mallison的PHP Twitter客户端的启发。

To learn more about Twitter API and OAuth, see the resources below.

要了解有关Twitter API和OAuth的更多信息,请参见下面的资源。

OAuth Authentication Demystified

OAuth身份验证已神秘化

How Twitter oAuth Works in Scenario Context

Twitter oAuth如何在方案上下文中工作

Twitter’s Documentation

Twitter的文档

Creating a PHP OAuth Server

创建一个PHP OAuth服务器

IETF RFC

IETF RFC

结论 (Conclusion)

In this article, we learned about OAuth and how to consume Twitter using an HTTP client class powered by WordPress HTTP API. As previously stated, this class should be used within a WordPress plugin because it uses the WordPress HTTP API, which is only present or instantiated when WordPress is loaded. This PHP class can come in handy in building, for example, a recent tweets widget.

在本文中,我们了解了OAuth以及如何使用由WordPress HTTP API支持的HTTP客户端类使用Twitter。 如前所述,此类应在WordPress插件中使用,因为它使用WordPress HTTP API,该API仅在加载WordPress时存在或实例化。 这个PHP类可以在构建时派上用场,例如, 最近的tweets小部件 。

The code is available on GitHub. Feel free to fork and even submit pull requests.

该代码可在GitHub上获得 。 随意分叉,甚至提交拉取请求。

Be sure to subscribe to the WordPress channel to keep abreast of my upcoming tutorials.

确保订阅WordPress频道,以跟上我即将发布的教程。

Happy Coding.

编码愉快。

翻译自: https://www.sitepoint.com/oauth-twitter-wordpress-http-api/

oauth2 api

相关资源:密钥环:密钥环是WordPress的身份验证框架。 它带有各种HTTP Basic,OAuth1和OAuth2 Web服务的定义。 将其用作在WordPress代码中与其他Web服务一起使用的通用基础-源码
最新回复(0)