Create Tweet API not working for other users - php

I've created a Twitter developer account with my profile and passing cosumer_key, consumer_secret, token_id, and token_secret and If I'm hitting create-tweet 'https://api.twitter.com/1.1/statuses/update.json' API then I'm getting a proper response but if I'm creating tweets with other users credentials I'm getting an error
([errors]=> Array([code] => 32, [message] => Could not authenticate you.)). I've given read & write permission to my app as well.
public function createTweet(Request $req) {
Log::channel('twitterwebhook')->info($req->all());
$access_token = $req->require('token_id');
$acess_token_secret = $req->require('token_secret');
$message = $req->require('message');
$twitter = new TwitterAPI($access_token, $acess_token_secret);
$response = $twitter->createTweet($message);
if(isset($response->errors)){
return error($response->errors, 4099);
}
$data = [
'tweet_id'=> $response->id,
'tweet_str_id' =>$response->id_str,
'message' =>$response->text,
'user_twitter_id'=>$response->user->id,
'user_twitter_name'=>$response->user->name,
'user_twitter_screen_name'=>$response->user->screen_name
];
return success($data);
}
public function createTweet($tweet_message) {
$postfields = [
'status' => $tweet_message,
'trim_user' => false
];
$twitterResponse = $this->buildOauth($this->_update_url, 'POST')
->setPostfields($postfields)
->performRequest();
return json_decode($twitterResponse);
}

Related

Laravel returns 302 error when trying to send POST request to API route from Laravel Controller

A 302 error is returned when I'm trying to post to API Route, only in the second Post, using the function insereTelefone. When I'm using the Postman, it's working properly, so I think the problem is with Route, but I don't know what. I'm a newbie at the Laravel, so I'm learning how to implement things.
Here is the controller who calls the POST API:
class IndexClientes extends Controller
{
public function index()
{
$request = Request::create('/api/clientes', 'GET');
$response = Route::dispatch($request);
$clientes = json_decode($response->getContent(), true);
return view('index', compact('clientes'));
}
public function create()
{
return view('formulariocliente');
}
public function store(Request $request)
{
$nome = $request->nome;
$cpf = $request->cpf;
$email = $request->email;
$numerosTelefone = $request->telefone;
$tiposTelefone = $request->tipoTelefone;
$request = Request::create('/api/clientes', 'POST', array(
"nome" => $nome,
"cpf" => $cpf,
"email" => $email
));
$responseInicial = Route::dispatch($request);
$response = json_decode($responseInicial->getContent(), true);
$status = json_decode($responseInicial->status(), true);
if ($status !== 200) :
echo "ERRO";
die();
endif;
$idCliente = $response['id'];
if (!empty($numerosTelefone)) :
$i = 0;
foreach ($numerosTelefone as $numeroTelefone) :
$tipoTelefone = (int)$tiposTelefone[$i];
$numeroTelefone = (int)$numeroTelefone;
if (!empty($tipoTelefone) && !empty($numeroTelefone)) :
return self::insereTelefone($idCliente, $tipoTelefone, $numeroTelefone);
endif;
$i++;
endforeach;
endif;
}
public function insereTelefone($idCliente, $tipoTelefone, $numTelefone)
{
$array = array(
"cliente_id" => $idCliente,
"telefone_tipo_id" => $tipoTelefone,
"numero" => $tipoTelefone
);
$request = Request::create('api/telefones', 'POST', $array);
$responseInicial = Route::dispatch($request);
$response = json_decode($responseInicial->getContent(), true);
$status = json_decode($responseInicial->status(), true);
return $status;
}
}
TelefonesController.php
public function store(Request $request)
{
$request->validate(
[
'cliente_id' => 'required',
'telefone_tipo_id' => 'required',
'numero' => 'required|max:11'
]
);
}
api.php
Route::apiResource('telefones', \App\Http\Controllers\TelefonesController::class);
A 302 response usually means your request is being redirected by laravel.
If you are expecting a json response, you need to set the Accept: 'application/json' header along with your request just after the line:
$request = Request::create('api/telefones', 'POST', $array );
$request->headers->set('Accept', 'application/json');
the first
Route::dispatch
was redirecting the page, when I'm was trying to run the second Route::dispatch Laravel returns 302, to solve this I'm using the
app()->handle()
in the function insereTelefone to back to handle the request.
public function insereTelefone($idCliente, $tipoTelefone, $numTelefone) {
$array = array(
"cliente_id" => $idCliente,
"telefone_tipo_id" => $tipoTelefone,
"numero" => $numTelefone
);
$request_telefone = Request::create('api/telefones', 'POST', $array );
$responseInicial = app()->handle($request_telefone);
$status = json_decode($responseInicial->status(),true);
return $status;
}

