PHP - Google API (Beta) getting bearer token - php

I have been using the Google API client in PHP for a project with google assistant where I need to post transaction updates.
See : https://developers.google.com/actions/transactions/dev-guide-physical-custom#6_send_order_updates
I use the server-to-server procedure to connect : https://developers.google.com/api-client-library/php/auth/service-accounts
I didn't found any support for Transactions or Actions. So I can't just call a service like the example. My goal is just to get the bearer token back and code the update based on the documentation of the transactions.
So I made this code :
$client = new Google_Client();
putenv('GOOGLE_APPLICATION_CREDENTIALS='.'path/to/file/');
$client->useApplicationDefaultCredentials();
$client->setApplicationName('Update_Orders_Test');
$client->setScopes(['https://www.googleapis.com/auth/actions.fulfillment.conversation']);
$auth = $client->authorize();
But with this code I can't get the bearer token in the $client object or the $auth object. But I do not have any error too. The path to the JSON file is correct, there is an error if the file doesn't exist.
Here is the client object :
{
"auth": null,
"http": {},
"cache": {},
"token": null,
"config": {
"application_name": "Update_Orders_Test",
"base_path": "https://www.googleapis.com",
"client_id": "",
"client_secret": "",
"redirect_uri": null,
"state": null,
"developer_key": "",
"use_application_default_credentials": true,
"signing_key": null,
"signing_algorithm": null,
"subject": null,
"hd": "",
"prompt": "",
"openid.realm": "",
"include_granted_scopes": null,
"login_hint": "",
"request_visible_actions": "",
"access_type": "online",
"approval_prompt": "auto",
"retry": [],
"cache_config": [],
"token_callback": null,
"jwt": null
},
"logger": null,
"deferExecution": false,
"requestedScopes": [
"https://www.googleapis.com/auth/actions.fulfillment.conversation"
]
}
As you can see the basic information are set but not the one relative to the json file.
Is there something I did wrong with this code ?

Related

Trying to access data returned from Stripe API with Alamofire, but result is not valid JSON

I'm trying to interface a Swift app with the Stripe API, using Alamofire, but I'm having trouble with the returned results. I was expecting valid JSON, but I am getting the following:
Stripe\SetupIntent JSON: {
"id": "seti_1Go**************g4qyJgp",
"object": "setup_intent",
"application": null,
"cancellation_reason": null,
"client_secret": "seti_1Go***************gp_secret_HM*******************ObpHy7Mk",
"created": 1590784053,
"customer": "cus_H*********Tna",
"description": null,
"last_setup_error": null,
"livemode": false,
"mandate": null,
"metadata": [],
"next_action": null,
"on_behalf_of": null,
"payment_method": null,
"payment_method_options": {
"card": {
"request_three_d_secure": "automatic"
}
},
"payment_method_types": [
"card"
],
"single_use_mandate": null,
"status": "requires_payment_method",
"usage": "off_session"
}
I'm using the following PHP code:
$customer = \Stripe\Customer::create();
$setupIntent = \Stripe\SetupIntent::create([
'customer' => $customer->id
]);
$this->response($setupIntent, 200);
How can I get at the JSON inside this object? I tried converting it to json, but then I get nothing. Alamofire doesn't like it the way it is now. Do I need to somehow strip off the "Stripe\SetupIntent JSON:"?
You can access the json object body that came back from the API with getLastResponse():
$setupIntent->getLastResponse()->body
edit. You can also use json_encode() to produce the json from the object yourself:
json_encode($setupIntent)

Stripe, Retrieve Card Info from Event

