Skip to content

Commit

Permalink
fix: re-add account activity trait (#372)
Browse files Browse the repository at this point in the history
Co-authored-by: Saiks <sykez@hotmail.com>
  • Loading branch information
reliq and sykezz authored Jul 19, 2021
1 parent 5278f6f commit 44331ff
Show file tree
Hide file tree
Showing 4 changed files with 216 additions and 2 deletions.
26 changes: 25 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,19 @@ It is safe to call `Twitter::forApiV1()` on either a `v1` or `v2` client instanc
* `postUserBanner()` - Uploads a profile banner on behalf of the authenticating user. For best results, upload an
profile_banner_url node in their Users objects.

#### Account Activity (Premium)

* `setWebhook($env, $url)` - Registers a webhook url for all event types in the given environment.
* `crcHash($crcToken)` - Returns HMAC SHA-256 hash from the given CRC token and consumer secret. You'll need to return this on your webhook ([more info](https://developer.twitter.com/en/docs/accounts-and-users/subscribe-account-activity/guides/securing-webhooks)).
* `getWebhooks($env)` - Returns webhook URLs for the given environment (or all environments if none provided), and their statuses for the authenticating app.
* `updateWebhooks($env, $webhookId)` - Triggers the challenge response check (CRC) for the given enviroments webhook for all activites. If the check is successful, returns true and reenables the webhook by setting its status to valid.
* `destroyWebhook($env, $webhookId)` - Removes the webhook from the provided application's all activities configuration. Returns true on success.
* `setSubscriptions($env)` - Subscribes the provided application to all events for the provided environment for all message types. Returns true on success.
* `getSubscriptions($env)` - Returns true if the provided user context has an active subscription with provided application.
* `getSubscriptionsCount()` - Returns the count of subscriptions that are currently active on your account for all activities.
* `getSubscriptionsList($env)` - Returns a list of the current All Activity type subscriptions.
* `destroyUserSubscriptions($env, $userId)` - Deactivates subscription for the specified user id from the environment. Returns true on success.

#### Block

* `getBlocks()` - Returns a collection of user objects that the authenticating user is blocking.
Expand Down Expand Up @@ -401,7 +414,7 @@ Route::get('/tweetMedia', function()

Get User Credentials with email.

```php
```
$credentials = Twitter::getCredentials([
'include_email' => 'true',
]);
Expand Down Expand Up @@ -478,6 +491,17 @@ Route::get('twitter/logout', ['as' => 'twitter.logout', function () {
}]);
```

Webhook
>In order to setup webhook successfully, you'll need to return a hash using the CRC token in response from your webhook URL ([more info](https://developer.twitter.com/en/docs/accounts-and-users/subscribe-account-activity/guides/securing-webhooks)).
```php
Route::post('twitter/webhook', ['as' => 'twitter.webhook', function(){
if (request()->has('crc_token'))
return response()->json(['response_token' => Twitter::crcHash(request()->crc_token)], 200);

// Your webhook logic goes here
}]);
```

### Twitter API v2 Examples

Get user tweets:
Expand Down
2 changes: 2 additions & 0 deletions src/ApiV1/Service/Twitter.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace Atymic\Twitter\ApiV1\Service;

use Atymic\Twitter\ApiV1\Contract\Twitter as TwitterContract;
use Atymic\Twitter\ApiV1\Traits\AccountActivityTrait;
use Atymic\Twitter\ApiV1\Traits\AccountTrait;
use Atymic\Twitter\ApiV1\Traits\AuthTrait;
use Atymic\Twitter\ApiV1\Traits\BlockTrait;
Expand All @@ -29,6 +30,7 @@ class Twitter implements TwitterContract
{
use FormattingHelpers;
use AccountTrait;
use AccountActivityTrait;
use BlockTrait;
use DirectMessageTrait;
use FavoriteTrait;
Expand Down
188 changes: 188 additions & 0 deletions src/ApiV1/Traits/AccountActivityTrait.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
<?php

/** @noinspection PhpDocRedundantThrowsInspection */

namespace Atymic\Twitter\ApiV1\Traits;

use Atymic\Twitter\Exception\TwitterException;
use Illuminate\Http\Response;

trait AccountActivityTrait
{
/**
* Creates HMAC SHA-256 hash from incoming crc_token and consumer secret.
* This base64 encoded hash needs to be returned by the application when Twitter calls the webhook.
*
* @param string $crcToken
*
* @return string
* @throws TwitterException
*/
public function crcHash(string $crcToken): string
{
$secret = $this->getQuerier()
->getConfiguration()
->getConsumerSecret();
$hash = hash_hmac('sha256', $crcToken, $secret, true);

return 'sha256=' . base64_encode($hash);
}

/**
* Registers a webhook $url for all event types in the given environment.
*
* @param mixed $env
* @param mixed $url
*
* @return object
* @throws TwitterException
*/
public function setWebhook($env, $url)
{
return $this->post("account_activity/all/{$env}/webhooks", ['url' => $url]);
}

/**
* Returns webhook URLs for the given environment (or all environments if none provided), and their statuses for the authenticating app.
*
* @param mixed $env
*
* @return object
* @throws TwitterException
*/
public function getWebhooks($env = null)
{
return $this->get('account_activity/all/' . ($env ? $env . '/' : '') . 'webhooks');
}

/**
* Triggers the challenge response check (CRC) for the given environments webhook for all activities.
* If the check is successful, returns 204 and re-enables the webhook by setting its status to valid.
*
* @param mixed $env
* @param mixed $webhookId
*
* @return bool
* @throws TwitterException
*/
public function updateWebhooks($env, $webhookId): bool
{
$this->query("account_activity/all/{$env}/webhooks/{$webhookId}", 'PUT');

$response = $this->getQuerier()
->getSyncClient()
->getLastResponse();

return $response !== null && $response->getStatusCode() === Response::HTTP_NO_CONTENT;
}

/**
* Removes the webhook from the provided application's all activities configuration.
* The webhook ID can be accessed by making a call to GET /1.1/account_activity/all/webhooks (getWebhooks).
*
* @param mixed $env
* @param mixed $webhookId
*
* @return bool
* @throws TwitterException
*/
public function destroyWebhook($env, $webhookId): bool
{
$this->delete("account_activity/all/{$env}/webhooks/{$webhookId}");

$response = $this->getQuerier()
->getSyncClient()
->getLastResponse();

return $response !== null && $response->getStatusCode() === Response::HTTP_NO_CONTENT;
}

/**
* Subscribes the provided application to all events for the provided environment for all message types.
* Returns HTTP 204 on success.
* After activation, all events for the requesting user will be sent to the application’s webhook via POST request.
*
* @param mixed $env
*
* @return bool
* @throws TwitterException
*/
public function setSubscriptions($env): bool
{
$this->post("account_activity/all/{$env}/subscriptions");

$response = $this->getQuerier()
->getSyncClient()
->getLastResponse();

return $response !== null && $response->getStatusCode() === Response::HTTP_NO_CONTENT;
}

/**
* Provides a way to determine if a webhook configuration is subscribed to the provided user’s events.
* If the provided user context has an active subscription with provided application, returns 204 OK.
* If the response code is not 204, then the user does not have an active subscription.
* See HTTP Response code and error messages for details:
* https://developer.twitter.com/en/docs/accounts-and-users/subscribe-account-activity/api-reference/aaa-premium#get-account-activity-all-env-name-subscriptions.
*
* @param mixed $env
*
* @return bool
* @throws TwitterException
*/
public function getSubscriptions($env): bool
{
$this->get("account_activity/all/{$env}/subscriptions");

$response = $this->getQuerier()
->getSyncClient()
->getLastResponse();

return $response !== null && $response->getStatusCode() === Response::HTTP_NO_CONTENT;
}

/**
* Returns the count of subscriptions that are currently active on your account for all activities.
*
* @return mixed
* @throws TwitterException
*/
public function getSubscriptionsCount()
{
return $this->get('account_activity/all/subscriptions/count', [], false, 'json');
}

/**
* Returns a list of the current All Activity type subscriptions.
*
* @param mixed $env
*
* @return mixed
* @throws TwitterException
*/
public function getSubscriptionsList($env)
{
return $this->get("account_activity/all/{$env}/subscriptions/list", [], false, 'json');
}

/**
* Deactivates subscription for the specified user id from the environment.
* After deactivation, all events for the requesting user will no longer be sent to the webhook URL.
*
* @param mixed $env
* @param mixed $userId
*
* @return bool
* @throws TwitterException
*/
public function destroyUserSubscriptions($env, $userId): bool
{
$this->delete("account_activity/all/{$env}/subscriptions/{$userId}", []);

$response = $this->getQuerier()
->getSyncClient()
->getLastResponse();

return $response !== null && $response->getStatusCode() === Response::HTTP_NO_CONTENT;
}
}
2 changes: 1 addition & 1 deletion src/Contract/Http/SyncClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,5 @@ public function request(string $method, string $url, array $data = []);
/**
* @return ResponseInterface|null
*/
public function getLastResponse();
public function getLastResponse(): ?ResponseInterface;
}

0 comments on commit 44331ff

Please sign in to comment.