I want to pull channel information based on a username or channel id. This information is derived from the URL used to view that channel.
EX: https://www.youtube.com/user/csga5000, or, https://www.youtube.com/channel/some-channel-id
I have this code:
$this->load->library('APIs/YouTube');
echo "[";
echo json_encode($this->youtube->getId('channel/UCkklJA9WbtJM5-g21xHI3yA'),false);
echo "\n]";
The function called is:
public function getId($url) {
$id = explode('/', $url);
echo json_encode($id).',';
//User's channel
if ($id[0] === 'user') {
$response = $this->youtube->channels->listChannels('id,snippet',array(
'forUsername' => $id[1]
));
}
//Channel id
else {
$response = $this->youtube->channels->listChannels('id,snippet',array(
'id' => $id[1],
'maxResults' => 2
));
}
return $response;
}
Here is the construct function for the youtube class:
public function __construct()
{
$this->client = new Google_Client();
$this->client->setDeveloperKey($this->api_key);
$this->client->setClientId($this->client_id);
$this->client->setClientSecret($this->client_secret);
$this->client->setScopes(array(
Google_Service_Oauth2::PLUS_LOGIN,
Google_Service_Oauth2::PLUS_ME,
Google_Service_Oauth2::USERINFO_EMAIL,
Google_Service_Oauth2::USERINFO_PROFILE,
Google_Service_YouTube::YOUTUBE
));
$ci =& get_instance();
$this->client->setRedirectUri($ci->config->item('base_url').'auth/youtube/');
$this->oauth = new Google_Service_Oauth2($this->client);
$this->youtube = new Google_Service_YouTube($this->client);
}
Calling the function with 'user/csga5000' doesn't work either
The results printed are:
[
[
"channel",
"UCkklJA9WbtJM5-g21xHI3yA"
],
{
"etag":"\"IHLB7Mi__JPvvG2zLQWAg8l36UU\/KcPrlZVHCJ9bAKurpGOj1BBEH6g\"",
"eventId":null,
"kind":"youtube#channelListResponse",
"nextPageToken":null,
"prevPageToken":null,
"visitorId":null
}
]
I just want results like this:
https://www.googleapis.com/youtube/v3/channels?part=id%2Csnippet&id=UCkklJA9WbtJM5-g21xHI3yA&key={YOUR_API_KEY}
or
https://www.googleapis.com/youtube/v3/channels?part=id%2Csnippet&forUsername=csga5000&key={YOUR_API_KEY}
Which you can test here:
https://developers.google.com/youtube/v3/docs/channels/list#try-it
With forUsername csga5000 or id UCkklJA9WbtJM5-g21xHI3yA
All the examples I found used "mine => true" and oauth to load this data, so nothing on google, or stack overflow seemed helpful.
I was just missing something silly, I'd been super confused by the response.
I needed the line:
$response->getItems();
Related
I am new in PHP and working to modify one API. Its built with Laravel Framework. I have API function like below in my controller.
public function DeleteOneMail(Request $request)
{
$uid = $request->uid;
if (\Request::is('api/*')) {
if ($request->has('key')) {
if (in_array($request->input('key'), explode(',', env('API_KEY')))) {
if ($uid == '') {
return response()->make('Please Enter UID', 401);
} else {
$client = Client::account('default');
$client->connect();
$inbox = $client->getFolder('INBOX');
$message = $inbox->getMessage($uid);
if ($message) {
return response(['success' => 1], 200);
} else {
return response(['success' => 0, 'message' => 'No Data Found'], 200);
}
}
} else {
return response()->make('Unauthorized Access. Please enter correct API Key', 401);
}
} else {
return response()->make('Unauthorized Access. Please enter correct API Key', 401);
}
}
}
I am calling API like below
https://example.com/api/delete-one-mail?key=2221212&uid=214
Its working fine without any issue. Now I want pass multiple uid with request and so I can process that uid one by one with my api function. I am not getting idea how I can pass arrary and process it. Let me know if any expert can help me for solve my puzzle. Thanks!
Your can pass an array like this
https://example.com/api/delete-one-mail?key=2221212&uid[]=214&uid[]=111&uid[]=222
$request->uid should be an array but you can make sure (if anyone use the old url with ony one uid) by doing
$uids = Arr::wrap($request->uid);
If you want to send an array by GET request just use []
https://example.com/api/delete-one-mail?key=2221212&uid[]=1&uid[]=2
In your controller you will get an array
$uid = $request->uid;
dd($uid);
As a result you will get
[1, 2]
Function to send a message:
const TOKEN = '99999999:AAAAAAAJjZ_T6hAAAAAAAAAAAAAAA';
const URL = 'https://api.telegram.org/bot'.TOKEN.'/';
function sendGetRequest($method,$params=null){
if($params){
$url = URL.$method.'?'.http_build_query($params);
}else{
$url = URL.$method;
}
return json_decode(file_get_contents($url), JSON_OBJECT_AS_ARRAY);
}
Function call:
$un_ban_params = [
'chat_id'=> $chat_id,
'user_id'=> $user_id*1,
];
sendGetRequest( 'unbanChatMember', $un_ban_params);
The call returns null.
Accordingly, the link to return to the group does not appear.
The answer is found. "unbanChatMember" is only valid in supergroups and channels. For a simple group, this method does not work.
Is there any sample/tutorial working with both Aura router and dispatcher? I found a sample code on the documentation page:
// dispatch the request to the route handler.
// (consider using https://github.com/auraphp/Aura.Dispatcher
// in place of the one callable below.)
$callable = $route->handler;
$response = $callable($request);
// emit the response
foreach ($response->getHeaders() as $name => $values) {
foreach ($values as $value) {
header(sprintf('%s: %s', $name, $value), false);
}
}
http_response_code($response->getStatusCode());
echo $response->getBody();
and I wanna know how can I integrate the Aura dispatcher with this sample code.
The second question is when we want to retrieve a GET request using Aura router, we use something like this:
// add a route to the map, and a handler for it
$map->get('blog.read', '/blog/{id}', function ($request) {
$id = (int) $request->getAttribute('id');
$response = new Zend\Diactoros\Response();
$response->getBody()->write("You asked for blog entry {$id}.");
return $response;
});
How about the POST method? I tried the following code, but it cannot retrieve the firstname in a similar way:
$map->post('profile', '/profile', function ($request) {
$firstname = $request->getAttribute('firstname');
$response = new Zend\Diactoros\Response();
$response->getBody()->write("first name is {$firstname}");
return $response;
});
The output is missing the $firstname value:
first name is
There are multiple ways you can use Aura.Dispatcher. The example provided below is one way.
$route = $matcher->match($request);
So once you match the request, there can be a route or null.
If there is a route, you can get the $route->handler;. This can be either a callable or string.
It is your implementation that tells how the Dispatcher can be invoked. From https://gist.github.com/harikt/8671136
<?php
require dirname(__DIR__) . '/vendor/autoload.php';
use Aura\Dispatcher\Dispatcher;
use Aura\Router\RouterContainer;
use Zend\Diactoros\Response;
use Zend\Diactoros\ServerRequest;
class Blog
{
public function browse(ServerRequest $request)
{
$response = new Response();
$response->getBody()->write("Browse all posts!");
return $response;
}
public function read(ServerRequest $request, $id)
{
$id = (int) $request->getAttribute('id');
$response = new Response();
$response->getBody()->write("Read blog entry $id");
return $response;
}
public function edit(ServerRequest $request, $id)
{
$response = new Response();
$response->getBody()->write("Edit blog entry $id");
return $response;
}
}
$dispatcher = new Dispatcher;
$dispatcher->setObjectParam('controller');
$dispatcher->setMethodParam('action');
$dispatcher->setObject('blog', new Blog());
$routerContainer = new RouterContainer();
$map = $routerContainer->getMap();
// NB : You can use # sign as in Laravel. So blog#browse
$map->get('blog.browse', '/blog', 'blog::browse');
$map->get('blog.read', '/blog/{id}', 'blog::read');
$request = Zend\Diactoros\ServerRequestFactory::fromGlobals(
$_SERVER,
$_GET,
$_POST,
$_COOKIE,
$_FILES
);
$matcher = $routerContainer->getMatcher();
$route = $matcher->match($request);
if ($route) {
foreach ($route->attributes as $key => $val) {
$request = $request->withAttribute($key, $val);
}
// Take special attention, how I am using the handler.
// Do what you want with the handler
list($controller, $action) = explode('::', $route->handler);
$params = [
'controller' => $controller,
'action' => $action,
'request' => $request,
// This is not needed, just showing for demo purpose
'id' => $request->getAttribute('id'),
];
$response = $dispatcher($params);
// emit the response
foreach ($response->getHeaders() as $name => $values) {
foreach ($values as $value) {
header(sprintf('%s: %s', $name, $value), false);
}
}
http_response_code($response->getStatusCode());
echo $response->getBody();
} else {
echo "No route found";
}
I repeat this is not the only way. There are other better ways, read https://github.com/auraphp/Aura.Web_Kernel if you are really interested to learn more.
Regarding your question about getting value from POST. No there is no other way. The router is not handling the POST values. I think probably PSR-7 could have improved a bit in those areas :-) .
I have a problem with the Google API. I need to get all the contacts of a user in my application, however I don't want to load all the data each time, because I store the data in my database.
It's why I want to use the Sync Token functionality which let's us get only data who has been changed since our last query.
For this i Use the Google APIs PHP client library.
I wrote my code and it throws an exception (Google_Service_Exception) which explains that my Sync Token is not valid anymore, so I decided to use a try/catch system to reset syncToken if it is not valid.
My problem is each time i made the request I go in the catch (the google_service_exception) is raised even if my token is valid.
I store the token in my database so I tested it in the API explorer here: https://developers.google.com/people/api/rest/v1/people.connections/list and it work fine, so I don't understand why my application doesn't work properly.
Here's my code:
$personFields = 'metadata,names,addresses,biographies,birthdays,emailAddresses,genders,memberships,organizations,phoneNumbers';
$user = $this->get('security.token_storage')->getToken()->getUser();
$syncToken = $user->getContactSyncToken();
$nextPagetoken = '';
$contactData = array();
$people_service = new \Google_Service_PeopleService($client);
do {
try {
$data = $people_service->people_connections->listPeopleConnections(
'people/me',
array(
'personFields' => $personFields,
'requestSyncToken' => true,
'syncToken' => $syncToken,
'pageToken' => $nextPagetoken,
)
);
}catch (\Google_Service_Exception $e){
$data = $people_service->people_connections->listPeopleConnections(
'people/me',
array(
'personFields' => $personFields,
'requestSyncToken' => true,
'syncToken' => '',
'pageToken' => $nextPagetoken,
)
);
}finally{
$syncToken = $data->getNextSyncToken();
$nextPagetoken = $data->getNextPageToken();
if (count($data->getConnections()) != 0) {
$contactData[] = $data->getConnections();
}
}
}while ($nextPagetoken !== null);
$user->setContactSyncToken($syncToken);
$this->getDoctrine()->getManager()->flush();
return $contactData;
Thank you for your help and sorry for my english i'm not a native and not very good at it.
Sorry i found the problem, in my User class i had:
public function getContactSyncToken()
{
if($token = $this->contactSyncToken !== null){
return $token;
}else{
return '';
}
}
And it always return ' ', now it works with:
public function getContactSyncToken()
{
$token = $this->contactSyncToken;
if($token !== null){
return $token;
}else{
return '';
}
}
While trying to request data from en external API, I want to control how the response is being passed to my view or database. However what would be the correct way to write the code below, so instead of simply echoing the data onto the view I would like to store it inside an object that I can pass to my view or model in a more controlled way?
public function index()
{
$contents = $this->saveApiData();
return View::make('stats.index')->with('contents', $contents);
}
public function saveApiData()
{
$client = new Client(['base_uri' => 'https://owapi.net/api/v3/u/']);
$res = $client->request('GET', "data" . "/blob");
echo $res->getStatusCode();
echo $res->getBody();
}
Just put them together in an array and return it. You never echo data in a function to return them.
public function saveApiData()
{
$client = new Client(['base_uri' => 'https://owapi.net/api/v3/u/']);
$res = $client->request('GET', "data" . "/blob");
$contents = [
'status' => $res->getStatusCode(),
'body' => $res->getBody()
];
return $contents;
}