Google Chat API. Can’t create space. Method not found - php

I'm trying to create a google chat space via making a post request to https://chat.googleapis.com/v1/spaces with Guzzle.
$scopes = [
'https://www.googleapis.com/auth/chat.spaces.create',
'https://www.googleapis.com/auth/chat.bot'
];
// create middleware
$middleware = ApplicationDefaultCredentials::getMiddleware($scopes);
$stack = HandlerStack::create();
$stack->push($middleware);
// create the HTTP client
$client = new Client([
'headers' => ['Content-Type' => 'application/json'],
'handler' => $stack,
'base_uri' => 'https://www.googleapis.com',
'auth' => 'google_auth' // authorize all requests
]);
// make the request
$response = $client->post( 'https://chat.googleapis.com/v1/spaces', [
RequestOptions::JSON => [
'name' => 'ABCDEFG',
'spaceType' => 'DIRECT_MESSAGE',
'threaded' => false,
'displayName' => 'TestSpace'
],
]);
In response I'm getting:
Client error: `POST https://chat.googleapis.com/v1/spaces` resulted in a `404 Not Found` response:
{
"error": {
"code": 404,
"message": "Method not found.",
"status": "NOT_FOUND"
}
}
But if I change the body of the request and add some new invalid fields like this:
$response = $client->post( 'https://chat.googleapis.com/v1/spaces', [
RequestOptions::JSON => [
'name' => 'ABCDEFG',
'spaceType' => 'DIRECT_MESSAGE',
'threaded' => false,
'displayName' => 'TestSpace',
'foo' => 'bar', //added invalid field
],
]);
I'm getting the next response:
Client error: `POST https://chat.googleapis.com/v1/spaces` resulted in a `400 Bad Request` response:
{
"error": {
"code": 400,
"message": "Invalid JSON payload received. Unknown name \"foo\" at 'space': Cannot find field.",
"status": "INVALID_ARGUMENT",
"details": [
{
"#type": "type.googleapis.com/google.rpc.BadRequest",
"fieldViolations": [
{
"field": "space",
"description": "Invalid JSON payload received. Unknown name \"foo\" at 'space': Cannot find field."
}
]
}
]
}
}
docs:
https://developers.google.com/chat/api/reference/rest/v1/spaces/create
What’s wrong with my original request?
Thanks.

The spaces.create documentation explains this at the top of the page:
Developer Preview: Available as part of the Google Workspace Developer Preview Program, which grants early access to certain features.
This means that the method is only available for users in Google's Developer Preview Program, which seems kind of like a closed beta for some developer features. The link above has a form that you can fill out to join this program, though do note that you also need to be part of the Google Cloud Partner Advantage program to apply.
In short, the method was released not long ago, and is not currently available for everyone. There's also an official blog post explaining this. It may become public in the future, so you'll have to either wait or fill out the applications to become a partner and then join the developer preview.
If you happen to be part of the program already and are still having issues you probably won't find answers among us commoners. You'd want to check out the Partner Advantage support to make sure that the features were enabled for your domain. The developer program documentation above also has a link to the issue tracker to send feedback about this API. You'll only be able to do this as a member, of course.

Related

Paymongo can't disable a webhook

I am trying to disable a webhook of Paymongo via the web console, but it seems I can not disable the webhook. When I do so, the interface shows the error like so:
{
"errors": [
{
"code": "resource_processing_state",
"detail": "Webhook with id hook_L0r3mIp5umD0L0r5itAm3t is still being processed."
}
]
}
It also has a 400 HTTP status code and its PHP code look like so:
<?php
require_once('vendor/autoload.php');
$client = new \GuzzleHttp\Client();
$response = $client->request('POST', 'https://api.paymongo.com/v1/webhooks/hook_L0r3mIp5umD0L0r5itAm3t/disable', [
'headers' => [
'accept' => 'application/json',
'authorization' => 'Basic someBase64encodedStringOfAKey',
],
]);
echo $response->getBody();
Note: The shown codes above don't contain the exact credentials. I edited these before posting here for privacy reasons.
What does it mean by "Webhook with id hook_L0r3mIp5umD0L0r5itAm3t is still being processed."?

How to create course work for a Google Classroom project using API in php

I want to create a course work(Assignment) as a course teacher using Google Classroom API to itself for a project in PHP. To create an assignment which correct code I wrote? Give me some suggestions with PHP code for creating an assignment.
I've added some code to the quickstart.php file.
Code:
$client = getClient();
$courseId = '394192735087';
$service = new Google_Service_Classroom($client);
$post_body = new Google_Service_Classroom_CourseWork(array(
'workType' => 'ASSIGNMENT',
'title' => 'Quiz-5',
'description' => 'where you add up by the number of numbers',
'state' => 'PUBLISHED',
'maxPoints' => 100,
'associatedWithDeveloper' => true,
'assigneeMode' => 'ALL_STUDENTS',
'submissionModificationMode' => 'SUBMISSION_MODIFICATION_MODE_UNSPECIFIED'
));
$service->courses_courseWork->create($courseId, $post_body);
But when I run this code in quickstart.php at localhost the following problems can be seen.
Fatal error: Uncaught Google\Service\Exception: {
"error": {
"code": 400,
"message": "Invalid JSON payload received. Unknown name \"name\" at 'course_
work': Cannot find field.",
"errors": [
{
"message": "Invalid JSON payload received. Unknown name \"name\" at 'cou
rse_work': Cannot find field.",
"reason": "invalid"
}
],
"status": "INVALID_ARGUMENT"
}
}
in C:\xampp\htdocs\api\vendor\google\apiclient\src\Http\REST.php:128
How can I solved it ?

