paypalrecurring.php
private $test = false;
private $liveServer = 'https://api-3t.paypal.com/nvp'; # https://api.paypal.com/nvp
private $testServer = 'https://api-3t.sandbox.paypal.com/nvp'; # https://api.sandbox.paypal.com/nvp
private $methodName = 'CreateRecurringPaymentsProfile';
public function sendRequest()
{
$nvpreq = '';
foreach ($this->request as $fldname => $val)
if($val != '') $nvpreq .= strtoupper($fldname) . "=" . urlencode($val) . "&";
$url = ($this->test) ? $this->testServer : $this->liveServer;
$post = "METHOD=" . $this->methodName . "&" . $nvpreq . "&VERSION=56.0";
$retstr = $this->sendAPIRequest($url . "?" . $post);
$retarrtmp = explode("&",$retstr);
$retarr = array();
for($i=0;$i<count($retarrtmp);$i++)
{
$sparr = explode("=",$retarrtmp[$i]);
$txt = urldecode($sparr[0]);
$val = urldecode($sparr[1]);
$retarr[$txt] = $val;
}
return $retarr;
}
/**
* True for test server. False for production.
* #param bool $isTest
*/
public function setIsTest($isTest)
{
$this->test = $isTest;
}
private function sendAPIRequest($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
if(curl_errno($ch))
$response = curl_error($ch);
curl_close($ch);
return $response;
}
}
Usageexample.php
<?php
require_once 'PaypalRecurring.php';
$pp = new PayPalRecurring();
$pp->setIsTest(true); // PayPal test sandbox or live server
// Your PayPal account credentials go here
$pp->request['user'] = 'xxx';
$pp->request['pwd'] = 'xxx';
$pp->request['signature'] = 'xxx';
// End PayPal account credentials
// User info
$pp->request['firstname'] = 'The users first name';
$pp->request['lastname'] = 'The users last name';
$pp->request['email'] = 'The users email address';
$pp->request['creditcardtype'] = 'Visa'; // Visa, Mastercard, Discover, Amex
$pp->request['acct'] = ''; // Credit card number
$pp->request['expdate'] = str_pad('8',2,'0', STR_PAD_LEFT) .'2020'; // Expiration month and full year. Pad the month with 0. Month should be 1-12. This example is 8/2020.
// End user info
// Product info
$pp->request['countrycode'] = 'US';
$pp->request['billingperiod'] = 'Month'; // Bill per month
$pp->request['billingfrequency'] = 1; // How many times to bill per billing period.. This example is once per month
$pp->request['currencycode'] = 'USD';
$pp->request['amt'] = 9.95; // Amount to bill every month
$pp->request['initamt'] = 0.00; // Setup fee.. One time on account creation
$pp->request['taxamt'] = $pp->request['amt'] * .07; // Replace .07 with your tax percentage. 0 for no tax.
$pp->request['desc'] = 'Super Deluxe Package'; // The description of your product for reporting in your account
$pp->request['profilestartdate'] = gmdate('Y-m-d\TH:i:s\Z');
$pp->request['totalbillingcycles'] = '3'; // How many billing cycles. 0 for no expiration. This example is for 3 total months of billing.
$pp->request['payerstatus'] = 'verified';
// End product info
$ppResponse = $pp->sendRequest();
if(isset($ppResponse['L_ERRORCODE0']))
echo "Error: {$ppResponse['L_LONGMESSAGE0']}";
else if(isset($ppResponse['ACK']) && $ppResponse['ACK'] == ('Success' || 'SuccessWithWarning'))
echo "Success: {$ppResponse['ACK']}";
else
print_r($ppResponse);
whenever i am trying to implement recurring payment in paypal always got error
security header is not valid
Above example is from github
i need to integrate recurring payment in ecommerce site
I have two files paypalrecurring.php & usageExample.php
When i executed usageExample.php i got error security header is not valid
can anybody help me
This is because your API credentials in below codes is not correct.
$pp->request['user'] = 'xxx';
$pp->request['pwd'] = 'xxx';
$pp->request['signature'] = 'xxx';
You can follow up the steps below to find your API credentials:
For sandbox account:
Access https://developer.paypal.com/ and login, then access below URL:
https://developer.paypal.com/developer/accounts
Click the business account being used for your test, then click the "Profile" link under the account.
Then click the "API Credentials" tab, you will find the API credentials.
For live account:
Login to www.paypal.com, go to Profile->Selling tools->API Access, click "Request API credentials" link,
then select "Request API signature" and click "Agree and Submit".
Then you can find your API username, API password and API signature in the final page.
Related
I have a little problem, I have a php script for sending messages to viber. The problem is that bot sends message when I send some message with my profile, but I want only to run php script and send message to chat.
Check the script:
<?php
use Alserom\Viber\Request\Type\SendMessage;
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$access_token = "TOKEN HERE";
$request = file_get_contents("php://input");
$input = json_decode($request, true);
if ($input['event'] == 'webhook') {
$webhook_response['status'] = 0;
$webhook_response['status_message'] = "ok";
$webhook_response['event_tyes'] = "delivered";
echo json_encode($webhook_response);
die;
} else if ($input['event'] == 'message') {
$text_received = $input['message']['text'];
$sender_id = $input['sender']['id'];
$sender_name = $input['sender']['name'];
$message_to_replay = "hello";
$data['auth_token'] = $access_token;
$data['receiver'] = $sender_id;
$data['type'] = "text";
$data['text'] = $message_to_replay;
sendMessage($data);
} else {
$message_to_replay = "Messageeeeeee";
$data['auth_token'] = $access_token;
/* $data['receiver'] = $sender_id; */
$data['type'] = "text";
$data['text'] = $message_to_replay;
sendMessage($data);
}
function sendMessage($data) {
$url = "https://chatapi.viber.com/pa/send_message";
$jsonData = json_encode($data);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$result = curl_exec($ch);
return $result;
}
?>
When I run script through browser, it goes to ELSE and it should send message immediately... but I get this error:
{
"status": 999,
"status_message": "Bad receiver ID",
"message_token": 5485177081717755848,
"chat_hostname": "SN-CHAT-20_"
}
Should I put some static receiver ID? And how to get ID of some user?
*** UPDATE *****
I have added static ID of subscribed user in ELSE statement... now it sends immediately when I run script, but now it sends 100 same messages. How to limit sending only one message?
else {
$message_to_replay = "Messageeeeeee";
$data['auth_token'] = $access_token;
$data['receiver'] = "staticID";
$data['type'] = "text";
$data['text'] = $message_to_replay;
sendMessage($data);
}
According to the Viber documentation, you can only send messages to accounts subscribing to your bot:
The send_message API allows accounts to send messages to Viber users who subscribe to the account.
A requirement for the user id is, that it has to be a user id of a user who subscribed to the bot, so this should be your first step to check.
Edit: I would recommend saving the user ids of those who subscribed by sending an initial message or something to your bot and then you can send messages to them by taking the previously saved user ids.
If your script didn't responded in 5 seconds or responded with HTML status code not equal 200 - then Viber servers will try to resend this webhook every minute.
I'm a EC manager. PayPal payment in production works without problems, but there is a problem in development (sandbox environment).
As mentioned in the title, DoExpressCheckout API via PHP always returns 10422 or 10486 error codes when only paying by a credit card. This means it works correctly when sandbox account's PayPal balance is enough to pay for an item.
I suspect there are problems in my sandbox account setting or my php code.
Is there anyone have clues to a solution to this problem?
My PHP code here.
<?php
/** DoExpressCheckoutPayment NVP example; last modified 08MAY23.
*
* Complete an Express Checkout transaction.
*/
require_once('paypal_configure.php'); // API settings
// Set request-specific fields.
$environment = ENVIRONMENT; // sandbox
$paymentType = urlencode("Authorization"); // or 'Sale' or 'Order'
$currencyID = urlencode(CURRENCY);
// Set parameter
$token = urlencode($argv[1]);
$payerID = urlencode($argv[2]);
$paymentAmount = urlencode($argv[3]);
$invNum = urlencode($argv[4]);
/**
* Send HTTP POST Request
*
* #param string The API method name
* #param string The POST Message fields in &name=value pair format
* #return array Parsed HTTP Response body
*/
function PPHttpPost($methodName_, $nvpStr_) {
global $environment;
// Set up your API credentials, PayPal end point, and API version.
$API_UserName = urlencode(API_USERNAME);
$API_Password = urlencode(API_PASSWORD);
$API_Signature = urlencode(API_SIGNATURE);
$API_Endpoint = "https://api-3t.paypal.com/nvp";
if("sandbox" === $environment || "beta-sandbox" === $environment) {
$API_Endpoint = "https://api-3t.$environment.paypal.com/nvp";
}
$version = urlencode('51.0');
// setting the curl parameters.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $API_Endpoint);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
// Set the curl parameters.
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
// Set the API operation, version, and API signature in the request.
$nvpreq = "METHOD=$methodName_&VERSION=$version&PWD=$API_Password&USER=$API_UserName&SIGNATURE=$API_Signature$nvpStr_";
// Set the request as a POST FIELD for curl.
curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);
// Get response from the server.
$httpResponse = curl_exec($ch);
if(!$httpResponse) {
exit('$methodName_ failed: '.curl_error($ch).'('.curl_errno($ch).')');
}
// Extract the response details.
$httpResponseAr = explode("&", $httpResponse);
$httpParsedResponseAr = array();
foreach ($httpResponseAr as $i => $value) {
$tmpAr = explode("=", $value);
if(sizeof($tmpAr) > 1) {
$httpParsedResponseAr[$tmpAr[0]] = $tmpAr[1];
}
}
if((0 == sizeof($httpParsedResponseAr)) || !array_key_exists('ACK', $httpParsedResponseAr)) {
exit("Invalid HTTP Response for POST request($nvpreq) to $API_Endpoint.");
}
return $httpParsedResponseAr;
}
/**
* This example assumes that a token was obtained from the SetExpressCheckout API call.
* This example also assumes that a payerID was obtained from the SetExpressCheckout API call
* or from the GetExpressCheckoutDetails API call.
*/
// Add request-specific fields to the request string.
$nvpStr = "&TOKEN=$token&PAYERID=$payerID&PAYMENTACTION=$paymentType&AMT=$paymentAmount&CURRENCYCODE=$currencyID";
$nvpStr .= "&INVNUM=$invNum";
// Execute the API operation; see the PPHttpPost function above.
$httpParsedResponseAr = PPHttpPost('DoExpressCheckoutPayment', $nvpStr);
// result
$resAck = strtoupper($httpParsedResponseAr["ACK"]);
$resTime = urldecode($httpParsedResponseAr["TIMESTAMP"]);
if( $resAck == "SUCCESS" || $resAck == "SUCCESSWITHWARNING" ) {
// get result
$resCode = "10000";
$resMsg = "_";
$resTranid = urldecode($httpParsedResponseAr["TRANSACTIONID"]);
$resAmount = urldecode($httpParsedResponseAr["AMT"]);
}
else {
// get result
$resCode = $httpParsedResponseAr["L_ERRORCODE0"];
$resMsg = mb_ereg_replace(" ","###SPACE###",urldecode($httpParsedResponseAr["L_LONGMESSAGE0"]));
$resTranid = "_";
$resAmount = "_";
}
// return text
$rtnText = "";
$rtnText = $resAck;
$rtnText .= " ".$resCode;
$rtnText .= " ".$resMsg;
$rtnText .= " ".$resTranid;
$rtnText .= " ".$resAmount;
$rtnText .= " ".$token;
$rtnText .= " ".$payerID;
$rtnText .= " ".$invNum;
$rtnText .= " ".$resTime;
$rtnText .= "\n";
echo $rtnText;
exit(0);
?>
Sometimes sandbox accounts get screwed up. Try creating a fresh sandbox buyer account and make sure to add a credit card to it during that process.
I've made a successful payments with Amazon Login and Pay Express (based on the demo here: https://github.com/amzn/pay-with-amazon-express-demo/tree/master/php).
However, when the user successfully makes a purchase they're redirected back to my site return success url with a bunch of params describing what they bought and a signature for the request provided by Amazon.
I've tried code given below to calculate the original signature for validation returned signature from Amazon but this code does not generate a matching signature to what Amazon is sending in the return url.
ExpressSuccess.php
<?php
echo ("<pre>");
print_r($_GET);
echo ("</pre>");
/* begin signature validation */
$merchantId = "************"; // SellerID
$accessKey = "*****************"; // MWS Access Key
$secretKey = "***********************"; // MWS Secret Key
$lwaClientId = "***********************"; // Login With Amazon Client ID
/* Add http:// or https:// before your Return URL
* The webpage of your site where the buyer should be redirected to after the payment is made
* In this example you can link it to the Result.php, which checks for the success or failure of the payment
* and routes it to the appropriate URL defined
*/
$returnURL = "http://localhost/demo/pay-with-amazon/ExpressSuccess.php";
$cancelReturnURL = "http://localhost/demo/pay-with-amazon/ExpressCancel.php";
$signatureReturned = $_GET['signature'];
$parameters = $_GET;
unset($parameters['signature']);
if(isset($parameters['sellerOrderId'])) {
$parameters['sellerOrderId'] = rawurlencode($parameters['sellerOrderId']);
}
uksort($parameters, 'strcmp');
$parseUrl = parse_url($returnURL);
$stringToSign = "GET\n" . $parseUrl['host'] . "\n" . $parseUrl['path'] . "\n";
foreach ($parameters as $key => $value) {
$queryParameters[] = $key . '=' . str_replace('%7E', '~', rawurlencode($value));
}
$stringToSign .= implode('&', $queryParameters);
$signatureCalculated = base64_encode(hash_hmac("sha256", $stringToSign, $secretKey, true));
$signatureCalculated = str_replace('%7E', '~', rawurlencode($signatureCalculated));
if ($signatureReturned == $signatureCalculated) {
echo "Signature was successfully validated.";
} else {
echo "Signature does not match.";
}
?>
If anybody has any idea where I'm doing wrong, please let me know.
Thanks !!
Ok, here is what I did:
Created a PayRequest
SetPaymentOptions - https://developer.paypal.com/webapps/developer/docs/classic/api/adaptive-payments/SetPaymentOptions_API_Operation/
ExecutePayment - "This payment request must be authorized by the sender". I have ran out of idea on why am I not able to execute the payment. From what I understand, once I execute the payment successfully, I will be given a payKey which I shall use this to redirect user to paypal. https://developer.paypal.com/webapps/developer/docs/classic/api/adaptive-payments/ExecutePayment_API_Operation/
Attached are the source codes that I used. The values are all hardcoded. I have tried my best to look through at similar questions, and it makes no sense to me as it contradicts what I understand. Some answers were pointing out that the buyer needs to approve the payment first before you executePayment.
I just want to see the details of all items when I reach the paypal login page.
//1. Obtain endpoint. For live, no need sandbox?
$endPoint = "https://svcs.sandbox.paypal.com/AdaptivePayments/Pay";
//2. Format the HTTP headers needed to make the call.
$appID = "xxx"; //Sandbox test AppID:
$username = "xxx;
$password = "xxx";
$signature = "xxx";
$paypalHeaders = array(
"X-PAYPAL-SECURITY-USERID :" . $username,
"X-PAYPAL-SECURITY-PASSWORD :" . $password,
"X-PAYPAL-SECURITY-SIGNATURE :" . $signature,
"X-PAYPAL-APPLICATION-ID :" . $appID,
"X-PAYPAL-REQUEST-DATA-FORMAT : JSON",
"X-PAYPAL-RESPONSE-DATA-FORMAT : JSON"
);
$data = array();
$data['actionType'] = "CREATE"; //PAY
$data['currencyCode'] = "SGD";
$receiver['amount'] = $orderTotal;
$receiver['email'] = $receiverEmail;
$data['receiverList'] = array();
$data['receiverList']['receiver'][] = $receiver;
$data['returnUrl'] = $returnURL;
$data['cancelUrl'] = $cancleURL;
$requestEnvelope = array();
$requestEnvelope['errorLanguage'] = "en_US";
$data['requestEnvelope'] = $requestEnvelope;
//I omitted the POST call
//print_r($returnedData);
$payKey = $returnedData->payKey;
$paymentStatus = $returnedData->paymentExecStatus;
/*
* Set payment options
*/
$endPoint = "https://svcs.sandbox.paypal.com/AdaptivePayments/SetPaymentOptions";
//paymentDetailsData
$paymentDetailsData = array();
//set payKey
echo "payKey: " . $payKey;
$paymentDetailsData['payKey'] = $payKey;
//displayOptions
$displayOptions['businessName'] = "My Business";
$paymentDetailsData['displayOptions'] = $displayOptions;
//senderOptions
$senderOptions = array();
$senderOptions['requireShippingAddressSelection'] = true; //set to true if courier is chosen
$senderOptions['shippingAddress']['addresseeName'] = "Ny Name";
$senderOptions['shippingAddress']['street1'] = "Address 1Avenue 3";
$senderOptions['shippingAddress']['street2'] = "#xx-112";
$senderOptions['shippingAddress']['city'] = "Singapore";
$senderOptions['shippingAddress']['state'] = "Singapore";
$senderOptions['shippingAddress']['zip'] = "123456";
$senderOptions['shippingAddress']['country'] = "Singapore";
$paymentDetailsData['senderOptions'] = $senderOptions;
//item
$item = array();
$item['name'] = "Korea";
$item['itemPrice'] = 11;
//there is still price, and itemcount
//invoiceData
$invoiceData = array();
$invoiceData['item'] = $item;
//receiverOptions
$receiverOptions = array();
$receiverOptions['description'] = "Product description.";
$receiverOptions['invoiceData'] = $invoiceData;
$paypalEmail = "test#test.com"; //I may need to change this
$receiver['email'] = $paypalEmail;
$receiverOptions['receiver'] = $receiver;
$paymentDetailsData['receiverOptions'] = $receiverOptions;
//requestEnvelope. I have set the request envelope above. It is the same. Can still be used.
$paymentDetailsData['requestEnvelope'] = $requestEnvelope;
makePaypalCall($endPoint, $paypalHeaders, $paymentDetailsData);
/*
* Get payment options. I can see the result of get payment options correctly,
*/
echo "GETTING PAYMENT OPTIONS";
$endPoint = "https://svcs.sandbox.paypal.com/AdaptivePayments/GetPaymentOptions";
$getPaymentData['payKey'] = $payKey;
$getPaymentData['requestEnvelope'] = $requestEnvelope;
makePaypalCall($endPoint, $paypalHeaders, $getPaymentData);
$endPoint = "https://svcs.sandbox.paypal.com/AdaptivePayments/ExecutePayment";
/*
* ExecutePayment. Ok, I get the error here. This payment request must be authorized by the sender
*/
$executePaymentData = array();
echo "paykey: " . $payKey;
$executePaymentData['payKey'] = $payKey;
//$executePaymentData['actionType'] = "PAY";
$executePaymentData['requestEnvelope'] = $requestEnvelope;
I hope I understand you correctly.
To me it seems like you are skipping the step where the user needs to authorize the payment. When you do a Pay (Create) operation you should see get a RedirectURL in the response from PayPal. You need to redirect the user to this URL for them to authorize the payment on PayPal.
Once they have approved the payment, then you'll be able to execute the payment.
Your steps need to change to:
Create PayRequest
Set PaymentOptions
Redirect to PayPal (RedirectURL from the PayRequest response) for user authorization
If authorized, ExecutePayment
PayPal hints at this on the Pay API operation page
URL to redirect the sender's browser to after the sender has logged into PayPal and approved a payment; it is always required but only used if a payment requires explicit approval
After the step 3, the user will be returned to the URL your provided in $data['returnUrl'] = $returnURL;
I am using Delayed Chained Payment and often i end up with this error "This payment request must be authorized by the sender". Actually it was due to a small mistake in the logic.
wrong procedure (# step 3)
generate a payKey successfully
save it to database
refresh the page for some reason which results in generating new payKey (this new payKey doesn't update to database)
payRequest = pay();
.....
if(empty(db_record)) {
.....
db_record->payKey = payRequest->payKey;
db_record->save();
}
paid with new payKey ( ie. payment approved by sender)
trying to execute payment with payKey from database (which is indeed old one. That payKey was not used to make payment)
Solution
update database with last payKey which used for making payment by getting approval of sender
step 3 should be like
if(empty(db_record) || is_expired(db_record->payKey)) {
payRequest = pay();
.....
.....
db_record->payKey = payRequest->payKey;
db_record->save();
}
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.