This was working for me on one account and today I added my listener to a new Stripe account and now it is no longer working. When a customer adds a new payment method to their account, the event customer.source.created is fired. Here is my code that WAS working (this is an excerpt):
<?php
if($event->type == 'customer.source.created') {
$cardID = $event_json->data->object->id;
$customerID = $event_json->data->object->customer;
$brand = $event_json->data->object->brand;
$last4 = $event_json->data->object->last4;
$exp_month = $event_json->data->object->exp_month;
$exp_year = $event_json->data->object->exp_year;
}
?>
Here is a sample Stripe JSON response:
{
"id": "evt_1DLkAh2Y54K5YG39Lku1hJ1G",
"object": "event",
"api_version": "2018-09-24",
"created": 1539664123,
"data": {
"object": {
"id": "card_1DLkAf2Y54K5YG39C0jMpCOj",
"object": "card",
"address_city": null,
"address_country": null,
"address_line1": null,
"address_line1_check": null,
"address_line2": null,
"address_state": null,
"address_zip": null,
"address_zip_check": null,
"brand": "JCB",
"country": "JP",
"customer": "cus_DnCcf39Nqp4RwF",
"cvc_check": "pass",
"dynamic_last4": null,
"exp_month": 12,
"exp_year": 2024,
"fingerprint": "t56gZmsPg6ztkHFH",
"funding": "credit",
"last4": "0000",
"metadata": {
},
"name": null,
"tokenization_method": null
}
},
"livemode": false,
"pending_webhooks": 2,
"request": {
"id": "req_L9pvt2RR3VSZoG",
"idempotency_key": null
},
"type": "customer.source.created"
}
The Stripe response code is 200. I have other events in my listener like charge.succeeded that are working just fine with pretty much the same coding methods. Right now, I can't get the $cardID to echo. So I'm wondering if Stripe changed something recently. I am running the latest version in Webhooks. I did try to revert to an older version but that didn't work either.
Ok this was a very stupid issue I didn't catch. The stripe account that I set up today was in an older version and there was an update available. I didn't catch that because I was working in test mode and you can only upgrade in live mode.
So, after upgrading, everything works perfectly. Hours of wasted time and something so simple.

get auth0 user metadata as part of user information

I don't find how to get the user_metadata from the Auth0 Authentication api:
$auth0Api = new Authentication($domain, $clientId, $clientSecret);
$tokenInfo = $auth0Api->login([
'username' => $username,
'password' => $password,
'realm' => 'Username-Password-Authentication',
]);
$accessToken = $tokenInfo["access_token"];
$info = $auth0Api->userinfo($accessToken);
The final $info array only contains the main user information, no meta_data at all. I tried creating a rule from the Auth0 side to add stuff to the user itself (doing user.customtag = 'helloworld' for example) and the customization does not show either.
User info retrieved:
{
"sub":"auth0|XXXX",
"name":"XXXX#XXXX.com",
"nickname":"XXXX",
"picture":"XXXX.png",
"updated_at":"2017-03-31T08:50:59.819Z",
"email":"XXXX#XXXX.com",
"email_verified":true
}
The "Raw Json" tab of that user shows something much more complete:
{
"email": "XXXX#XXXX.com",
"email_verified": true,
"user_id": "auth0|XXXX",
"picture": "XXXX.png",
"nickname": "XXXX",
"identities": [
{
"user_id": "XXXX",
"provider": "auth0",
"connection": "Username-Password-Authentication",
"isSocial": false
}
],
"updated_at": "2017-03-31T08:50:59.819Z",
"created_at": "2017-03-23T16:03:47.075Z",
"name": "XXXX",
"user_metadata": {
"languageCode": "EN"
},
"last_ip": "XXXX",
"last_login": "XXXX",
"logins_count": XXXX,
"blocked_for": [],
"guardian_enrollments": []
}
How is it supposed to work?
Environment:
composer: "auth0/auth0-php": "~5.0"
php 7.1
Auth0 Free account
Try starting up your application locally, then update the following URL with your own settings and paste it into a web browser:
https://YOUR_TENANT.auth0.com/authorize?client_id=YOUR_CLIENT_ID&response_type=code&scope=openid profile&redirect_uri=YOUR_REDIRECT_URI&nonce=12345
This should at least ensure you are making a request with right scopes etc. You should also ensure you have a User Profile with some "metadata" assigned if you are expecting to read that data post authentication of course ;)

Notifications using Twitch API