GuzzleHTTP returns 404 on existing page

My Guzzle POST request to https://api.scarif.dev/auth gives back a 404, while the page exists through Postman, or browser, or javascript. It should return a 200 with a 401 message, but Guzzle gives back a 404. In both POST and GET mode that is.
I've tried multiple Client setups, including different headers and disabling SSL verification, but without any success. Now I've copied the exact same headers that made it work in postman, but still no success.
I've been searching through google and stackoverflow, but couldn't find an answer that fixed my problem.
Request in PHP:
<?php
$client = new Client([
'header' => [
'Accept' => 'application/json',
'Content-Type' => 'application/x-www-form-urlencoded'
],
'verify' => false
]);
$response = $client->request('POST', 'https://api.scarif.dev/auth', [
'form_params' => []
]);
echo $response->getBody()->getContents();
?>
Expected result:
{
"detail": "https://login.scarif.dev",
"status": 401,
"title": "Unauthorized",
"type": "http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html"
}
Actual result:
Fatal error: Uncaught GuzzleHttp\Exception\ClientException: Client
error: POST https://api.scarif.dev/auth resulted in a 404 Not
Found response:
404 Not Found Not Found
(truncated...) in
/home/admin/domains/login.scarif.dev/framework/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php:113
Stack trace: #0
/home/admin/domains/login.scarif.dev/framework/vendor/guzzlehttp/guzzle/src/Middleware.php(66):
GuzzleHttp\Exception\RequestException::create(Object(GuzzleHttp\Psr7\Request),
Object(GuzzleHttp\Psr7\Response)) #1
/home/admin/domains/login.scarif.dev/framework/vendor/guzzlehttp/promises/src/Promise.php(203):
GuzzleHttp\Middleware::GuzzleHttp{closure}(Object(GuzzleHttp\Psr7\Response))
2 /home/admin/domains/login.scarif.dev/framework/vendor/guzzlehttp/promises/src/Promise.php(156):
GuzzleHttp\Promise\Promise::callHandler(1,
Object(GuzzleHttp\Psr7\Response), Array) #3
/home/admin/domains/login.scarif.dev/framework/ven in
/home/admin/domains/login.scarif.dev/framework/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php
on line 113
API endpoint controller:
<?php
namespace Controller;
use Core\Config;
use Core\Request;
use Core\Response;
use Model\Token;
use Model\User;
use MongoDB\BSON\UTCDateTime;
class AuthController extends Controller
{
public function view(User $user, Token $token)
{
extract(Request::getPostData());
if (isset($access_token) && !empty($access_token)) {
$_token = $token->getTokenByToken($access_token);
if (
$_token['type'] !== Token::TYPE_ACCESS_TOKEN ||
$_token['expires_on'] <= new UTCDateTime()
) {
return $this->view->display('json', [
'payload' => Response::apiResponse(
$this->config->get('url.login'), 401
)
]);
}
$token->delete($_token['_id']);
$newToken = $token->create(Token::TYPE_ACCESS_TOKEN, $_token['user_id']);
return $this->view->display('json', [
'payload' => Response::apiResponse($newToken['token'])
]);
}
if (!isset($email) || !isset($password) || empty($email) || empty($password)) {
return $this->view->display('json', [
'payload' => Response::apiResponse(
$this->config->get('url.login'), 401
)
]);
}
if (!$user->checkCredentials($email, $password)) {
return $this->view->display('json', [
'payload' => Response::apiResponse(
"The email address or password you've entered is invalid. Please check your entry and try again.",
422
)
]);
}
$user = $user->getUserByEmail($email);
$token = $token->create(Token::TYPE_ACCESS_TOKEN, $user['_id']);
return $this->view->display('json', [
'payload' => Response::apiResponse($token['token'])
]);
}
}
It seems like the issue is coming from the API you are consuming. When using your code with a different url it works just fine:
$client = new Client([
'header' => [
'Accept' => 'application/json',
'Content-Type' => 'application/x-www-form-urlencoded'
],
'verify' => false
]);
$response = $client->request('POST', 'https://jsonplaceholder.typicode.com/posts', [
'form_params' => []
]);
echo $response->getBody()->getContents();
Could you show the code for the API endpoints?
I had the same issue and was looking for solutions until I landed here. Didn't get any help online though and solutions of other people didn't work for me but later I solved myself through extensive debugging and I am sharing the solution in a hope it might help someone else in the future.
Scenario: In my case I had an API gateway and client (Postman in my case) was making request to the API gateway and gateway in turn was making request to a microservice using Guzzle 7 in Laravel 8. I used to pass all headers I received from the client to microservice as is and that was causing 404 error. When I changed that and passed only my own headers in the request to the microservice, there was light and 404 was gone.
These were default headers of Postman and I was passing in the request as is:
{
"authorization": [
"Bearer eyJ0eXAiOiJKV1 .."
],
"user-agent": [
"PostmanRuntime/7.29.0"
],
"accept": [
"*/*"
],
"postman-token": [
"ca180f3a-ec65-4212-bd9f-dc294846dc65"
],
"host": [
"sagateway.com"
],
"accept-encoding": [
"gzip, deflate, br"
],
"connection": [
"keep-alive"
]
}
I removed all of it and only passed one thing in the header:
['Authorization' => "<Key Here>"]
It then worked fine and I took a breath of relief after a few days of continuous googling.

