Twitter says "Could not authenticate you" when space inside a parameter - twitter

The code below works perfectly fine if, $searchterm = "Chinmay", but doesn't work correct, when the $searchterm has a space in it. I have tried many encoding and have no luck with it.
Section 1 - Getting the URL and Parameters
$searchterm = "Chinmay+Patel";
$params = array( "q" => $searchterm );
$url = 'https://api.twitter.com/1.1/users/search.json';
Section 2 - Building the Signature
$oauth = array(
'oauth_consumer_key' => \Config::get("oauth-4-laravel::consumers.Twitter.client_id"),
'oauth_nonce' => hash('SHA1', time()),
'oauth_signature' => '',
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_timestamp' => time(),
'oauth_token' => $this->twitter_user->access_token,
'oauth_version' => '1.0'
);
foreach ($oauth as $key => $value)
{
if (empty($value)) continue;
$oauth_vals[] = "{$key}={$value}";
}
if( !empty( $params ) ){
foreach ($params as $key => $value) {
if(empty($value)) continue;
$oauth_vals[] = "{$key}={$value}";
}
}
$base = 'GET&' . rawurlencode($url) . '&' . rawurlencode(implode('&', $oauth_vals) );// . '&'. implode( '&', $params);
$composite_key = rawurlencode(\Config::get("oauth-4-laravel::consumers.Twitter.client_secret")) . '&' . rawurlencode($this->twitter_user->secret);
$oauth_signature = base64_encode(hash_hmac('sha1', $base, $composite_key, true));
$oauth['oauth_signature'] = rawurlencode($oauth_signature);
Section 3 - Building the request header
foreach ($oauth as $key => $value)
{
$auth_header[] = "{$key}=\"{$value}\"";
}
$auth_header = implode(', ', $auth_header);
Section 4 - Building the url and making the request
if( !empty( $params ) ){
$url .= "?" . http_build_query( $params );
}
$verbose = fopen('php://temp', 'rw+');
$options = array(
CURLOPT_HTTPHEADER => array("Authorization: OAuth {$auth_header}"),
CURLOPT_HEADER => false,
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_HTTPGET => true,
// DEBUGGING
CURLOPT_VERBOSE => TRUE,
CURLOPT_STDERR => $verbose
);
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);
$twitter_data = json_decode($json, true);
rewind($verbose);
Section 5 - Outputting the data
$verboseLog = stream_get_contents($verbose);
echo "Verbose information:\n<pre>", htmlspecialchars($verboseLog), "</pre>\n";
var_dump( $twitter_data );
What could be the issue? A little bit out of scope for the question, but this code doesn't work with multiple parameters either. For example, if I add the count parameter, it gives me the same error.

Related

Microsoft Graph - Get Token from Authorisation Response

