How would you like to Share on LinkedIn using PHP OAuth Class - php

I'm trying to use the CallAPI function to post a status remotely after I get the tokens, but it's not working for some reason.
Here is my code:
if (($success = $client->Initialize())) {
if (($success = $client->Process())) {
if (strlen($client->access_token)) {
$url = 'http://api.linkedin.com/v1/people/~/shares';
$method = 'POST';
$parameters = array('comment' => 'Some comment', 'content' => 'Some content', 'title' => 'Some title');
$options = array();
$success = $client->CallAPI($url, $method, $parameters, $options, $response);
}
}
$success = $client->Finalize($success);
}
I'm doing something wrong, but I can't find out what, because it doesn't give me any errors.

Related

Update query laravel return false result and nothing error show why?

i'm working with laravel project, and i have an issue that is update query result return false value if i update with the same data, how to solve this? do i have to validate first before run the query and send a notification that the data is the same?
well this is my codes
public function update(Request $request)
{
$kamar_id = $request->input('kamar_id');
$title = $request->input('title');
$content = $request->input('content');
$keyword = $request->input('keyword');
$description = $request->input('description');
$prolog = $request->input('prolog');
$path = $request->input('path');
$sort = $request->input('sort');
$status = $request->input('status');
$type = $request->input('type');
$user_id = $request->input('user_id');
if (empty($request->input('path'))) {
$path = serialize(array('data/def.png'));
}else{
$path = serialize(explode(',', $request->input('path')));
}
$data = array('title' => $title,
'content' => $content,
'keyword' => $keyword,
'description' => $description,
'prolog' => $prolog,
'path' => $path,
'sort' => $sort,
'status' => $status,
'type' => $type,
'user_id' => $user_id);
// echo($kamar_id);
$update = Kamar::where('kamar_id',$kamar_id)->update($data);
if ($update) {
$response['status'] = 1;
}else{
$response['status'] = 0;
}
return response()->json($response);
}
thanks for helping me
Laravel Eloquent Update method returns true if anything updated in database from your query and return false if nothing is updated in database from your query.
refer:
https://laravel.com/docs/5.8/eloquent#updates
!nullTry
$update = Kamar::where('kamar_id','=',$kamar_id)->first();
if (!null($update))
{
$update->title = $title;
$update->content = $content;
$update->keyword = $keyword;
$update->description = $description;
$update->prolog = $prolog;
$update->path = $path;
$update->sort = $sort;
$update->status = $status;
$update->type = $type;
$update->user_id = $user_id;
$update->save();
$response['status'] = 1;
}
else
{
$response['status'] = 0;
}
Try using this
$kamarObj = new Kamar();
$kamarData = $kamarObj->find($kamar_id);
$result = $kamarData->update($data);
You can force updated_at column to be updated (or you can create this column if you don't have). So the query will be always updated.

How to use linked in login for https server?

Previously i was used http server for my linkedin login. Now I changed https server for my entire site. But now i cannot show login details after changed that. Here i post my function, In this fuction i also changed https. But yet not i show the details. I use this function in codeigniter.
public function login(){
$client_id = $this->config->item('linkedin_app_id');
$redirect_uri = base_url().'linkedinLogin';
if (isset($_GET['error'])) {
echo $_GET['error'] . ': ' . $_GET['error_description'];
} elseif (isset($_GET['code'])) {
$this->loginAccessToken();
$user = $this->login_fetch('GET', '/v1/people/~:(id,firstName,lastName,email-address,picture-url)');//get name
$email = $user->emailAddress;
$user_name = $user->firstName;
$last_name = $user->lastName;
$social_id = $user->id;
$profile_image_url = 'user-thumb.png';
echo "<pre>";print_r($user); die;
if($email != '')
{
$googleLoginCheck = $this->user_model->googleLoginCheck($email);
if($googleLoginCheck > 0)
{
//echo "login";
$getGoogleLoginDetails = $this->user_model->google_user_login_details($email);
//echo "<pre>";print_r($getGoogleLoginDetails);die;
$userdata = array(
'fc_session_user_id' => $getGoogleLoginDetails['id'],
'session_user_email' => $getGoogleLoginDetails['email']
);
//echo "<pre>";print_r($userdata);die;
$this->session->set_userdata($userdata);
if($this->data['login_succ_msg'] != '')
$lg_err_msg = $this->data['login_succ_msg'];
else
$lg_err_msg = 'You are Logged In ...';
$this->setErrorMessage('success',$lg_err_msg);
redirect(base_url());
}
else
{
$google_login_details = array('social_login_name'=>$user_name,'social_login_unique_id'=>$social_id,'screen_name'=>$user_name,'social_image_name'=>'','social_email_name'=>$email,'loginUserType'=>'google');
//echo "<pre>";print_r($google_login_details);die;
//echo "redirect to registration page";
$social_login_name = $user_name;
$this->session->set_userdata($google_login_details);
$firstname = $user_name;
$lastname = $last_name;
$orgPass = time();
$pwd = md5($orgPass);
$Confirmpwd = $orgPass;
$username = $user_name;
$condition = array ('email' => $email);
$duplicateMail = $this->user_model->get_all_details ( USERS, $condition );
$expireddate = date ( 'Y-m-d', strtotime ( '+15 days' ) );
$dataArr = array('firstname'=>$firstname,'lastname'=>$lastname,'user_name'=>$firstname,'group'=>'User','image'=>$profile_image_url,'email'=>$email,'password'=>$pwd,'status'=>'Active','expired_date'=>$expireddate,'is_verified'=>'No','loginUserType'=>'linkedin','google'=>'Yes','created'=>date('Y-m-d H:i:s'));
$this->user_model->simple_insert(USERS,$dataArr);
$lstID = $this->db->insert_id();
//echo $this->db->last_query(); die;
$userdata = array (
'quick_user_name' => $firstname,
'quick_user_email' => $email,
'fc_session_user_id' => $lstID,
'session_user_email' => $email
);
$this->session->set_userdata ( $userdata );
$this->setErrorMessage('success','Registered & Login Successfully');
redirect(base_url());
}
}
else
{
redirect('');
}
}else {
header("Location:https://www.linkedin.com/uas/oauth2/authorization?response_type=code&client_id=$client_id&redirect_uri=$redirect_uri&state=987654321&scope=r_basicprofile%20r_emailaddress%20w_share");
}
}
public function loginAccessToken() {
$params = array(
'grant_type' => 'authorization_code',
'client_id' => $this->config->item('linkedin_app_id'),
'client_secret' => $this->config->item('linkedin_app_key'),
'code' => $_GET['code'],
'redirect_uri' => base_url().'linkedinLogin'
);
// 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('https' =>
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 login_fetch($method, $resource, $body = '') {
$opts = array(
'https' => array(
'method' => $method,
'header' => "Authorization: Bearer " .
$_SESSION['access_token'] . "\r\n" .
"x-li-format: json\r\n"
)
);
$url = 'https://api.linkedin.com' . $resource;
// if (count($params)) {
// $url .= '?' . http_build_query($params);
// }
$context = stream_context_create($opts);
$response = file_get_contents($url, false, $context);
return json_decode($response);
}
Here look the login() fuction. I print the user details. But i got empty window only
echo "<pre>";print_r($user); die;
But when i use http, i got the user details. Can help me anyone?

How do I update a track’s streamable property via the API?

Using the SoundCloud PHP wrapper, I can successfully update a song’s title, privacy, genre, tags. But I can't figure out what I'm doing wrong with regard to the streamable property. When I send a true value to track[streamable], it remains false.
Here’s what I’m working with:
<?php
require_once 'Soundcloud.php';
require './globaldatabase.php';
$access_token = $_POST['access_token'];
$trackid = $_POST['trackid'];
$title = $_POST['title'];
$genre = $_POST['genre'];
$tag_list = $_POST['tag_list'];
$privacy = $_POST['privacy'];
$release = $_POST['release'];
$streamable = true;
if($privacy=='disabled'){
$streamable = false;
$privacy = 'private';
}
$client = new Services_Soundcloud($sc_clientid, $sc_clientsecret);
$client->setAccessToken($access_token);
try {
$track = json_decode($client->get('tracks/'.$trackid));
$client->put('tracks/' . $track->id, array(
'track[title]' => $title,
'track[genre]' => $genre,
'track[tag_list]' => $tag_list,
'track[sharing]' => $privacy,
'track[release]' => $release,
'track[streamable]' => $streamable
));
$return = $client->get('tracks/' . $track->id);
$return_array[] = json_decode($return);
echo json_encode($return_array);
} catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
exit($e->getMessage());
}
?>
Try setting the track attribute api_streamable to true.

Twitter access token request returns "Invalid or expired token"

I am using custom code to connect to Twitter and request an access token. For some reason when trying to post to "access_token" on the API it returns "invalid or expired token". The code is as follows (apart from a few external function calls and properties this should be sufficient to replicate the error):
public function authenticate($get,$return = false) {
session_start();
if (!isset($get['oauth_verifier'])){
// Step 1 - get a request token
$step1 = $this->processRequest('oauth/request_token',0,$this->pObj->getRedirectUrl().'?process=true');
parse_str($step1,$parts);
if ($parts['oauth_callback_confirmed'] !== 'true'){ die('Error with process'); }
$_SESSION['tw_secret'] = $parts['oauth_token_secret'];
// Step 2
$url = str_replace('1.1/','',$this->api_url);
header("Location: {$url}oauth/authenticate?oauth_token={$parts['oauth_token']}");
} else {
// Step 3
$this->o_token = $get['oauth_token'];
$this->o_secret = $_SESSION['tw_secret'];
$content['oauth_verifier'] = $get['oauth_verifier'];
$step3 = $this->processRequest('oauth/access_token',1,null,$content,'array');
}
}
// https://dev.twitter.com/docs/auth/creating-signature
private function generateSignature($oauth,$fullurl,$http_method,$content){
// Take params from url
$main_url = explode('?',$fullurl);
// Split the content
$contents = explode('&',$content);
$urls = array_merge(explode('&',$main_url[1]),$contents);
foreach ($urls as $param){
$bits = explode('=',$param);
if (strlen($bits[0])){
$oauth[$bits[0]] = rawurlencode($bits[1]);
}
}
ksort($oauth);
$string = http_build_query($oauth);
$new_string = strtoupper($http_method).'&'.urlencode($main_url[0]).'&'.urlencode(urldecode($string));
// The request_token request doesn't need a o_secret because it doesn't have one!
$sign_key = strstr($fullurl,'request_token') ? $this->c_secret.'&' : $this->c_secret.'&'.$this->o_secret;
return urlencode(base64_encode(hash_hmac('sha1',$new_string,$sign_key,true)));
}
public function processRequest($in_url,$test = false,$callback = null,$content = null, $content_type = 'json',$form_content_type = 'application/x-www-form-urlencoded'){
$method = 'GET';
// Twitter still uses Oauth1 (which is a pain)
$oauth = array(
'oauth_consumer_key'=>$this->c_key,
'oauth_nonce'=>$this->random(32),
'oauth_signature_method'=>'HMAC-SHA1',
'oauth_timestamp'=>time(),
'oauth_token'=>$this->o_token,
'oauth_version'=>'1.0'
);
$url = $this->api_url.$in_url;
if (strlen($callback)){
$oauth['oauth_callback'] = urlencode(urldecode($callback));
unset($oauth['oauth_token']);
$method = 'POST';
$url = str_replace('1.1/','',$url);
}
if (is_array($content) || strlen($content)){ $method = 'POST'; }
$oauth['oauth_signature'] = $this->generateSignature($oauth,$url,$method,'');
ksort($oauth);
foreach ($oauth as $k=>$v){
$auths[] = $k.'="'.$v.'"';
}
$stream = array('http' =>
array(
'method' => $method,
'ignore_errors'=>true, // http://php.net/manual/en/context.http.php - otherwise browser returns error not error content
'follow_location'=>false,
'max_redirects'=>0,
'header'=> array(
'Content-type: '.$form_content_type,
'Authorization: OAuth '.implode(', ',$auths),
'Connection: close'
)
)
);
if (is_array($content)){
$content = $content_type == 'json' ? json_encode($content) : http_build_query($content);
/* foreach ($content as $k=>$v){
$strs[] = "$k=".urlencode(urldecode($v));
}
// Just for now to keep things simple
$content = 'status=Hello%20Ladies%20%2b%20Gentlemen%2c%20a%20signed%20OAuth%20request%21';*/
}
if (!is_null($content)){
$stream['http']['content'] = $content;
}
// Tell streams to make a request
// Invalid key or 401 error tends to suggest an incorrect signing key / signature
$response = file_get_contents($url, false, stream_context_create($stream));
if ($test){
print'<pre>';print_r($oauth);print'</pre>';
print'<pre>';print_r($stream);print'</pre>';
//echo $callback.'<br>';
echo $url.'<br>';
//print'<pre>';print_r($http_response_header);print'</pre>';
print'<pre>[';print_r($response);print']</pre>';
}
if (!is_object(json_decode($response))){
// Content supplied is not json - just return it
return $response;
} else {
$response = json_decode($response);
}
return $this->pObj->convertObjectToArray($response);
}
The reason for the problems are:
1) The version of the Twitter API should not be included
2) The post is missing the Oauth_verifier in the signature
Thanks to twitteroauth for providing some guiding light.