I'm currently creating a Twitch notification web app in PHP.
For the moment, the authentication works fine :
Client wants use the app -> redirected on Twitch website to accept asked scopes -> redirected on my app website with a "code" parameter -> "code" sent by curl request -> response containing the accessToken.
I stored accessToken and client username in $_COOKIE and $_SESSION variable (set $_COOKIE doesn't work on all web browsers).
After that I have to check (in real-time ?) if the user has new followers. Certains web applications, as TNotifier, exists and do this very well... But I don't know how.
In the Twitch API, we have only for the follows request the possibility to list all of these followers. I thought directly i will have to make requests, again and again (with one second of delay), and compare the new request with the last one... But i think there 's an other way to make that ?
Here is the follows request :
curl -H 'Accept: application/vnd.twitchtv.v2+json' \
-X GET https://api.twitch.tv/kraken/channels/test_user1/follows
And the JSON response :
{
"_links": {
"next": "https://api.twitch.tv/kraken/channels/test_user1/follows?limit=25&offset=25",
"self": "https://api.twitch.tv/kraken/channels/test_user1/follows?limit=25&offset=0"
},
"follows": [
{
"_links": {
"self": "https://api.twitch.tv/kraken/users/test_user2/follows/channels/test_user1"
},
"user": {
"_links": {
"self": "https://api.twitch.tv/kraken/users/test_user2"
},
"staff": false,
"logo": null,
"display_name": "test_user2",
"created_at": "2013-02-06T21:21:57Z",
"updated_at": "2013-02-13T20:59:42Z",
"_id": 40091581,
"name": "test_user2"
}
},
...
]
}
Here is my code, but still thinking a better way exists...
$uknown=""; //to initialize my loop function.
comparaison($uknown);
function comparaison($u){
$options = array(
'http' => array(
'header' => 'Accept: application/vnd.twitchtv.v2+json',
'method' => 'GET',
)
);
$context = stream_context_create($options);
$result = file_get_contents('https://api.twitch.tv/kraken/channels/test_user1/follows', false, $context);
$decode_result = json_decode($result, true);
$follow=$decode_result['follows'][0];
$user=$follow['user'];
$last_follower=$user['display_name'];
if($last_follower != $u){
haveANewFollower($last_follower);
}
comparaison($last_follower);
}
Is it possible TNotifier use another way to check new followers ?
It's the only way, as there's no push way to do followers, so you have to rely on pulling. For subscribers there would be the possibility to listen for chat messages for new subscribers, but as this does not work for followers, you can only rely on the pull method using the kraken api.

Google Drive SDK: Inserting a file results in Untitled in PHP

I do know about the two previous posts:
PHP Google Drive API - File Upload Only As "Untitled"-File Or Just Without Content
Google Drive PHP SDK saves an Untitled file
But apart from the answer 'are you sure you're using the latest release', none of the askers have come back to say if yes or no or if they've managed to find an answer.
Because I'm doing the same thing as them, I'm using the latest apiDriveService.php with the last revision dated from June 2012.
The data is correctly found but when you arrive at the insert line, clearly, something wrong happens.
And I don't understand why for the SDK php example, it seems to go correctly.
Is this a problem in the Google Api Console? Or do I need to encode the data in something special?
EDIT: in the apiDriveService file, I can see this line:
$this->files = new FilesServiceResource($this, $this->serviceName, 'files', json_decode('{"methods": {
"insert": {"scopes": ["https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/drive.file"],
"parameters": {"convert": {"default": "false", "type": "boolean", "location": "query"}, "targetLanguage": {"type": "string", "location": "query"}, "sourceLanguage": {"type": "string", "location": "query"}, "ocrLanguage": {"type": "string", "location": "query"}, "pinned": {"default": "false", "type": "boolean", "location": "query"}, "ocr": {"default": "false", "type": "boolean", "location": "query"}, "timedTextTrackName": {"type": "string", "location": "query"}, "timedTextLanguage": {"type": "string", "location": "query"}}, "supportsMediaUpload": true, "request": {"$ref": "File"}, "mediaUpload": {"maxSize": "10GB", "accept": ["*/*"], "protocols": {"simple": {"path": "/upload/drive/v2/files", "multipart": true}, "resumable": {"path": "/resumable/upload/drive/v2/files", "multipart": true}}}, "id": "drive.files.insert", "httpMethod": "POST", "path": "files", "response": {"$ref": "File"}}, ...);
In the parameters I'm sending, there is data and mimetype:
$created = $apiService->files->insert($driveFile, array('data' => $data,'mimeType' => $mimeType));
And in the insert function, there is an array_merge with data and mimetype:
public function insert(DriveFile $postBody, $optParams = array()) {
$params = array('postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('insert', array($params));
if ($this->useObjects()) {
return new DriveFile($data);
} else {
return $data;
}
}
I don't find them in the insert part of the line I've mentionned above. Is it tied to that?
Just check out the current API Client from Google SVN.
http://code.google.com/p/google-api-php-client/source/checkout
We had the same problem but after doing an svn checkout, it magically worked and thanks to Alain and Claudio for their swift response on this.

Categories