I am following the instructions here:
https://learn.microsoft.com/en-us/graph/auth-v2-user?view=graph-rest-1.0#3-get-a-token
I get the authorisation response and therefore the required code, but when I request the token I get a "HTTP/1.1 401 Unauthorized" response.
This is my code (not for production, just for me to get the flow/code right first):
<?php
/*
Auth
https://learn.microsoft.com/en-us/graph/auth-v2-user?view=graph-rest-1.0
*/
define("HOST", 'https://login.microsoftonline.com');
define("TENANT", 'common');
define("AUTH_ENDPOINT", HOST.'/'.TENANT.'/oauth2/v2.0/authorize');
define("TOKEN_ENDPOINT", HOST.'/'.TENANT.'/oauth2/v2.0/token');
define("CLIENT_ID", '<< FROM AZURE PORTAL >>');
define("CLIENT_SECRET", '<< FROM AZURE PORTAL >>');
define("ALL_SCOPES", rawurlencode('offline_access user.read mail.read'));
define("CALLBACK", rawurlencode('http://localhost:300/graph2/auth.php'));
// Build URL
$url = AUTH_ENDPOINT."?client_id=".CLIENT_ID;
$url .= "&response_type=code";
$url .= "&redirect_uri=".CALLBACK;
$url .= "&response_mode=query";
$url .= "&scope=".ALL_SCOPES;
echo "<a href=$url>$url</a>";
if (isset($_GET))
{
echo '<pre>';print_r($_GET);echo'</pre>';
if (isset($_GET['code']))
{
// Got authorisation code - now need token
$response = requestAccessTokenByVerifier($_GET['code']);
echo ">".$response;
}
}
function requestAccessTokenByVerifier($verifier)
{
return requestAccessToken(
array(
'client_id' => CLIENT_ID,
'redirect_uri' => CALLBACK,
'client_secret' => CLIENT_SECRET,
'code' => $verifier,
'grant_type' => 'authorization_code',
'scope' => ALL_SCOPES
)
);
}
function requestAccessToken($content)
{
$response = sendRequest(TOKEN_ENDPOINT, 'POST', $content);
if ($response !== false)
{
$authToken = json_decode($response);
if (!empty($authToken) && !empty($authToken->{ACCESSTOKEN})) return $authToken;
}
die("No access token");
return false;
}
function sendRequest($url, $method = 'GET', $data = array(), $headers = array('Content-Type: application/x-www-form-urlencoded'))
{
$context = stream_context_create(
array(
'http' => array(
'method' => $method,
'header' => $headers,
'content' => buildQueryString($data)
)
)
);
echo "URL: $url<br>";
echo '<pre>';print_r($data);echo '</pre>';
echo buildQueryString($data)."<br>";
$response = file_get_contents($url, false, $context);
echo '<pre>';var_dump($http_response_header);echo '</pre>';
return $response;
}
function buildQueryString($array)
{
$result = '';
foreach ($array as $k => $v)
{
if ($result == '') $prefix = ''; else $prefix = '&';
$result .= $prefix . $k . '=' . $v;
}
return $result;
}
?>
As you will see I've put a few basic diagnostics in there which show I am getting the code required successfully, but then not being able to get a token from the code.
Can anybody suggest what to try next, I wonder either from a debugging point of view or alternative approaches.
Thanks.
OK, after digging around I realised I'd made a stupid mistake, but just in case anybody else does the same - you need to use the client secret value not id!
I've deleted that client secret :)
Hope that helps somebody else bashing their head against a brick wall.

post data with curl and change page url

I have a shopping site and I have to send username and password and some other data to the bank, so I have used curl for posting data .because it should be safe.
but my problem is when I post data with curl to the bank, page url dont change! I see banks result in my server page !!!
I need this posting data same as posting data in html page redirect too the url which has been determined !!
$data = array(
"MID" => "0113-19",
"RedirectURL" => $SERVER . "/shop/profile.php",
"Amount" => $sum,
"ResNum" => $ResNum,
"username" => "xxxx",
"password" => "1234");
//traverse array and prepare data for posting (key1=value1)
foreach ( $data as $key => $value) {
$data[] = $key . '=' . urlencode($value);
}
$post_string = implode ('&', $data);
$res = array();
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_POST => true, // return web page
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_AUTOREFERER => false, // set referer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect
CURLOPT_TIMEOUT => 120, // timeout on response
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
CURLOPT_POSTFIELDS => $post_string, // stop after 10 redirects
CURLOPT_SSL_VERIFYPEER => false , // stop after 10 redirects
CURLOPT_COOKIEJAR => "cookie.txt" , // stop after 10 redirects
CURLOPT_COOKIEFILE => "cookie.txt" , // stop after 10 redirects
CURLOPT_SSL_VERIFYPEER => false , // stop after 10 redirects
CURLOPT_USERAGENT => "Mozilla/5.0 (Windows; U;
Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1" // stop after 10 redirects
);
//////////////////////
$ch = curl_init( $url );
curl_setopt_array( $ch, $options );
$content = curl_exec( $ch );
$err = curl_errno( $ch );
$errmsg = curl_error( $ch );
$header = curl_getinfo( $ch );
curl_close( $ch );

Twitter OAuth Showing Timeline Not Tweets

