Twitter cookies expiring - PHP CURL - php

have this code that saves Twitter cookies so I can use it later, that is, I have a login system.
$obj = new stdClass;
$obj->cookies = '';
$obj->location = '';
$request = curl_init();
curl_setopt_array($request, [
CURLOPT_URL => 'https://twitter.com/',
CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_HEADER => true,
CURLOPT_COOKIEJAR => getcwd() . '/cookies/' . $username . '.txt',
CURLOPT_HEADERFUNCTION => function($curl, $header) use (&$obj) {
if (stripos($header, 'Set-Cookie:') === 0) {
if (preg_match('/^Set-Cookie: \s*([^=]*)=([^;]*)/mi', $header, $matches)) {
$obj->cookies .= $matches[1] . '=' . $matches[2] . '; ';
$obj->{$matches[1]} = $matches[2];
}
}
return strlen($header);
}
]
);
$response = curl_exec($request);
The problem is that when you purchase these cookies later, they do not work, they expire, how do I renew or do not expire?

Related

Php Codeigniter - improve execution time

Actually, i have this script
public function getsbstock()
{
if ($_SERVER['REMOTE_ADDR'] !== $this->localhost) {echo $_SERVER['REMOTE_ADDR'];}
else{
$datetimenow = (new DateTime())->format('Y-m-d');
$url = get_integration_url('smartbill');
$this->db->select('user_id');
$this->db->where('sb_get_stock',1);
$this->db->where('is_smartbill',1);
$this->db->where('is_active',1);
$resArr = $this->db->get('ci_users')->result_array();
foreach ($resArr as $row){
$user_id = $row['user_id'];
$auth = base64_encode(get_sb_email($user_id) . ":" . get_sb_token($user_id));
$cif = get_sb_cif($user_id);
$sbwh = preg_replace('/\s+/', '+', get_sb_warehouse($user_id));
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => ''. $url .'stocks?cif=' . $cif . '&date=' . $datetimenow . '&warehouseName=' . $sbwh . '',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_HTTPHEADER => array(
'Authorization: Basic ' . $auth . ' '
),
));
$content = curl_exec($curl);
$prodArr = json_decode($content, true);
foreach($prodArr['list'][0]['products'] as $key => $val){
$productCode = $val['productCode'];
$quantity = $val['quantity'];
$updatedata = array('quantity' => $quantity,);
$this->db->where('sbCode',$productCode);
$this->db->where('user_id', $user_id);
$this->db->update('ci_products', $updatedata);
}
}
}
}
All works fine here, and to make a brifley description, i get from db every users which is active, then for each i m calling an api (different apikeys) and grab data. Api responded me with 1k prod and 2-3 prod for other (just tests), then i update quantity in my database (ci_products) where i have around 15k rows. I see that execution is taking a bit long and i'm not sure if it's normal and if this can be improved somehow :-? it's taking around 20-30 seconds to perform this function.

Shopee RefreshAccessToken always return Error param

i've tried to get a new token, by running shopee open api RefreshAccessToken with php curl,
but the result always give me error param code.
from this documentation : https://open.shopee.com/documents/v2/OpenAPI%202.0%20Overview?module=87&type=2
<?php
$partner_id = ...partnerid;
$partner_key = ...partnerkey;
$timest = time();
$shop_id = ...shopid;
$refresh_token = ...refresh_token;
$host = 'https://partner.shopeemobile.com';
$path = '/api/v2/auth/access_token/get';
$base_string = sprintf("%s%s%s",$partner_id,$path,$timest);
$sign = hash_hmac('sha256', $base_string, $key, false);
$url = $host.$path.sprintf("?timestamp=%s&partner_id=%s&sign=%s",$timest,$partner_id,$sign);
$data = array(
'shop_id' => $shop_id,
'refresh_token:' => $refresh_token,
'partner_id:' => $partner_id,
);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_POSTFIELDS => $data,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json'
),
));
$response = curl_exec($curl);
curl_close($curl);
// echo $response;
?>
and the result is
{"error":"error_param","message":"error params","request_id":"b61938142425d13e72292xf3b645d62b"}
where did my code goes wrong, please help.
I don't work with php, but in python i solved converted type str to int in shop_id and partner_id
body = {
'code': code,
'shop_id': int(shop_id),
'partner_id': int(partner_id),
}
follow my full code
def get_token_shop_level(code, partner_id, partner_key, shop_id):
timest = int(time.time())
body = {
'code': code,
'shop_id': int(shop_id),
'partner_id': int(partner_id),
}
host = 'https://partner.test-stable.shopeemobile.com'
path = '/api/v2/auth/token/get'
base_string = f'{partner_id}{path}{timest}'
partner_key = partner_key.encode()
base_string = base_string.encode()
sign = hmac.new(partner_key, base_string, hashlib.sha256).hexdigest()
url = host + path + f'?partner_id={partner_id}&timestamp={timest}&sign={sign}'
headers = {
'Content-Type': 'application/json'
}
resp = requests.post(url, json=body, headers=headers)
ret = json.loads(resp.content)
access_token = ret.get('access_token')
refresh_token = ret.get('refresh_token')
return access_token, refresh_token
$partner_id = ...partnerid;
$partner_key = ...partnerkey;
$timest = time();
$shop_id = ...shopid;
$refresh_token = ...refresh_token;
$host = 'https://partner.shopeemobile.com';
$path = '/api/v2/auth/access_token/get';
$base_string = sprintf("%s%s%s",$partner_id,$path,$timest);
$sign = hash_hmac('sha256', $base_string, $key, false);
your $sign is wrong.. should be
$sign = hash_hmac('sha256', $base_string, $partner_key, false);
the answer is in both #SungALy and #Davin Kho, check your code again,
As the error suggested you have an error on your POST data parameters,
$data = array(
'shop_id' => $shop_id,
'refresh_token' => $refresh_token,
'partner_id' => $partner_id,
);
$data = json_encode($data);
remove the colon on the array name and convert to JSON before passing as pointed by #SungALy
and $key in
$sign = hash_hmac('sha256', $base_string, $key, false);
must be $partner_key
$sign = hash_hmac('sha256', $base_string, $partner_key, false);
pointed by Davin Kho.
this is work for me.in url i am just add &is_developer=1 and base string I am using utf8_encode.
$timestamp = time();
$path = '/api/v2/auth/access_token/get';
$base = $partnerId.$path.$timestamp;
$sign = hash_hmac('sha256',utf8_encode($base), $partnerKey);
$url = $host.$path.sprintf("?timestamp=%s&partner_id=%s&sign=%s&is_developer=1'",$timest,$partner_id,$sign);
and in change this CURLOPT_POSTFIELDS => $data, with CURLOPT_POSTFIELDS => json_encode($data),

