how to get user profile from linked in using codeigniter - codeigniter-2

How do you get the user profile after you have finish verification in linkedin? I've been googling around and found some tutorials but none of them are working, or should I say I can't get them to work. Below is my controller.
function __construct(){
parent::__construct();
$this->config->load('linkedin');
$this->data['consumer_key'] = $this->config->item('api_key');
$this->data['consumer_secret'] = $this->config->item('secret_key');
$this->data['callback_url'] = site_url() . 'main/linkedin_display';
}
function linkedin_request(){
$this->load->library('linkedin', $this -> data);
$token = $this->linkedin->get_request_token();
$oauth_data = array(
'oauth_request_token' => $token['oauth_token'],
'oauth_request_token_secret' => $token['oauth_token_secret']
);
$this->session->set_userdata($oauth_data);
$request_link = $this->linkedin->get_authorize_URL($token);
header("Location: " . $request_link);
}
function linkedin_display{
// get user details(first name, email etc) here
}

Add the following function to your linkedin library, in order to get data
function getData($url, $access_token)
{
$request = OAuthRequest::from_consumer_and_token($this->consumer, $access_token, "GET", $url);
$request->sign_request($this->method, $this->consumer, $access_token);
$auth_header = $request->to_header("https://api.linkedin.com");
$response = $this->httpRequest($shareUrl, $auth_header, "GET");
return $response;
}
Then create a function in your controller as follows:
/**
* Fetch linkedin profile
*/
function myprofile()
{
$auth_data = $this->session->userdata('auth');
$this->load->library('linkedin', $this->data);
$status_response = $this->linkedin->getData('http://api.linkedin.com/v1/people/~', unserialize($auth_data['linked_in']));
print_r($status_response);
}
This should work for you.

Related

How to pass whole url as params?

I want allow user to scan QR code and go to website. This is search results with params in url address like
http://example.com/qr-code/http://example.org/search/user_id=12&model_id=4&role_id=8
My route is set as
Route::get('qr-code/{data?}/{size?}', 'QrController#qrCode')->name('qr-code');
so i hope my $data will get url:
http://example.org/search/user_id=12&model_id=4&role_id=8
My Controller has
public function qrCode(Request $request, $data = null, $size = 60) {
dd(88);
$data = (empty($data)) ? env('APP_URL') : $data;
return view('qr.code')->with('qr', QrCode::size($size)->generate($data));
}
But i can't even see dd(88) route redirect to main page.
How can i fix that ?
The thing is that Laravel doesn't know that you will provide an entire URL as a parameter. He could interpret everything like that:
http://example.com/qr-code/http:/ /search/user_id=12&model_id=4&role_id=8 . Try encoding the URL diffrently. Your $data will be "http:/" and your size will be 60.
Ok i took i added to helper
function base64url_encode($s) {
return str_replace(array('+', '/'), array('-', '_'), base64_encode($s));
}
function base64url_decode($s) {
return base64_decode(str_replace(array('-', '_'), array('+', '/'), $s));
}
And then i am getting URI from request on view like
Click me
From JS i send params to QrController
public function qrCode(Request $request, $data = null, $type = null, $size = 200) {
$data = (empty($data)) ? env('APP_URL') : $data;
if ($type == 'url') $data = env('APP_URL') . base64url_decode($data);
return view('qr.code')->with('qr', QrCode::size($size)->generate($data));
}
And works fine. Base64 has + or / sometimes so thats why need to replace both - and _ and second is i add base url from env to make whole address.
Thx

Vuejs Laravel Axios create request