yii2 rest api exception handling

I am using yii2 rest api module in which controller class extends an ActiveController and i have a problem dealing with the error exception . i need a proper json response when HTTP status code that are used by the Yii REST framework like 500 , 400. If i try a wrong method call on access api it show a exception object
object(yii\web\NotFoundHttpException)#170 (8) { ["statusCode"]=> int(404)
In my config/main.php set the response
'response' => [
'class' => 'yii\web\Response',
'on beforeSend' => function ($event) {
$response = $event->sender;
if ($response->data !== null) {
$response->data = [
'success' => $response->isSuccessful,
'data' => $response->data,
];
$response->statusCode = 200;
}
},
]
It should display a msg like:
{
"status": 0,
"error_code": 400,
"message": "Bad request"
}
I have try to add the behaviour verbs in controller using this link : click here
My whole application is based on api so please help me for handling all kind of errors
Also depends on your server configs but usually you don't need any of that. this should be enough:
'response' => [
'format' => yii\web\Response::FORMAT_JSON,
'charset' => 'UTF-8',
],
Here is an output example using those configs: https://yii2-f4a.rhcloud.com/api/tags

Yii Google Webmaster Tools API sitemap submitting

I've searched far and wide and have come up with little to nothing on this problem. I've made a module for my Yii app that crawls my website and gathers links to generate a sitemap, I've even made it so that it can run on a cron.
Now I've hit the wall with Google Webmaster Tools API and it's lack of information on how to implement it with OAuth2 for sitemap submission.
Every time I've tried to submit the sitemap I got this response back:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "required",
"message": "Login Required",
"locationType": "header",
"location": "Authorization"
}
],
"code": 401,
"message": "Login Required"
}
}
I would very much appreciate any pointers in any direction.
Maybe this extension can help you:
http://www.yiiframework.com/extension/jgoogleapi/
I'm not sure which is the API for sitemaps and what are its methods but that extension would help you Login to google in "Service" mode that won't need your browser to interact with the login.
You should also before create your application in Google console and then create a service account user type for it.
A paste of my config file when using this extension with Google Analytics:
<?php
/*
* How to obtain a Service Account:
* https://developers.google.com/accounts/docs/OAuth2ServiceAccount
*
*
* (403) User does not have any Google Analytics account.
* http://stackoverflow.com/a/13167988/115050
*
*
*/
return array(
'class' => 'ext.JGoogleAPI.JGoogleAPI',
//Default authentication type to be used by the extension
'defaultAuthenticationType'=>'serviceAPI',
//Account type Authentication data
'serviceAPI' => array(
'clientId' => '...',
'clientEmail' => '...',
'keyFilePath' => dirname(__FILE__).'/../extensions/JGoogleAPI/keys/Analytics-a0e8e345f273.p12',
),
/*
//You can define one of the authentication types or both (for a Service Account or Web Application Account)
webAppAPI = array(
'clientId' => 'YOUR_WEB_APPLICATION_CLIENT_ID',
'clientEmail' => 'YOUR_WEB_APPLICATION_CLIENT_EMAIL',
'clientSecret' => 'YOUR_WEB_APPLICATION_CLIENT_SECRET',
'redirectUri' => 'YOUR_WEB_APPLICATION_REDIRECT_URI',
'javascriptOrigins' => 'YOUR_WEB_APPLICATION_JAVASCRIPT_ORIGINS',
),
*/
'simpleApiKey' => 'AIzaSyAx63Ht-0XmuLdp0-j9zVREKNsCyqXgeUA',
//Scopes needed to access the API data defined by authentication type
'scopes' => array(
'serviceAPI' => array(
'drive' => array(
'https://www.googleapis.com/auth/drive.file',
),
'Analytics'=>array(
'https://www.googleapis.com/auth/analytics.readonly',
),
),
'webappAPI' => array(
'drive' => array(
'https://www.googleapis.com/auth/drive.file',
),
),
),
//Use objects when retriving data from api if true or an array if false
'useObjects'=>false,
);
And how I'm using it:
$api = Yii::app()->JGoogleAPI->getService('Analytics');
$api->data_ga->get(...)
Your access code is invalid. Use refresh token to avoid getting error while authenticating google client.
use the below code:
$gClient->setAccessType("offline");// to get refresh token after expiration of access token
$gClient->setIncludeGrantedScopes(true);

Categories