how to get auth in guzzle response and send to view

I am confused how to retrieve authentication details like username and password as my guzzle api is receiving only success message and code at the time of login. I am not able to make session. Please explain how I can get authentication details in dashboard view like Auth:user();
This is my controller:
<?php
public function getGuzzleRequest(Request $request)
{
$inputData = [];
$inputData = $request->all();
$client = new Client([
'allow_redirects'=>true,
]);
$URI = 'http://ahlocal.test/api/login';
$body['username']=$inputData['username'];
$body['password']=$inputData['password'];
$response = $client->request('POST', $URI,[
'form_params' => $body,
]);
$response =$response->getBody()->getContents();
if(statuscode=='200')
{
return redirect('dashboard');
}
else
{
return back()->with('error', 'Wrong Login Details');
}
}
?>
Not sure I understood you correctly, but try this option:
$client = new Client([ 'allow_redirects'=>true, ]);
$URI = 'http://ahlocal.test/api/login';
$response = $client->request('POST', $URI, [ 'auth' => [$inputData['username'], $inputData['password']]]);
$body = $response->getBody()->getContents();
if($response->getStatusCode() == 200) {
return redirect('dashboard');
} else {
return back()->with('error', 'Wrong Login Details');
}

Phalcon Rest Micro sessions not set

Iḿ trying to make an rest application using Phalcon, i save some of the info
of the logged in user in an session but i don't get this to work, my code:
$this->session->set( Sessions::USERINFO, array (
'login' => true,
'type' => UserTypes::ADMIN,
'username' => $this->user->getUsername(),
'adminid' => $this->user->getAdminID(),
'fullname' => $this->user->getFullName(),
'avatar' => $this->user->getAvatar() )
);
return $this->session->get( Sessions::USERINFO );
When he returns the session it works but when i try to get the session in an other request it returns empty
return array("session" => $this->session->isStarted(),
"session Data" => $this->session->get(Sessions::USERINFO));
isStarted returns true
get returns null
Sessions::USERINFO
is an class with const values
const USERINFO = "userInfo";
Session var creation
$di->setShared( 'session', function () {
$session = new Session();
$session->start();
return $session;
} );
I am using this to save my session:
$obj = $this->request->getJsonRawBody();
$user = Users::findFirstByUsername($obj->username);
if($user) {
if($this->security->checkHash($obj->password, $user->password)) {
unset($user->password);
$this->session->set('auth', $user->toArray());
$response = $user->toArray();
}
else {
$response = array('msg' => 'failed');
}
}
else {
$response = array('error' => 'User not found');
}
$this->setPayload($response);
return $this->render();
And this to recieve information from my session
if($this->session->get('auth')['username']) {
$response = $this->session->get('auth');
}
else {
$response = array('msg' => 'noInfo');
}
$this->setPayload($response);
return $this->render();
This is how I start my session:
$di->set('session', function () {
$session = new SessionAdapter();
$session->start();
return $session;
});
It works just fine, you might want to try this.
I found the problem. Had to enable this in my frondend application:
RestangularProvider.setDefaultHttpFields({
withCredentials: true
});
The frontend was not sending the cookie with every request.

