How have logged in user's email using oauth in PHP - php

I used yahoo oauth in my website. In code below that I found on github, for example $user -> query -> results -> profile -> givenName returns the first name of logged in user, $user -> query -> results -> profile -> familyName and so on.
I searched a lot but still I don't know how to get user's email address.
This is my code :
require('include/http.php');
require('include/oauth_client.php');
$client = new oauth_client_class;
$client->debug = false;
$client->debug_http = true;
$client->server = 'Yahoo';
$client->redirect_uri = 'http://www.example.com';
$client->client_id = '';
$application_line = __LINE__;
$client->client_secret = '';
if(($success = $client->Initialize()))
{
if(($success = $client->Process()))
{
if(strlen($client->access_token))
{
$success = $client->CallAPI(
'https://query.yahooapis.com/v1/yql',
'GET', array(
'q'=>'select * from social.profile where guid=me',
'format'=>'json'
), array('FailOnAccessError'=>true), $user);
}
}
$success = $client->Finalize($success);
}
if($client->exit)
exit;
if(strlen($client->authorization_error))
{
$client->error = $client->authorization_error;
$success = false;
}
if($success)
{
$yahname =$user->query->results->profile->givenName.$user->query->results->profile->familyName;
echo '<pre>', HtmlSpecialChars(print_r($user, 1)), '</pre>';
}
else
{
echo HtmlSpecialChars($client->error);
}
Please let me know if I am doing anything wrong.

I do not believe that the profile contains the users email address (it is not listed in the Yahoo profile docs). If you have requested the sdpp-w scope the the id token you get when exchanging an authorization code for an access token contains the email address of the user under the key email.

Related

How to set sendAsEmail via Google's Gmail api

I'm updating a PHP application to create new email accounts in Google (using the Google Directory Service). I have no problem creating the account, but so far I've been unable to use the Google Gmail Service to set the sendAsEmail attribute (so that the alias will show up in the "From"). Also, var_dump($createSendAsResult) in the snippet below does not produce any output. Any help would be appreciated. Thanks!
Here's my code:
//Create account in Google
function createGoogleAccount($server_name, $acc_user, $acc_password)
{
$clientDir = getClientDir($server_name);
$dirService = new Google_Service_Directory($clientDir);
$userInstance = new Google_Service_Directory_User();
$nameInstance = new Google_Service_Directory_UserName();
$nameInstance -> setGivenName('Generic');
$nameInstance -> setFamilyName($acc_user);
$userInstance -> setOrgUnitPath("/generic_email");
$userInstance -> setName($nameInstance);
$userInstance -> setHashFunction("MD5");
$domain = getDomain($server_name);
$primary_email = $acc_user . '#' . $domain;
$userInstance -> setPrimaryEmail($primary_email);
$userInstance -> setPassword(hash("md5", $acc_password));
$optParams = array( );
$error_msg = null;
try
{
$createUserResult = $dirService->users->insert($userInstance, $optParams);
var_dump($createUserResult);
}
catch (Google_IO_Exception $gioe)
{
$error_msg = "Error in connection: ".$gioe->getMessage();
}
catch (Google_Service_Exception $gse)
{
$error_msg = "Service Exception: ".$gse->getMessage();
}
addSendAs($server_name, $acc_user, $domain); return $error_msg;
}
function addSendAs($server_name, $acc_user, $domain)
{
$clientGmail = getClientGmail($server_name);
$gmailService = new Google_Service_Gmail($clientGmail);
$primary_email = $acc_user . '#' . $domain;
$sendAsEmail = new Google_Service_Gmail_SendAs();
$alias = '';
if (($server_name == null) || (strpos($server_name, "dev") != false))
{
$alias = '#g.';
}
else
{
$alias = '#mail.';
}
$sendAsEmail -> setSendAsEmail($acc_user . $alias . $domain);
$sendAsEmail -> setIsDefault(TRUE);
$sendAsEmail -> setIsPrimary(TRUE);
$error_msg = null;
try
{
$createSendAsResult = $gmailService->users_settings_sendAs -> create($primary_email, $sendAsEmail);
var_dump($createSendAsResult);
}
catch (Google_IO_Exception $gioe)
{
$error_msg = "Error in connection: ".$gioe->getMessage();
}
catch (Google_Service_Exception $gse)
{
$error_msg = "Service Exception: ".$gse->getMessage();
}
}
Finally, after much experimentation with the code and some help from a couple of colleagues, I figured out what the problem is and how to solve it.
Apparently, Google needs time to set up a new user's account with email. When I added a 10-second delay - sleep(10) in php - that was sufficient for the account to be ready for calls to the Gmail API, including the creation of a SendAs alias.