Anyone know how I can tweak the settings in the Wordpress theme used in this site (http://www.ethnecity.church.ly/) to make the Twitter section (near the bottom left of the page) show the tweets for the account instead of the timeline from the Twitter account? Note: the plugin is using OAuth...I just don't know how to tell it to display tweets instead of the timeline.
I believe this is the code that displays the twitter info:
<?php
$user_screen_name = 'ethnecity';
$user_full_name = '(removed)';
$settings = array(
'consumer_key' => '(removed)',
'consumer_secret' => '(removed)',
'access_token' => '(removed)',
'access_token_secret' => '(removed)');
$api_url = 'https://api.twitter.com/1.1/statuses/home_timeline.json';
$api_params = array(
'count' => 40,
'contributor_details' => 'false',
'include_entities' => 'false');
// OAuth:
function oauth_encode($data){
if(is_array($data)){
return array_map('oauth_encode', $data);
} else if(is_scalar($data)) {
return str_ireplace(array('+', '%7E'), array(' ', '~'), rawurlencode($data));
} else {
return '';
}}
// OAuth base settings
$oauth_params = array(
'oauth_consumer_key' => $settings['consumer_key'],
'oauth_nonce' => md5(microtime() . mt_rand()),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_timestamp' => time(),
'oauth_token' => $settings['access_token'],
'oauth_version' => '1.0',
);
// Sign OAuth params
$sign_params = array_merge($oauth_params, $api_params);
uksort($sign_params, 'strcmp');
foreach ($sign_params as $k => $v) {
$sparam[] = oauth_encode($k) . '=' . oauth_encode($v);
}
$sparams = implode('&', $sparam);
$base_string = 'GET&' . oauth_encode($api_url) . '&' . oauth_encode($sparams);
$signing_key = oauth_encode($settings['consumer_secret']) . '&' . oauth_encode($settings['access_token_secret']);
$oauth_params['oauth_signature'] = oauth_encode(base64_encode(hash_hmac('sha1', $base_string, $signing_key, TRUE)));
// Set Authorization header:
uksort($oauth_params, 'strcmp');
foreach ($oauth_params as $k => $v) {
$hparam[] = $k . '="' . $v . '"';
}
$hparams = implode(', ', $hparam);
$headers = array();
$headers['Expect'] = '';
$headers['Authorization'] = 'OAuth ' . $hparams;
foreach ($headers as $k => $v) {
$curlheaders[] = trim($k . ': ' . $v);
}
// Format params:
foreach ($api_params as $k => $v) {
$rparam[] = $k . '=' . $v;
}
$rparams = implode('&', $rparam);
// echo "curl --get '" . $api_url . "' --data '" . $rparams . "' --header 'Authorization: OAuth " . $hparams . "' --verbose" . PHP_EOL;
// GET:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $api_url . '?' . $rparams);
curl_setopt($ch, CURLOPT_HTTPHEADER, $curlheaders);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 10 );
$response = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$info = curl_getinfo($ch);
$error = curl_error($ch);
$errno = curl_errno($ch);
curl_close($ch);
function get_twitterfeeds(){
global $code; global $response;
if($code != 200){
//echo 'Error' . PHP_EOL;
//echo $code . PHP_EOL;
//print_r($response);
//print_r($info);
} else {
$all = json_decode($response, true);
//echo '<pre />';
// print_r($all);
//exit;
return $all;
}
}
?>
Your code should be modified so as to retrieve user's timeline. As per the current code it should return only tweets present on your timeline.
If you need only your's or a particular user's feed , your code should be modified in such a way that resource URL should be changed.
$api_url = 'https://api.twitter.com/1.1/statuses/user_timeline.json';
$api_params = array(
'screen_name' => 'ethnecity'
'count' => 40,
'contributor_details' => 'false',
'include_entities' => 'false'
);
Please verify the document https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline

paypal access oauth login json_decode returned null