Get users email from twitter for auth (https://api.twitter.com/1.1/account/verify_credentials.json)




I followed the tutorial from twitter (documentation), and got stuck at the last stage when I need to get user data with his mail (to make user authorization).



When I make a request without parameters, I get user data such as name, user ID, etc., I need to get the user's mail, but when I add the parameter "? Include_email = true" I get the error 32 "We cannot authenticate you".



I do not understand where I made a mistake (as I understand in the signature)



Thanks for attention


(Sorry for my English, this is not my native language)
$oauthParams = [
"oauth_consumer_key" => "...",
"oauth_token" => $requestOauthToken,
"oauth_signature_method" => "HMAC-SHA1",
"oauth_timestamp" => time(),
"oauth_nonce" => md5(uniqid()),
"oauth_version" => "1.0",
];
$baseURI = "https://api.twitter.com/1.1/account/verify_credentials.json?include_email=true";
$baseString = $this->buildBaseStringGET($baseURI, $oauthParams);
$consumerSecret = '...';
$compositeKey = $this->getCompositeKey($consumerSecret, $requestOauthTokenSecret);
$oauthParams['oauth_signature'] = base64_encode(hash_hmac('sha1', $baseString, $compositeKey, true));
$header = $this->buildAuthorizationHeader($oauthParams);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $baseURI,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_HTTPHEADER => array(
$header,
),
));
$response = curl_exec($curl);
curl_close($curl);
$response = json_decode($response, true)
private function buildBaseStringGET($baseURI, $oauthParams)
{
$baseStringParts = [];
ksort($oauthParams);
foreach ($oauthParams as $key => $value) {
$baseStringParts[] = "$key=" . urlencode($value);
}
return 'GET&' . urlencode($baseURI) . '&' . urlencode(implode('&', $baseStringParts));
}
private function buildAuthorizationHeader($oauthParams)
{
$authHeader = 'Authorization: OAuth ';
$values = [];
foreach ($oauthParams as $key => $value) {
$values[] = "$key=\"" . urlencode($value) . "\"";
}
$authHeader .= implode(',', $values);
return $authHeader;
}
If the user does not have an email address on their account, or if the email address is not verified, null will be returned.
https://developer.twitter.com/en/docs/twitter-api/v1/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials

API returns 1 profile data when array is passed

I am stuck on this for past 1 days and can't seem to get it to work. When I pass the array of userIds to profilesearch I only get 1 result back from the APi.
Please advise what am I doing wrong?
class Players{
public $username = "username";
public $password = "password";
public $base_url = "https://www.example.com/api/v1";
public $userIds = [];
//This is the first method that fires of to get the userId
public function usersearch(){
$url = $this->base_url . '/usersearch?informat=json&format=json';
$request = '{"identification":[]}';
$username = $this->username;
$password = $this->password;
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_HEADER => false,
CURLOPT_HTTPHEADER => array("Content-Type: UTF-8"),
CURLOPT_USERPWD => "$username:$password",
CURLOPT_TIMEOUT => 60,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $request,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_UNRESTRICTED_AUTH => true,
CURLOPT_FORBID_REUSE => false,
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_SSL_VERIFYPEER => 0
));
$response = curl_exec($ch);
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (curl_errno($ch)) {
var_dump(curl_error($ch), 'cURL Errors');
curl_close($ch);
} else {
$result = array();
$result = json_decode($response, true);
$result = $result['results'][0]['results'];
//Now that we have the list of users, loop over it and get their userId and save it in the userIds property as in array
foreach($result as $key => $item){
$this->userIds[] = $item['userId'];
}
}
curl_close($ch);
//Let's go and grab the profile data
$this->profilesearch();
}
public function profilesearch(){
//Make a local variable of the property userIds which contains list of userIds in array format
$userIds = $this->userIds;
$userIds = implode(',', $userIds); //This becomes "101,239,240"
$url = $this->base_url . '/profilesearch?informat=json&format=json';
$request = '{"formNames":["Athlete Summary"],"userIds":[' . $userIds . ']}'; //This becomes {"formNames":["Athlete Summary"],"userIds":[101,239,240]}
$username = $this->username;
$password = $this->password;
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_HEADER => false,
CURLOPT_HTTPHEADER => array("Content-Type: UTF-8"),
CURLOPT_USERPWD => "$username:$password",
CURLOPT_TIMEOUT => 60,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $request,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_UNRESTRICTED_AUTH => true,
CURLOPT_FORBID_REUSE => false,
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_SSL_VERIFYPEER => 0
));
$response = curl_exec($ch);
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (curl_errno($ch)) {
var_dump(curl_error($ch), 'cURL Errors');
} else {
$result = array();
$result = json_decode($response, true);
var_dump( $result ); //I get only one user data
}
curl_close($ch);
}
}
I think the API probably expects another JSON format. But I would recommend to
not craft a JSON string by hand you should use instead json_encode to build the
JSON string i.e.:
$request = json_encode([
'formNames' => ['Athlete Summary'],
'userIds' => $userIds,
]);

php curl multi init HTTP 401 Unauthorized

I have used a curl single init to issue an HTTP Get and all worked fine.
Now I tried to use a multi init (as I need to get multiple URLs) and I get a 401 message with "This request requires HTTP authentication" on the response to the Get.
Same Curl options where used on both cases.
Here is the code for th multi init and below it the single init function.
protected function _multiQueryRunkeeper($uri, $subscribersInfo,$acceptHeader) {
$curlOptions = array(
CURLOPT_URL => 'https://api.runkeeper.com' . $uri,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_TIMEOUT => 8,
CURLOPT_HTTPAUTH => CURLAUTH_ANY,
CURLOPT_HTTPGET => true
);
$curl_array = array();
$mh = curl_multi_init();
foreach ($subscribersInfo as $i => $subscriber) {
$curl_array[$i] = curl_init();
curl_setopt_array($curl_array[$i],$curlOptions);
curl_setopt($curl_array[$i], CURLOPT_HEADER,
array('Authorization: Bearer '.$subscriber['token'],
'Accept: application/vnd.com.runkeeper.' . $acceptHeader));
curl_multi_add_handle($mh,$curl_array[$i]);
}
$running = NULL;
do {
usleep(10000);
curl_multi_exec($mh,$running);
} while($running > 0);
$subscribersWorkoutFeed = array();
foreach($subscribersInfo as $i => $subscriber)
{
$subscribersWorkoutFeed[$i] = curl_multi_getcontent($curl_array[$i]);
curl_multi_remove_handle($mh, $curl_array[$i]);
}
curl_multi_close($mh);
return $subscribersWorkoutFeed;
}
protected function _singleQueryRunkeeper($uri, $subscriberToken,$acceptHeader) {
try{
// get fitness user's fitness activities from Runkeeper
$this->_curl = isset($this->_curl)? $this->_curl : curl_init();
$curlOptions = array(
CURLOPT_URL => 'https://api.runkeeper.com' . $uri,
CURLOPT_HTTPHEADER => array('Authorization: Bearer '.$subscriberToken,
'Accept: application/vnd.com.runkeeper.' . $acceptHeader),
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_TIMEOUT => 8,
CURLOPT_HTTPGET => true
);
curl_setopt_array($this->_curl,$curlOptions);
$response = curl_exec($this->_curl);
if($response == false) {
if (Zend_Registry::isRegistered('logger')) {
$logger = Zend_Registry::get('logger');
$logger->log('Curl error on _singleQueryRunkeeper: '
. curl_error($this->_curl), Zend_Log::INFO);
}
return null;
}
$data = Zend_Json::decode($response);
return($data);
} catch(Exception $e){
if (Zend_Registry::isRegistered('logger')) {
$logger = Zend_Registry::get('logger');
$logger->log('exception occured on getUsersLatestWorkoutsFromRK. Curl error'
. curl_error($this->_curl), Zend_Log::INFO);
}
}
}

Categories