Authentication failed. Either supplied credentials are invalid or the account is inactive

I'm trying to authenticate on Bing Ads Api but I'm getting this message:
Authentication failed. Either supplied credentials are invalid or the account is inactive
This is my code:
$UserName = "xxx#hotmail.com";
$Password = "xxx";
$DeveloperToken = "xxx";
$CustomerId = xxx;
$AccountId = xxx;
$wsdl = "https://campaign.api.bingads.microsoft.com/Api/Advertiser/CampaignManagement/V10/CampaignManagementService.svc?singleWsdl";
try
{
$proxy = ClientProxy::ConstructWithAccountAndCustomerId($wsdl, $UserName, $Password, $DeveloperToken, $AccountId, $CustomerId, null);
// Specify one or more campaigns.
$campaigns = array();
$campaign = new Campaign();
$campaign->Name = "Winter Clothing " . $_SERVER['REQUEST_TIME'];
$campaign->Description = "Winter clothing line.";
$campaign->BudgetType = BudgetLimitType::MonthlyBudgetSpendUntilDepleted;
$campaign->MonthlyBudget = 1000.00;
$campaign->TimeZone = "PacificTimeUSCanadaTijuana";
$campaign->DaylightSaving = true;
// Used with FinalUrls shown in the ads that we will add below.
$campaign->TrackingUrlTemplate =
"http://tracker.example.com/?season={_season}&promocode={_promocode}&u={lpurl}";
$campaigns[] = $campaign;
// Add the campaign, ad group, keywords, and ads
$campaignIds = AddCampaigns($proxy, $AccountId, $campaigns);
PrintCampaignIdentifiers($campaignIds);
}
catch (SoapFault $e)
{
// Output the last request/response.
print "\nLast SOAP request/response:\n";
print $proxy->GetWsdl() . "\n";
print $proxy->GetService()->__getLastRequest()."\n";
print $proxy->GetService()->__getLastResponse()."\n";
// Campaign Management service operations can throw AdApiFaultDetail.
if (isset($e->detail->AdApiFaultDetail))
{
// Log this fault.
print "The operation failed with the following faults:\n";
$errors = is_array($e->detail->AdApiFaultDetail->Errors->AdApiError)
? $e->detail->AdApiFaultDetail->Errors->AdApiError
: array('AdApiError' => $e->detail->AdApiFaultDetail->Errors->AdApiError);
// If the AdApiError array is not null, the following are examples of error codes that may be found.
foreach ($errors as $error)
{
print "AdApiError\n";
printf("Code: %d\nError Code: %s\nMessage: %s\n", $error->Code, $error->ErrorCode, $error->Message);
switch ($error->Code)
{
case 105: // InvalidCredentials
break;
case 117: // CallRateExceeded
break;
default:
print "Please see MSDN documentation for more details about the error code output above.\n";
break;
}
}
Sorry for the delayed reply. I noticed that you are setting the UserName to ***#hotmail.com. If you are using an email address login i.e. Microsoft account, then you must use OAuth i.e. set the AuthenticationToken header element instead of setting the UserName/Password fields.

Twitter OAuth Error 220

I have an application that Authenticates a user using OAuth and gets all of the permissions needed to post an update for a twitter user but when i try to actually do the post I get this response:
stdClass Object ( [errors] => Array ( [0] => stdClass Object ( [code] => 220 [message] => Your credentials do not allow access to this resource. ) ) )
here is my code for the authentication when they first link twitter:
// The TwitterOAuth instance
$twitteroauth = new TwitterOAuth(TWITTER_KEY, TWITTER_SECRET);
// Requesting authentication tokens, the parameter is the URL we will be redirected to
$request_token = $twitteroauth->getRequestToken(TWITTER_CALLBACK_URL);
// Saving them into the session
$_SESSION['twitter_oauth_token'] = $request_token['oauth_token'];
$_SESSION['twitter_oauth_token_secret'] = $request_token['oauth_token_secret'];
// If everything goes well..
if($twitteroauth->http_code==200){
// Let's generate the URL and redirect
$url = $twitteroauth->getAuthorizeURL($request_token['oauth_token']);
header('Location: '. $url);
} else {
// Remember to adds script for error handling and reporting but for now kill the script
die('Something wrong happened.');
}
And here is what happend when they get to the callback:
if(!empty($_GET['oauth_verifier']) && !empty($_SESSION['twitter_oauth_token']) && !empty($_SESSION['twitter_oauth_token_secret'])){
// TwitterOAuth instance, with two new parameters we got in twitter_login.php
$twitteroauth = new TwitterOAuth(TWITTER_KEY, TWITTER_SECRET, $_SESSION['twitter_oauth_token'], $_SESSION['twitter_oauth_token_secret']);
// Let's request the access token
$access_token = $twitteroauth->getAccessToken($_GET['oauth_verifier']);
// Save it in a session var
$_SESSION['access_token'] = $access_token;
// Let's get the user's info
$user_info = $twitteroauth->get('account/verify_credentials');
if(isset($user_info->error)){
// Something's wrong, go back to square 1
header('Location: networks.php?connect=2');
} else {
// Let's find the user by its ID
$query = mysql_query("SELECT * FROM connected_accounts WHERE oauth_provider = 'twitter' AND oauth_uid = ". $user_info->id);
$result = mysql_fetch_array($query);
// If not, let's add it to the database
if(empty($result)){
$query = mysql_query("INSERT INTO connected_accounts (user_id, account_id, oauth_provider, acct_usr_id, oauth_uid, username, token, secret) VALUES ('".${'User'}['id']."', '2', 'twitter', ".$user_info->id.", ".$user_info->id.", '".$user_info->screen_name."', '".$access_token['oauth_token']."', '".$access_token['oauth_token_secret']."')");
$query = mysql_query("SELECT * FROM connected_accounts WHERE id = " . mysql_insert_id());
$result = mysql_fetch_array($query);
} else {
// Update the tokens
$query = mysql_query("UPDATE connected_accounts SET token = '".$access_token['oauth_token']."', secret = '".$access_token['oauth_token_secret']."' WHERE oauth_provider = 'twitter' AND oauth_uid = ".$user_info->id);
}
$_SESSION['id'] = $result['id'];
$_SESSION['username'] = $result['username'];
$_SESSION['oauth_uid'] = $result['oauth_uid'];
$_SESSION['oauth_provider'] = $result['oauth_provider'];
$_SESSION['oauth_token'] = $result['token'];
$_SESSION['oauth_secret'] = $result['secret'];
header('Location: manage_accounts.php');
}
} else {
// Something's missing, go back to square 1
header('Location: networks.php?connect=2');
}
// Get our permenant token
$response = $twitter_client->getAccessToken($_GET['oauth_verifier']);
// If we did not receive a permenant token, notify the user
if (!$response['oauth_token']) {
$message = '<center><div class="error">An error occurred while linking your Twitter account. Please try again later.</div></center>';
// Otherwise
} else {
// Update our info
mysql_query('UPDATE `connected_accounts` SET `token` = "'.$response['oauth_token'].'", `acct_usr_id` = "'.$response['user_id'].'", `secret` = "'.$response['oauth_token_secret'].'" WHERE `account_id` = 2 AND `user_id` = '.${'User'}['id']) or die(mysql_error());
// Send the user to the post page
header('Location: manage_accounts.php'); exit;
}
I am using the Library from https://github.com/abraham/twitteroauth
Everything used to work just fine but now it isn't working.
It seems that it has something to do with application only authentication but I am using OAuth which is supposed to allow posting to statuses/update

Twitter OAuth returning blank array if there is no tweet

I spent my last 5 hours in this issue and finally I came here for the solution.
I am doing log-in using twitter functionality in my site (Zend Framework + PHP) and everything is working fine. But I am facing the following issue in it:
If the user has no tweets (0 tweets) in his account then the
$tweets = json_decode($response->getBody());
echo "<pre>";
print_r($tweets);
exit;
Its showing me blank array. i.e. : Array(); :-(
And if I am adding some tweets there in twitter account then its showing me the complete array along with user information like display name, image, etc...like this:
Array
(
//other data
[0] => stdClass Object
(
[user] => stdClass Object
....
....
so on..
)
)
Following is my code :
public function twitterregisterAction() {
$path = realpath(APPLICATION_PATH . '/../library/');
set_include_path($path);
session_start();
require $path . "/Zend/Oauth/Consumer.php";
$config = array(
"callbackUrl" => "http://" . $_SERVER['HTTP_HOST'] . "/register/twittercallback",
"siteUrl" => "http://twitter.com/oauth",
"consumerKey" => "xxxxxxxxxxxxx",
"consumerSecret" => "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
);
$consumer = new Zend_Oauth_Consumer($config);
// fetch a request token
$token = $consumer->getRequestToken();
// persist the token to storage
$_SESSION["TWITTER_REQUEST_TOKEN"] = serialize($token);
// redirect the user
$consumer->redirect();
}
/*
* Ticket id #16
* twittercallbackAction method
*/
public function twittercallbackAction() {
$config = array(
"callbackUrl" => "http://" . $_SERVER['HTTP_HOST'] . "/register/twittercallback",
"siteUrl" => "http://twitter.com/oauth",
"consumerKey" => "xxxxxxxxxxxxxxxxxx",
"consumerSecret" => "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
);
$consumer = new Zend_Oauth_Consumer($config);
if (!$this->_getParam("denied")) {
if (!empty($_GET) && isset($_SESSION['TWITTER_REQUEST_TOKEN'])) {
$token = $consumer->getAccessToken($_GET, unserialize($_SESSION['TWITTER_REQUEST_TOKEN']));
} else {
// Mistaken request? Some malfeasant trying something?
exit('Invalid callback request. Oops. Sorry.');
}
// save token to file
// file_put_contents('token.txt', serialize($token));
$client = $token->getHttpClient($config);
$client->setUri('https://api.twitter.com/1/statuses/user_timeline.json?');
$client->setMethod(Zend_Http_Client::GET);
$client->setParameterGet('name');
$client->setParameterGet('profile_image_url');
$response = $client->request();
$tweets = json_decode($response->getBody());
$session = new Zend_Session_Namespace("userIdentity");
Zend_Session::rememberMe(63072000); //2years
$session->tw_id = $tweets[0]->user->id;
$session->tw_name = $tweets[0]->user->name;
$session->tw_image = $tweets[0]->user->profile_image_url;
if ($session->tw_id != "") {
$tw_id = $session->tw_id;
//Calling the function twitterAuthAction for email authentication
$twAuthArr = $this->twitterAuthAction($tw_id);
if ($twAuthArr['socialId'] == $tw_id) {
$session->userId = $twAuthArr['id'];
$session->email = $twAuthArr['emailId'];
$this->_redirect('/profile/showprofile');
} else {
$user = new UserRegistration();
$firstname = "";
$lastname = "";
$password = "";
$socialtype = "twitter";
$email = "";
$socialid = $session->tw_id;
$result = $user->registerUser($firstname, $lastname, $socialid, $socialtype, $email, $password);
$session->userId = $result;
$this->_redirect('/register');
}
}
$this->_redirect("/register");
} else {
$this->_redirect("/register");
}
}
My Questions are :
1) Why its not providing user array if there is no any tweet in my twitter account (or newly created twitter account)
2) I want user profile details from twitter account. How can I get it?
Need Help. Thanks
I think as per david's answer you need to use users/show url there instead of using statuses/user_timeline. You can use curl for requesting url so you'll get the response which contains the users information.
Try with following code:
$user_id = $client->getToken()->getParam('user_id');
$trends_url = "http://api.twitter.com/1/users/show.json?user_id=".$user_id;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $trends_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$curlout = curl_exec($ch);
curl_close($ch);
$response = json_decode($curlout, true);
$session = new Zend_Session_Namespace("userIdentity");
Zend_Session::rememberMe(63072000); //2years
$session->tw_id = $response['id'];
$session->tw_name = $response['name'];
$session->tw_image = $response['profile_image_url'];
Try this. Hope it will help you.
I think you are misreading the Twitter API docs for the statuses/user_timeline endpoint.
The field user that you identify is one of the fields within a returned tweet. If the user id to which you point has no tweets, then there will be no entries in the returned array, hence no user field.
If you need the user information even in the absence of any tweets, then you probably need to hit the users/show endpoint.

joomla 1.7 user registration customization issue

-> i am trying for new user registration customization.
-> for that i create form and hidden variable through call function from controller.
-> in controller save function i write this code but some inner function which not work in 1.7 so create problem here.
function register_save()
{
global $mainframe;
$db =& JFactory::getDBO();
// Check for request forgeries
JRequest::checkToken() or jexit( 'Invalid Token' );
//clean request
$post = JRequest::get( 'post' );
$post['username'] = JRequest::getVar('username', '', 'post', 'username');
$post['password'] = JRequest::getVar('password', '', 'post', 'string', JREQUEST_ALLOWRAW);
$post['password2'] = JRequest::getVar('password2', '', 'post', 'string', JREQUEST_ALLOWRAW);
// get the redirect
$return = JURI::base();
// do a password safety check
if(strlen($post['password']) || strlen($post['password2'])) { // so that "0" can be used as password e.g.
if($post['password'] != $post['password2']) {
$msg = JText::_('PASSWORD NOT MATCH');
// something is wrong. we are redirecting back to edit form.
// TODO: HTTP_REFERER should be replaced with a base64 encoded form field in a later release
$return = str_replace(array('"', '<', '>', "'"), '', #$_SERVER['HTTP_REFERER']);
if (empty($return) || !JURI::isInternal($return)) {
$return = JURI::base();
}
$this->setRedirect($return, $msg, 'error');
return false;
}
}
// Get required system objects
$user = clone(JFactory::getUser());
$pathway = JFactory::getApplication();
//$pathway =& $mainframe->getPathway();
$config =& JFactory::getConfig();
//print_r($config)."<br>";
$authorize =& JFactory::getACL();
//print_r($authorize)."<br>"; /// some mistake here
$newUsertype = 'Registered';
// Bind the post array to the user object
if (!$user->bind( JRequest::get('post'), 'usertype' )) {
JError::raiseError( 500, $user->getError());
}
// Set some initial user values
$user->set('id', 0);
$user->set('usertype', $newUsertype);
$user->set('gid', $authorize->get_group_id( '', $newUsertype, 'ARO' ));
$date =& JFactory::getDate();
$user->set('registerDate', $date->toMySQL());
// If user activation is turned on, we need to set the activation information
jimport('joomla.user.helper');
$user->set('activation', JUtility::getHash( JUserHelper::genRandomPassword()) );
$user->set('block', '1');
// If there was an error with registration, set the message and display form
if ( !$user->save() )
{
JError::raiseWarning('', JText::_( $user->getError()));
$this->register();
return false;
}
$obj1 = new stdClass();
$obj1->userid = $user->id;
$obj1->points = 0;
$obj1->posted_on = $date->toMySQL();
$obj1->avatar = '';
$obj1->thumb = '';
$obj1->params = 'notifyEmailSystem=1
privacyProfileView=0
privacyPhotoView=0
privacyFriendsView=0
privacyVideoView=1
notifyEmailMessage=1
notifyEmailApps=1
notifyWallComment=0';
$db->insertObject('#__community_users', $obj1, 'userid');
$extra_field = array(1=>2,2=>3,3=>4,4=>6,5=>7,6=>8,7=>9,8=>10,9=>11,10=>12,11=>14,12=>15,13=>16);
$i = 1;
$obj2 = new stdClass();
while($extra_field[$i] != "")
{
$obj2->id = '';
$obj2->user_id = $user->id;
$obj2->field_id = $extra_field[$i];
$obj2->value = '';
$db->insertObject('#__community_fields_values', $obj2, 'id');
$i++;
}
////////// end of joomsocial customisation///////////////////////////
// Send registration confirmation mail
$password = JRequest::getString('password', '', 'post', JREQUEST_ALLOWRAW);
$password = preg_replace('/[\x00-\x1F\x7F]/', '', $password); //Disallow control chars in the email
UserControllerRegister::_sendMail($user, $password);
// Everything went fine, set relevant message depending upon user activation state and display message
$message = JText::_( 'Your account has been created and an activation link has been sent to the e-mail address you entered. Note that you must activate the account by clicking on the activation link when you get the e-mail before you can login.' );
$this->setRedirect('index.php', $message);
}
not insert record in table.
please help me.
I think you're right:
Joomla 1.5 ACL (Access Control Lists) is hierarchical: each user group inherits permissions from the groups below it.
In Joomla 1.7 ACL is not necessarily hierarchical. You can setup groups with whatever permissions you wish.
The difference between the ACL in Joomla 1.5 and 1.7 is not only in the behavior - but also in the implementation! which means that the authentication/registration mechanism will be implemented in different ways:
http://www.youtube.com/watch?v=ZArgffnPUo4

Categories