PHP YouTube Data API get channel information without oath

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();

how to fetch linkedin data in codeigniter

I am using codeigniter and want to fetch linkedin data but it not works.. it getting no error but i could not fetch data also
i am using this code defined in following url:
Linkedin php api not setting access token in codeigniter
and codes are
create library:
defined('BASEPATH') OR exit('No direct script access allowed');
class Linkedin {
function __construct(){
}
public function getAuthorizationCode() {
$params = array('response_type' => 'code',
'client_id' => API_KEY,
'scope' => SCOPE,
'state' => uniqid('', true), // unique long string
'redirect_uri' => REDIRECT_URI,
);
// Authentication request
$url = 'https://www.linkedin.com/uas/oauth2/authorization?' . http_build_query($params);
// Needed to identify request when it returns to us
$_SESSION['state'] = $params['state'];
// Redirect user to authenticate
header("Location: $url");
exit;
}
public function getAccessToken() {
$params = array('grant_type' => 'authorization_code',
'client_id' => API_KEY,
'client_secret' => API_SECRET,
'code' => $_GET['code'],
'redirect_uri' => REDIRECT_URI,
);
// Access Token request
$url = 'https://www.linkedin.com/uas/oauth2/accessToken?' . http_build_query($params);
// Tell streams to make a POST request
$context = stream_context_create(
array('http' =>
array('method' => 'POST',
)
)
);
// Retrieve access token information
$response = file_get_contents($url, false, $context);
// Native PHP object, please
$token = json_decode($response);
// Store access token and expiration time
$_SESSION['access_token'] = $token->access_token; // guard this!
$_SESSION['expires_in'] = $token->expires_in; // relative time (in seconds)
$_SESSION['expires_at'] = time() + $_SESSION['expires_in']; // absolute time
return true;
}
public function fetch($method, $resource, $body = '') {
$params = array('oauth2_access_token' => $_SESSION['access_token'],
'format' => 'json',
);
// Need to use HTTPS
$url = 'https://api.linkedin.com' . $resource . '?' . http_build_query($params);
// Tell streams to make a (GET, POST, PUT, or DELETE) request
$context = stream_context_create(
array('http' =>
array('method' => $method,
)
)
);
// Hocus Pocus
$response = file_get_contents($url, false, $context);
// Native PHP object, please
return json_decode($response);
}
}
Put all your Constants stuff in confin/constants.php
define('API_KEY', 'Put Yoour API_KEY here');
define('API_SECRET', 'Put Yoour API_SECRET here');
define('REDIRECT_URI', 'Put Yoour REDIRECT_URI here');
define('SCOPE', 'r_fullprofile r_emailaddress rw_nus r_contactinfo r_network');
and finally make my controller
class Profile extends CI_Controller {
function __construct() {
parent:: __construct();
$this->load->library('linkedin'); // load library
session_name('linkedin');
session_start();
}
// linkedin login script
function profile() {
// OAuth 2 Control Flow
if (isset($_GET['error'])) {
// LinkedIn returned an error
// load any error view here
exit;
} elseif (isset($_GET['code'])) {
// User authorized your application
if ($_SESSION['state'] == $_GET['state']) {
// Get token so you can make API calls
$this->linkedin->getAccessToken();
} else {
// CSRF attack? Or did you mix up your states?
exit;
}
} else {
if ((empty($_SESSION['expires_at'])) || (time() > $_SESSION['expires_at'])) {
// Token has expired, clear the state
$_SESSION = array();
}
if (empty($_SESSION['access_token'])) {
// Start authorization process
$this->linkedin->getAuthorizationCode();
}
}
// define the array of profile fields
$profile_fileds = array(
'id',
'firstName',
'maiden-name',
'lastName',
'picture-url',
'email-address',
'location:(country:(code))',
'industry',
'summary',
'specialties',
'interests',
'public-profile-url',
'last-modified-timestamp',
'num-recommenders',
'date-of-birth',
);
$profileData = $this->linkedin->fetch('GET', '/v1/people/~:(' . implode(',', $profile_fileds) . ')');
if ($profileData) {
$this->session->set_userdata("profile_session",$profileData);
} else {
// linked return an empty array of profile data
}
}
}
When i am running this controller then linkedin api works a modal window appears with my app name ..but after login
When i trying to print this session it does not apppears... dont know this code is working or not.. please help
This should work:
LinkedIn Class:
class Linkedin extends CI_Controller {
function __construct(){
parent:: __construct();
$this->load->library('session');
}
public function getAuthorizationCode() {
$params = array('response_type' => 'code',
'client_id' => API_KEY,
'scope' => SCOPE,
'state' => uniqid('', true), // unique long string
'redirect_uri' => REDIRECT_URI,
);
// Authentication request
$url = 'https://www.linkedin.com/uas/oauth2/authorization?' . http_build_query($params);
// Needed to identify request when it returns to us
$this->session->set_userdata('state',$params['state']);
// Redirect user to authenticate
header("Location: $url");
exit;
}
public function getAccessToken() {
$params = array('grant_type' => 'authorization_code',
'client_id' => API_KEY,
'client_secret' => API_SECRET,
'code' => $_GET['code'],
'redirect_uri' => REDIRECT_URI,
);
// Access Token request
$url = 'https://www.linkedin.com/uas/oauth2/accessToken?' . http_build_query($params);
// Tell streams to make a POST request
$context = stream_context_create(
array('http' =>
array('method' => 'POST',
)
)
);
// Retrieve access token information
$response = file_get_contents($url, false, $context);
// Native PHP object, please
$token = json_decode($response);
// Store access token and expiration time
$ses_params = array('access_token' => $token->access_token,
'expires_in' => $token->expires_in,
'expires_at' => time() + $_SESSION['expires_in']);
$this->session->set_userdata($ses_params);
return true;
}
public function fetch($method, $resource, $body = '') {
$params = array('oauth2_access_token' => $_SESSION['access_token'],
'format' => 'json',
);
// Need to use HTTPS
$url = 'https://api.linkedin.com' . $resource . '?' . http_build_query($params);
// Tell streams to make a (GET, POST, PUT, or DELETE) request
$context = stream_context_create(
array('http' =>
array('method' => $method,
)
)
);
// Hocus Pocus
$response = file_get_contents($url, false, $context);
// Native PHP object, please
return json_decode($response);
}
}
Profile Controller:
class Profile extends CI_Controller {
function __construct() {
parent:: __construct();
$this->load->library('linkedin'); // load library
$this->load->library('session');
}
// linkedin login script
function profile() {
// OAuth 2 Control Flow
if (isset($_GET['error'])) {
// LinkedIn returned an error
// load any error view here
exit;
} elseif (isset($_GET['code'])) {
// User authorized your application
if ($this->session->userdata('state'); == $_GET['state']) {
// Get token so you can make API calls
$this->linkedin->getAccessToken();
} else {
// CSRF attack? Or did you mix up your states?
exit;
}
} else {
if ((empty($this->session->userdata('expires_at'))) || (time() > $this->session->userdata('expires_at'))) {
// Token has expired, clear the state
$this->session->sess_destroy();
}
if (empty($this->session->userdata('access_token'))) {
// Start authorization process
$this->linkedin->getAuthorizationCode();
}
}
// define the array of profile fields
$profile_fileds = array(
'id',
'firstName',
'maiden-name',
'lastName',
'picture-url',
'email-address',
'location:(country:(code))',
'industry',
'summary',
'specialties',
'interests',
'public-profile-url',
'last-modified-timestamp',
'num-recommenders',
'date-of-birth',
);
$profileData = $this->linkedin->fetch('GET', '/v1/people/~:(' . implode(',', $profile_fileds) . ')');
if ($profileData) {
$this->session->set_userdata("profile_session",$profileData);
} else {
// linked return an empty array of profile data
}
}
}

Categories