I have a vuejs method which implements axios to send a put/create request over to my laravel api create method passing over some data.
create(data) {
this.mute = true;
window.axios.put('/api/showreels/create', {data}).then(({ data }) => {
this.showreels.push(new Showreel(data));
this.mute = false;
}).catch(error => {
document.write(error.response.data);
});
},
My api.php is setup with the following resource
//Showreel
Route::resource('/showreels' , 'ShowreelController' , [
'except' => ['edit', 'show', 'store']
]);
And I have a create method to handle the request and update persist the data. (Which I have added a load of debugging in)
/**
* Create a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create(Request $request)
{
$message = 'sdfsdfsdf';
$message = $message . $request->heading . 'BALLS';
\App::abort(500, $message);
$showreel = new Showreel();
$showreel->heading = $request->heading;
$showreel->subheading = $request->subheading;
$showreel->detail = $request->heading;
$showreel->youtubeid = $request->youtubeid;
$showreel->heading = "test";
$showreel->subheading = "test";
$showreel->detail = "test";
$showreel->youtubeid = "test";
$showreel->save();
return response($showreel->jsonSerialize(), Response::HTTP_CREATED);
}
However laravel is giving me this error.
Not sure why I am getting this error?
Looks like I had the STORE option disabled in my api.php which was closing down the post request option. The post request now takes me through to my store method in laravel.

API REST don't work routes

I'm using codeigniter, for make an api rest, with the library that provide the oficial web site.
The problem is: the file routes.php doesn't redirect well. When i put localhost/API/1 into my browser apear the 404 error.
Here my controller "Apicontroller":
public function __construct() { //constructor //no tocar
parent::__construct();
$this -> load -> model("Modelocontrolador");
}
public function index_get() { //get all the info
$datos_devueltos = $this->Modelocontrolador->getPrueba(NULL, "Usuarios");
if(!is_null($datos_devueltos)){
$this->response(array("response" => $datos_devueltos), 200);
}else{
$this->response(array("response" => "No date"), 200);
}
}
public function find_get($id){ //select where
$datos_devueltos = $this->Modelocontrolador->getPrueba($id, "Usuarios");
if($id != NULL){
if(!is_null($datos_devueltos)){
$this->response(array("response" => $datos_devueltos), 200);
}else{
$this->response(array("response" => "No date"), 200);
}
}else{
$this->response(array("response" => "No dates for search"), 200);
}
}
public function index_post() { //insert in la table
if(! $this -> post("dato")){
$this->response(array("response" => "No enought info"), 200);
}else{
$datoID = $this -> Modelocontrolador -> save($this -> post("dato"),"UsuariosJJ");
if(!is_null($datoID)){
$this->response(array("response" => $datoID), 200);
}else{
$this->response(array("response" => "No found it"), 200);
}
}
}
public function index_put($id) { //"update"
if(! $this -> post("dato") || ! $id){
$this->response(array("response" => "No ha mandado informacion correcta para el update"), 200);
}else{
$datoID = $this -> Modelocontrolador -> update("Uid",$id,$this -> post("dato"),"UsuariosJJ");
if(!is_null($datoID)){
$this->response(array("response" => "Dato actualizado"), 200);
}else{
$this->response(array("response" => "Error modify"), 200);
}
}
}
public function index_delete($id) {
if(! $id){
$this->response(array("response" => "Not enought info"), 200);
}else{
$delete = $this-> Modelocontrolador -> delete("Uid",$id,"UsuariosJJ");
}
if(!is_null($delete)){
$this->response(array("response" => "Date delete"), 200);
}else{
$this->response(array("response" => "Error delete"), 200);
}
}}
And my routes file:
$route['default_controller'] = 'Apicontroller';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
/*sub-rutas*/
/*---------*/
$route["Apicontroller"]["get"] = "Apicontroller/index"; //basico
$route["Apicontroller/(:num)"]["get"] = "Apicontroller/find"; //select
$route["Apicontroller"]["post"] = "Apicontroller/index"; //insert
$route["Apicontroller/(:num)"]["put"] = "Apicontroller/index/$1"; //update
$route["Apicontroller/(:num)"]["delete"] = "Apicontroller/index/$1"; //delete
If the browser request literally uses /API then routing needs to 'see' exactly that. Also, the route rules must be explicit with the method to be called. (Hopefully the code shown reflects the mapping you had in mind.)
/*sub-rutas*/
/*---------*/
$route["API"]["get"] = "Apicontroller/index_get"; //basico
$route["API/(:num)"]["get"] = "Apicontroller/find_get/$1"; //select
$route["API"]["post"] = "Apicontroller/index_post"; //insert
$route["API/(:num)"]["put"] = "Apicontroller/index_put/$1"; //update
$route["API/(:num)"]["delete"] = "Apicontroller/index_delete/$1"; //delete
Using the above routes I created some test code. Here are those files.
The much simplified Apicontroller.
class Apicontroller extends CI_Controller
{
function __construct()
{
parent::__construct();
}
function index_get()
{
echo "API index";
}
public function find_get($id)
{ //select where
echo "API find_get $id";
}
public function index_post()
{
echo 'API index_post';
}
public function index_put($id)
{ //"update"
echo "API put $id";
}
}
I don't believe that because your Apicontroller is extending a different Class the results would change. That may be a drastic assumption.
In order to test POST calls I used these two files.
First a Testpost.php controller
class Testpost extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper('form');
}
public function index()
{
$this->load->view("test");
}
}
The very simple view (test.php) loaded by the above.
<?php
echo form_open("API");
echo form_submit('mysubmit', 'Submit Post!');
echo form_close();
Directing the browser to localhost/testpost shows a page with a single submit button. Pressing the button results in a screen with the text "API index_post".
Sending the browser to localhost/API/3 produces a screen with the text "API find_get 3".
localhost/API produces "API index".
Now the interesting thing (not related to your problem, but interesting).
Given the default
$route['default_controller'] = 'Apicontroller';
and the route
$route["API"]["get"] = "Apicontroller/index_get";
I expected that directing the browser to the home page localhost would produce "API index". But it doesn't. It results in a 404. Due to that behavior it might be wise to be more explicit with default_controller
$route['default_controller'] = 'Apicontroller/index_get';
Or add an index() function to Apicontroller that calls $this->index_get().
I did not test PUT or DELETE as my server isn't setup to handle them. But as GET and POST seem to function, in a righteous world, they will work.
seems like you are using PHil's REST_Controller library with CI 2.x, correct ?
If so, I would recommend you to use what I like to call an "index gateway" because you can't do per-Method routing with CI2:
class Apicontroller extends REST_Controller
{
function index_gateway_get($id){
$this->get_get($id);
}
function index_gateway_put($id){
$this->put_put($id);
}
// This is not a "gateway" method because POST doesn't require an ID
function index_post(){
$this->post_post();
}
function get_get($id = null){
if(!isset($id)){
// Get all rows
}else{
// Get specific row
}
}
function put_put($id = null){
if(!isset($id)){
// a PUT withtout an ID is a POST
$this->post_post();
}else{
// PUT method
}
}
function post_post(){
// POST method
}
}
The routing to make this work is really easy:
$route["API/(:num)"] = "Apicontroller/index_gateway/$1";
That's all you need. Phil's REST Library will redirect to the correct index_gateway_HTTPMETHOD depending on which method is used.
Each index_gateway_HTTPMETHOD will then redirect to the correct method.
As far as I know, this trick is the only way to have CI2 use a single /API/ entry point that works for all HTTP Methods.

