Skip to content

Instantly share code, notes, and snippets.

@nguyenphuocnhatthanh
Created May 8, 2017 03:12
Show Gist options
  • Save nguyenphuocnhatthanh/f7999f415830a38b36c88a4c8e8a2c1f to your computer and use it in GitHub Desktop.
Save nguyenphuocnhatthanh/f7999f415830a38b36c88a4c8e8a2c1f to your computer and use it in GitHub Desktop.
Facebook Social
<?php
namespace App\Services\Social;
use App\Exceptions\FurusatoException;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
class FacebookService extends AbstractSocial
{
/**
* The base Facebook Graph URL.
*
* @var string
*/
protected $graphUrl = 'https://graph.facebook.com';
/**
* @var string
*/
protected $graphVideoUrl = 'https://graph-video.facebook.com';
/**
* The Graph API version for the request.
*
* @var string
*/
protected $version = 'v2.8';
/**
* The user fields being requested.
*
* @var array
*/
protected $fields = ['name', 'email', 'gender', 'verified', 'link'];
/**
* Get user data from facebook
*
* @param $token
* @return mixed
* @throws FurusatoException
*/
protected function getUserByToken($token)
{
$meUrl = $this->graphUrl.'/'.$this->version.'/me?access_token='.$token.'&fields='.implode(',', $this->fields);
if (! empty($this->clientSecret)) {
$appSecretProof = hash_hmac('sha256', $token, $this->clientSecret);
$meUrl .= '&appsecret_proof='.$appSecretProof;
}
$http = new Client();
try {
$response = $http->get($meUrl, [
'headers' => [
'Accept' => 'application/json',
],
]);
} catch (ClientException $e) {
throw new FurusatoException($e->getMessage(), config('error.social.invalid_params'));
}
return json_decode($response->getBody(), true);
}
/**
* Post to Newsfeed
*
* @param $accessToken
* @param array $params
* @return mixed
*/
public function post($accessToken, array $params)
{
$http = new Client();
$user = $this->getUserByToken($accessToken);
$response = $http->post($this->graphUrl.'/'.$this->version.'/'.$user['id'].'/feed', [
'json' => [
/* 'access_token' => $accessToken,
'message' => str_random(40),
'privacy' => [
'value' => 'EVERYONE',
],
'link' => 'http://www.youtube.com/watch?v=3aICB2mUu2k',
'source' => 'http://www.youtube.com/v/3aICB2mUu2k',
'picture' => 'http://img.youtube.com/vi/3aICB2mUu2k/0.jpg',
'properties' => [
'name' => 'test video',
'text' => 'The text video',
'href' => 'http://clips.vorwaerts-gmbh.de/VfE_html5.mp4'
]*/
]
]);
return json_decode($response->getBody(), true);
}
/**
* Convert data
*
* @param array $user
* @return array
*/
protected function mapUserToObject(array $user)
{
$avatarUrl = $this->graphUrl.'/'.$this->version.'/'.$user['id'].'/picture';
return [
'id' => $user['id'],
'nickname' => isset($user['name']) ? $user['name'] : null,
'name' => isset($user['name']) ? $user['name'] : null,
'email' => isset($user['email']) ? $user['email'] : null,
'images' => [
'origin' => $avatarUrl.'?width=1920',
'thumb' => $avatarUrl.'?width=normal',
]
];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment