google api & OAuth2 get refresh token - google-oauth

I have the following code:
$this->client = new Google_Client();
$this->client->setAuthConfig(FCPATH . 'google-api-php-client-master'.DIRECTORY_SEPARATOR.'client_secret.json');
$this->client->setRedirectUri($redirect_uri);
$this->client->addScope("https://www.googleapis.com/auth/calendar");
$this->client->setAccessType('offline');
$this->client->setApprovalPrompt("force");
$this->client->setAccessToken($access_token);
if ($this->client->isAccessTokenExpired()) {
$this->client->refreshToken($this->client->getRefreshToken());
print_r($this->client->getAccessToken());
}
When I print_r get access token, I got the following array without refresh token:
Array
(
[access_token] => ya29.LwIjjaXB1kGunCp8EzwMwmaO4eoDsqbdoRFNjWhcDvw59RtDnT6mbjlauX3PM6irbMfg
[token_type] => Bearer
[expires_in] => 3600
[created] => 1447747649
)
But I want to get such an array with refresh token, for example:
Array
(
[access_token] => ya29.LwIjjaXB1kGunCp8EzwMwmaO4eoDsqbdoRFNjWhcDvw59RtDnT6mbjlauX3PM6irbMfg
[token_type] => Bearer
[expires_in] => 3600
[refresh_token] => 1/wzTZcDm2fzZD9y3Ixr2gczgC5iD1zifVSGQoijCu4vlIgOrJDtdun6zK6XiATCKT
[created] => 1447747649
)

Related

Shopware - How to get products using App Credentials?

I created App in Shopware and able to get apiKey, secretKey, shopUrl and shopId. I want to get all my products using these credentials.
This is my code
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "http://shopware.example.com/store-api/product",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $payload,
CURLOPT_HTTPHEADER => [
"Accept: application/json",
"Content-Type: application/json",
"sw-access-key: SW234C1LVA010CWHDD34WK1TMW"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
$data = json_decode($response, true);
print_r($data);
}
and I am getting error like this
Array
(
[errors] => Array
(
[0] => Array
(
[status] => 412
[code] => FRAMEWORK__ROUTING_SALES_CHANNEL_NOT_FOUND
[title] => Precondition Failed
[detail] => No matching sales channel found.
[meta] => Array
(
[parameters] => Array
(
)
)
)
)
)
When I using API key from settings page API I am able to get products.
But how to use App credentials (App key, secret key, shop URL) and get products
You should have gotten the API key during App registration:
https://developer.shopware.com/docs/guides/plugins/apps/app-base-guide#confirmation-request
Did you try that one? If it does not work for the store API you might want to use the admin API.

Add Tracking API in Paypal - Authorization failed

I am trying to add tracking number and order status in my sandbox account through tracking API but getting "Authorization failed due to insufficient permissions" error. Anyone have any idea why this error happens? Below are my codes and response from paypal -
API request
$clientId = 'my client id';
$secretKey = 'my secret key';
$token = $this->getAccessToken($clientId, $secretKey);
$transaction = $this->_objectManager->create('\Magento\Sales\Api\Data\TransactionSearchResultInterfaceFactory')->create()->addOrderIdFilter($currentOrder->getId())->getFirstItem();
$transactionId = $transaction->getData('txn_id');
$postfields = [
'trackers' =>
[
0 =>
[
'transaction_id' => $transactionId,
'tracking_number' => $currentOrderTrackingNumber,
'status' => 'SHIPPED',
'carrier' => 'OTHER',
'carrier_name_other' => 'SCS Logistics'
]
]
];
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api-m.sandbox.paypal.com/v1/shipping/trackers-batch",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode($postfields),
CURLOPT_HTTPHEADER => array(
"Content-Type: application/json",
"Authorization: Bearer " . $token
),
));
$response = curl_exec($curl);
curl_close($curl);
$response = json_decode($response, true);
Response from paypal
Array
(
[tracker_identifiers] => Array
(
)
[errors] => Array
(
[0] => Array
(
[name] => NOT_AUTHORIZED
[message] => Authorization failed due to insufficient permissions
[details] => Array
(
[0] => Array
(
[field] => /trackers/1/transaction_id
[value] => 42L93730906985049
[location] => body
[issue] => USER_NOT_AUTHORIZED
[description] => You are not authorized to add or modify tracking number for this transaction
)
)
[links] => Array
(
)
)
)
[links] => Array
(
[0] => Array
(
[href] => https://api-m.sandbox.paypal.com/v1/shipping/trackers-batch
[rel] => self
[method] => POST
[encType] => application/json
)
)
)
I already contacted support and they added required permission but it's not working. Please if anyone have any idea about it help me. Thanks in advance.

LinkedIn API: The token used in the OAuth request has been revoked (Web Social Login)

Here's how I try to get the user data from LinkedIn:
$config = array(
'appKey' => 'appKey',
'appSecret' => 'appSecret',
'callbackUrl' => 'callbackUrl'
);
#session_start();
$linkedin = new LinkedInOAuth2( $config );
if ( $_GET['login_type'] == 'linkedin_login' ) {
$scope = array( 'r_emailaddress', 'r_basicprofile' );
social_js_redirect( $linkedin-getAuthorizeUrl( $config['appKey'], $config['callbackUrl'], $scope ) );
} elseif ( ! empty( $_GET['code'] && ! empty( $_GET['state'] ) ) ) {
$data = $linkedin->getAccessToken( $config['appKey'], $config['appSecret'], $config['callbackUrl'] );
if ( ! empty( $data['access_token'] ) ) {
$linkedin->getProfile(); // Get user data from linkedin to add to database
} else {
// Invalid Authorization
}
}
This is the error code that adds into the database:
Array
(
[0] => Array
(
[errorCode] => 0
[message] => Then token used in this request has been revoked by the user.
[requestId] => xxx
[status] => 401
[timestamp] => 1540051999134
)
)
NOTE: By check my PHP code you will understand that LinkedIn successfully get the access token
could you try adding a delay of 5-6 seconds after obtaining the token. Most problems i see on stackoverflow/github regarding this problem has to due to the fact that LinkedIn doesnt seem to activate the token that it gives immediately, so waiting a bit helps.

Github api Login - get user

I have a problem with Github api.
I parse the access_token but when i try to get the user I get the following error:
Warning: file_get_contents(https://api.github.com/user?access_token=mplamplampla): failed to open stream: HTTP request failed! HTTP/1.0 403 Forbidden
When I try to get the contents through address bar in my browser is working!
My code:
//Get the access token
$postdata = http_build_query(
array(
'client_id' => 'mplamplaID',
'client_secret' => 'mplamplaSECRET',
'code' => trim($_GET['code']),
'redirect_uri' => 'http://vlingos.com/github.php'
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$vip = file_get_contents('https://github.com/login/oauth/access_token',false,$context);
parse_str($vip);
//Get the User
$json = file_get_contents('https://api.github.com/user?access_token='.$access_token);
if(isset($json) and (is_array($json)===true or is_object($json)===true)){
$jsonIterator = new RecursiveIteratorIterator(new RecursiveArrayIterator(json_decode($json, TRUE)),RecursiveIteratorIterator::SELF_FIRST);
foreach ($jsonIterator as $key => $val) {
$git_user[$key] = $val;
}
print_r($git_user);
}else{
echo "can't get user";
}
Can someone propose something?
kindest regards
Enable your token is correct. generate new token, refer to:https://help.github.com/articles/creating-an-access-token-for-command-line-use/
test it:
curl https://api.github.com/user?access_token=your token

Get the CSRF token in test

I'm writing functional test and i need to make ajax post request. "The CSRF token is invalid. Please try to resubmit the form". How can i get the token in my functional test ?
$crawler = $this->client->request(
'POST',
$url,
array(
'element_add' => array(
'_token' => '????',
'name' => 'bla',
)
),
array(),
array('HTTP_X-Requested-With' => 'XMLHttpRequest')
);
CSRF token generator is normal symfony 2 service. You can get service and generate token yourself. For example:
$csrfToken = $client->getContainer()->get('form.csrf_provider')->generateCsrfToken('registration');
$crawler = $client->request('POST', '/ajax/register', array(
'fos_user_registration_form' => array(
'_token' => $csrfToken,
'username' => 'samplelogin',
'email' => 'sample#fake.pl',
'plainPassword' => array(
'first' => 'somepass',
'second' => 'somepass',
),
'name' => 'sampleuser',
'type' => 'DSWP',
),
));
The generateCsrfToken gets one important parameter intention which should be the same in the test and in the form otherwise it fails.
After a long search (i've found nothing in doc and on the net about how to retrieve csrf token) i found a way:
$extract = $this->crawler->filter('input[name="element_add[_token]"]')
->extract(array('value'));
$csrf_token = $extract[0];
Extract the token from response before make the request.
In symfony 3, in your WebTestCase, you need to get the CSRF token:
$csrfToken = $client->getContainer()->get('security.csrf.token_manager')->getToken($csrfTokenId);
To get the $csrfTokenId, the best way would be to force it in the options of your FormType ():
class TaskType extends AbstractType
{
// ...
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'csrf_token_id' => 'task_item',
));
}
// ...
}
So in this case: $csrfTokenId = "task_item";. Or you you can try to use the default value, that would be the name of your form.
Then use it as a post parameter:
$client->request(
'POST',
'/url',
[
'formName' => [
'field' => 'value',
'field2' => 'value2',
'_token' => $csrfToken
]
]
);
Just in case someone stumble on this, in symfony 5 you get the token this way:
$client->getContainer()->get('security.csrf.token_manager')->getToken('token-id')->getValue();
where 'token-id' is the id that you used in the configureOptions method in your form type, which would look something like this:
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
"data_class" => Foo::class,
"csrf_protection" => true,
"csrf_field_name" => "field_name", //form field name where token will be placed. If left empty, this will default to _token
"csrf_token_id" => "token-id", //This is the token id you must use to get the token value in your test
]);
}
Then you just put the token in the request as a normal field.