how to get facebook email id from Nodge/yii2-eauth

Am trying to integrate Yii2 EAuth for facebook login integration.
I made configaration * in model am using below code
public static function findIdentity($id) {
if (Yii::$app->getSession()->has('user-'.$id)) {
return new self(Yii::$app->getSession()->get('user-'.$id));
}
else {
return isset(self::$users[$id]) ? new self(self::$users[$id]) : null;
}
}
/**
* #param \nodge\eauth\ServiceBase $service
* #return User
* #throws ErrorException
*/
public function findByEAuth($service) {
if (!$service->getIsAuthenticated()) {
throw new ErrorException('EAuth user should be authenticated before creating identity.');
}
$id = $service->getServiceName().'-'.$service->getId();
// echo $id;exit;
print_r($service->getAttribute('email'));
echo '<pre>';
print_r($service->getAttributes());
exit;
$attributes = array(
'id' => $id,
'username' => $service->getAttribute('name'),
'authKey' => md5(#$id),
'profile' => $service->getAttributes(),
);
$attributes['profile']['service'] = $service->getServiceName();
Yii::$app->getSession()->set('user-'.$id, $attributes);
return new self($attributes);
}
i want email , pls can any one help me to get facebook email id...thanks in advance......
I managed to get the email of the user from facebook after changing the few setting in vendor\nodge\yii2-eauth\src\services\FacebookOAuth2Service.php.
Edit FacebookOAuth2Service.php
Override protected $scopes = array(self::SCOPE_EMAIL);
And modify the fetchAttributes() functions. It should look like this:
protected function fetchAttributes()
{
$info = $this->makeSignedRequest('me');
$this->attributes['id'] = $info['id'];
$this->attributes['name'] = $info['name'];
$this->attributes['url'] = $info['link'];
$this->attributes['email'] = $info['email'];
return true;
}
Try and see it it works for you.

How to return to edit form?

I have this code in my controller (admin):
function save(){
$model = $this->getModel('mymodel');
if ($model->store($post)) {
$msg = JText::_( 'Yes!' );
} else {
$msg = JText::_( 'Error :(' );
}
$link = 'index.php?option=com_mycomponent&view=myview';
$this->setRedirect($link, $msg);
}
In model I have:
function store(){
$row =& $this->getTable();
$data = JRequest::get('post');
if(strlen($data['fl'])!=0){
return false;
}
[...]
And this is working - generate error message, but it return to items list view. I want to stay in edit view with entered data. How to do it?
In your controller you can:
if ($model->store($post)) {
$msg = JText::_( 'Yes!' );
} else {
// stores the data in your session
$app->setUserState('com_mycomponent.edit.mymodel.data', $validData);
// Redirect to the edit view
$msg = JText::_( 'Error :(' );
$this->setError('Save failed', $model->getError()));
$this->setMessage($this->getError(), 'error');
$this->setRedirect(JRoute::_('index.php?option=com_mycomponent&view=myview&id=XX'), false));
}
then, you will need to load the data from session with something like:
JFactory::getApplication()->getUserState('com_mycomponent.edit.mymodel.data', array());
normally this is loaded in the method "loadFormData" in your model. Where to load that data will depend on how are you implementing your component. If you are using the Joomla's form api then you can add the following method to your model.
protected function loadFormData()
{
// Check the session for previously entered form data.
$data = JFactory::getApplication()->getUserState('com_mycomponent.edit.mymodel.data', array());
if (empty($data)) {
$data = $this->getItem();
}
return $data;
}
EDIT:
BUT please note, that Joomla's API already can do all this for you if you controller inherits from "JControllerForm", you don't need to rewrite the save method. The best way to create your component is copying what is in Joomla's core components, com_content for example
It is not recommended to rewrite save or any method.
If you really want to override something and want to update something before or after save, you should use JTable file.
For Example:
/**
* Example table
*/
class HelloworldTableExample extends JTable
{
/**
* Method to store a node in the database table.
*
* #param boolean $updateNulls True to update fields even if they are null.
*
* #return boolean True on success.
*/
public function store($updateNulls = false)
{
// This change is before save
$this->name = str_replace(' ', '_', $this->name);
if (!parent::store($updateNulls))
{
return false;
}
// This function will be called after saving table
AnotherClass::functionIsCallingAfterSaving();
}
}
You can extends any method using JTable class and that's the recommended way to doing it.

Resources