Facebook api PHP: Posting to another users page feed not working

I have been trying to post a message and image on a page feed. I keep getting the error message
(#1) An error occured while creating the share.
This only happens if someone else tries to post. If I, the owner of the page tries to post it is successful.
So my question is: Is it possible to post to another users page feed?
I have done a lot of research into this but I cant seem to find a plausible solution.
Here is the code I am using to post the message:
<?php
class Photo_contest_helper extends Facebook
{
private $_key = '***********';
private $_secret = '***************';
private $_page_id = '387228561388254';
public $fb_login_url;
public $fb_logout_url;
public $image_id;
public function init()
{
$this->connect();
$image_id = $this->save_image();
if( !!$image_id ) {
$this->image_id = $image_id;
$this->push_to_facebook( $image_id );
}
}
public function save_image()
{
$image_id = NULL;
if ( !!$_POST[ "image" ] || !!$_FILES ) {
$image_id = Image_helper::save_one( $_POST[ "image" ] );
}
return $image_id;
}
public function push_to_facebook( $image_id )
{
$access_token = $this->get_page_access_token();
$this->publish_photo( $access_token );
}
public function connect()
{
parent::__Construct( array( 'appId' => $this->_key, 'secret' => $this->_secret ) );
$user = $this->getUser();
if( !$user ) {
$this->fb_login_url = $this->getLoginUrl( array( 'scope' => 'manage_pages,publish_actions,publish_stream,status_update' ) );
}
else {
$this->fb_logout_url = $this->getLogoutUrl( array( 'next' => 'http://stormtest.co.uk/' . DIRECTORY . "home/logout" ) );
}
}
public function get_page_access_token()
{
$accounts = $this->api( '/me/accounts', 'get' );
$access_token = NULL;
foreach ( $accounts[ 'data' ] as $account ) {
if ( $account[ 'id' ] == $this->_page_id ) {
$access_token = $account[ 'access_token' ];
}
}
return $access_token;
}
public function publish_photo( $access_token = "" )
{
$params = array( 'message' => 'Competition entry',
'link' => 'http://stormtest.co.uk/' . DIRECTORY . '_admin/assets/uploads/images/' . $this->get_image(),
'caption' => 'This is my competition entry',
'picture' => 'http://stormtest.co.uk/' . DIRECTORY . '_admin/assets/uploads/images/' . $this->get_image() );
if( !!$access_token ) {
$params[ 'access_token' ] = $access_token;
}
try {
$this->api( '/' . $this->_page_id . '/feed', 'post', $params );
}
catch( FacebookApiException $e ) {
die( print_r( $e ) );
}
}
public function get_image()
{
$image_model = new Image_model();
$image_model->find( $this->image_id );
return $image_model->attributes[ 'imgname' ];
}
}
?>
Thanks in advance.
You should use the JavaScript SDK to share content to the page. Posting to others' walls via the API has been disabled:
FB.ui( {
method: 'feed',
to: '387228561388254',
name: "Facebook API: Tracking Shares using the JavaScript SDK",
link: "https://www.webniraj.com/2013/05/11/facebook-api-tracking-shares-using-the-javascript-sdk/",
picture: "https://stackexchange.com/users/flair/557969.png",
caption: "Tracking Facebook Shares on your website or application is a useful way of seeing how popular your articles are with your readers. In order to tracking Shares, you must used the Facebook JavaScript SDK."
}, callback );
Use the to field in the above code to set the page_id, and change the other attributes accordingly (but don't change method).

Categories