i have 2 PHP files, one index.php and the other one paypal.php.
The code for paypal.php is:
<?php
session_start();
$client_id = 'xxxxxxxxxxxx';
$client_secret = 'xxxxxxxxxxxxxxxxxxxx';
$scopes = 'email profile';
$app_return_url = 'http://xxx.com/xxx/paypal.php';
$nonce = time() . rand();
$code = $_REQUEST["code"];
if(empty($code)) {
$_SESSION['state'] = md5(uniqid(rand(), TRUE));
$paypal_auth_url = "https://www.paypal.com/webapps/auth/protocol/openidconnect/v1/authorize?"
."client_id=".$client_id
."&response_type=code"
."&scope=".$scopes
."&nonce=".$nonce
."&state=".$_SESSION['state']
."&redirect_uri=".urlencode($app_return_url);
header("Location: $paypal_auth_url");
}else{
$token_url = "https://www.paypal.com/webapps/auth/protocol/openidconnect/v1/tokenservice";
$postvals = "client_id=".$client_id
."&client_secret=".$client_secret
."&grant_type=authorization_code"
."&code=".$code;
$ch = curl_init($token_url);
$options = array(
CURLOPT_POST => 1,
CURLOPT_VERBOSE => 1,
CURLOPT_POSTFIELDS => $postvals,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_SSLVERSION => 3
);
curl_setopt_array( $ch, $options );
$response = curl_exec($ch);
curl_close($ch);
$atoken = json_decode($response);
$profile_url = "https://www.paypal.com/webapps/auth/protocol/openidconnect/v1/userinfo?"
."schema=openid"
."access_token=".$atoken->access_token;
$ch = curl_init($profile_url);
$options = array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_SSLVERSION => 3
);
curl_setopt_array( $ch, $options );
$response = curl_exec($ch);
curl_close($ch);
$profile= json_decode($response,true);
$_SESSION['paypal_user'] = "true";
$_SESSION['profile'] = $profile;
echo("<script> top.location.href='index.php'</script>");
}
?>
The code for index.php is:
<?php
session_start();
// LOGOUT
if ($_GET['logout'] == 'true'){
$_SESSION['paypal_user']="";
}
if (strlen($_SESSION['paypal_user'])){
// LOGGED USER
echo "<pre>";
print_r($_SESSION['profile']);
echo "</pre>";
echo "<br><BR> <a href='?logout=true'>LOGOUT</a>";
}else{
// LOGIN
?>
<a href='paypal.php' title='Paypal oAuth Login'>
<img src='https://www.paypalobjects.com/en_US/Marketing/i/btn/login-with-paypal-button.png'>
</a>
<?
}
?>
Any ideas why this code is not working? I tried var_dump json_decode and it returns null.
Thank you!
I may be wrong, but I believe you scopes need to be...
"scopes": "email https://uri.paypal.com/services/paypalattributes",
The URL is the profile
simply add '&' on before access token,he missed & symbol between two variables
$profile_url = "https://www.paypal.com/webapps/auth/protocol/openidconnect/v1/userinfo?" ."schema=openid" ."**&**access_token=".$atoken->access_token;

get_permalink to attachment not working

I have following code:
<?php
$args = array(
'post_type' => 'attachment',
'numberposts' => 12,
'post_status' => null
);
$attachments = get_posts( $args );
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
echo '<li><a href="'.get_permalink( $attachment->ID ).'">';
echo wp_get_attachment_image( $attachment->ID, array('100', '100') );
echo '</a></li>';
}
}
?>
The point of this script is to show last added 12 photos (thumbs of it). And this works perfect. But I want to add second funcionality - link to the page where it comes from (usually native gallery embed into post/page)
The problem is that in this case the link is corrupted. It always links to the very first post. What I am doing wrong?
Try get_attachment_link($attachment->ID).
Or the_attachment_link($attachment->ID) to directly print the anchor tag with the URL
Here is the final version:)
<?php
$args = array(
'post_type' => 'attachment',
'numberposts' => 12,
'post_status' => null
);
$attachments = get_posts( $args );
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
$url = get_permalink( $attachment->ID );
echo '<li><a href="'.strstr($url, '/attachment', true).'">';
echo wp_get_attachment_image( $attachment->ID, array('100', '100') );
echo '</a></li>';
}
}
?>
/attachment is the starting point from which we want to remove everything from the url.

Resources