Google Cloud DNS Services - entity.change parameter is required but missing - php

With the following code using Google's PHP API Client I am receiving this response.
Google_Service_Exception with message 'Error calling POST https://www.googleapis.com/dns/v1/projects/PROJECT-NAME/managedZones/DNSZONE/changes: (400) The 'entity.change' parameter is required but was missing.
Where PROJECT-NAME and DNSZONE are my project and zone.
$client_email = MYCLIENT;
$private_key = file_get_contents('config/credentials/KEY.p12');
$scopes = array('https://www.googleapis.com/auth/ndev.clouddns.readwrite');
$project = "PROJECT-NAME";
$managedZone = "DNSZONE";
$creds = new Google_Auth_AssertionCredentials($client_email,$scopes,$private_key);
$client = new Google_Client();
$client->setAssertionCredentials($creds);
$resource = new Google_Service_Dns_ResourceRecordSet();
$resource->kind = "dns#resourceRecordSet";
$resource->name = "testing.DNSZONE.net.";
$resource->rrdatas[] = "testing.otherhost.com.";
$resource->ttl = 800;
$resource->type = "CNAME";
$dns = new Google_Service_Dns($client);
$change = new Google_Service_Dns_Change();
$change->kind = "dns#change";
$change->setAdditions($resource);
$dns->changes->create($project,$managedZone,$change);
I am a bit confused as to how to set this parameter. Or where I am even am to define it.

Just for clarify what the answer is, setAdditions expects an array.
$change->setAdditions([ $resource ]);

Related

how do i authenticate against cybersource soap toolkit api on php

I have the following code on my index.php
<?php
// This sample demonstrates how to run a sale request, which combines an
// authorization with a capture in one request.
// Using Composer-generated autoload file.
require __DIR__ . '/vendor/autoload.php';
// Or, uncomment the line below if you're not using Composer autoloader.
//require_once(__DIR__ . '/lib/CybsSoapClient.php');
// Before using this example, you can use your own reference code for the transaction.
$referenceCode = 'holla';
$client = new CybsSoapClient();
$request = $client->createRequest($referenceCode);
// Build a sale request (combining an auth and capture). In this example only
// the amount is provided for the purchase total.
$ccAuthService = new stdClass();
$ccAuthService->run = 'true';
$request->ccAuthService = $ccAuthService;
$ccCaptureService = new stdClass();
$ccCaptureService->run = 'true';
$request->ccCaptureService = $ccCaptureService;
$billTo = new stdClass();
$billTo->firstName = 'John';
$billTo->lastName = 'Doe';
$billTo->street1 = '1295 Charleston Road';
$billTo->city = 'Mountain View';
$billTo->state = 'CA';
$billTo->postalCode = '94043';
$billTo->country = 'US';
$billTo->email = 'null#cybersource.com';
$billTo->ipAddress = '10.7.111.111';
$request->billTo = $billTo;
$card = new stdClass();
$card->accountNumber = '4111111111111111';
$card->expirationMonth = '12';
$card->expirationYear = '2020';
$request->card = $card;
$purchaseTotals = new stdClass();
$purchaseTotals->currency = 'USD';
$purchaseTotals->grandTotalAmount = '90.01';
$request->purchaseTotals = $purchaseTotals;
$reply = $client->runTransaction($request);
// This section will show all the reply fields.
print("\nRESPONSE: " . print_r($reply, true));
and the cybs.ini is like
merchant_id = "firefy"
transaction_key = "5430494897960177107046"
; Modify the URL to point to either a live or test WSDL file with the desired API version.
wsdl = "https://ics2wstest.ic3.com/commerce/1.x/transactionProcessor/CyberSourceTransaction_1.109.wsdl"
when i run the code on my local machine i get the following error messaage.
Fatal error: Uncaught SoapFault exception: [wsse:FailedCheck] Security Data : UsernameToken authentication failed. in C:\xampp\htdocs\cybersourceTest\index.php:50 Stack trace: #0 C:\xampp\htdocs\cybersourceTest\index.php(50): SoapClient->__call('runTransaction', Array) #1 {main} thrown in C:\xampp\htdocs\cybersourceTest\index.php on line 50
How do i know what caused the error above and how can i solve the above error.
I am trying to add payout api to my app and this is giving a headache right now.
Please guys help me out if anyone can.
The error “authentication failed” is saying your merchant_id and transaction_key are not correct.
Assuming that your merchant_id is correct your transaction_key is not the correct format. You can get a transaction_key by going to the business center at https://ebctest.cybersource.com then go to Account Management-> Transaction Security Keys -> Security Keys for the SOAP Toolkit API. Generate a key there.
I found out that i the url that i was pointing to was not valid or something but i fixed it by changing the endpoint of the wsdl from
wsdl="https://ics2wstest.ic3.com/commerce/1.x/transactionProcessor/CyberSourceTransaction_1.109.wsdl"
to
wsdl="https://ics2wstest.ic3.com/commerce/1.x/transactionProcessor/CyberSourceTransaction_1.151.wsdl"
That took care of everything that was wrong with the error that was popping up.

PHP Google Api Client SQL Admin not enable Auth IP

I have this code that updates my Google MySQL instance authorized IPs, connection is ok, the code prints me the current IP's but it cannot add a new IP to the settings I tried many ways but it still do not works it doesn't make any change to the Instance configuration.
$client = new Google_Client();
$client->setAuthConfig('../config/service-account.json');
$client->setApplicationName(env("APP_NAME"));
$projectName = env("GOOGLE_PROJECT_NAME");
$instanceName = env("SQL_INSTANCE_NAME");
$scopes = [
"https://www.googleapis.com/auth/sqlservice.admin",
"https://www.googleapis.com/auth/compute",
];
$client->addScope($scopes);
$sql = new Google_Service_SQLAdmin($client);
$sqlAdmin = new Google_Service_SQLAdmin_Settings($client);
$instanceSettings = $sql->instances->get($projectName, $instanceName)->getSettings();
$authNetworks = $instanceSettings->getIpConfiguration();
$newAuthNetwork = new Google_Service_SQLAdmin_AclEntry($client);
$newAuthNetwork->setName("tmp_ip_connection");
$newAuthNetwork->setKind("sql#aclEntry");
$authNetworks->setAuthorizedNetworks($newAuthNetwork);
$ipv4 = file_get_contents('https://api.ipify.org');
$newAuthNetwork->setValue($ipv4);
$ipConfiguration = new Google_Service_SQLAdmin_IpConfiguration($client);
$ipConfiguration->setIpv4Enabled(true);
$ipConfiguration->setAuthorizedNetworks([$newAuthNetwork]);
$instanceSettings->setIpConfiguration($ipConfiguration);
$sql->instances->get($projectName, $instanceName)->setSettings($instanceSettings);
//TODO why it is not working??
print_r($sql->instances->get($projectName, $instanceName)->getSettings()->getIpConfiguration()->getAuthorizedNetworks());
The main thing missing from yours is you never updated the instance after you made the change.
Working example:
$client = new Google_Client();
$client->setAuthConfig('../config/service-account.json');
$client->setApplicationName(env("APP_NAME"));
$projectName = env("GOOGLE_PROJECT_NAME");
$instanceName = env("SQL_INSTANCE_NAME");
$scopes = [
"https://www.googleapis.com/auth/sqlservice.admin",
"https://www.googleapis.com/auth/compute",
];
$client->addScope($scopes);
$sql = new Google_Service_SQLAdmin($client);
$instances = $sql->instances;
$instance = $instances->get('projectId', 'instanceId');
$networks = $instance->getSettings()->getIpConfiguration()->getAuthorizedNetworks();
$values = [];
foreach ($networks as $network) {
$values[$network->getName()] = $network;
}
$values['1.production'] = array_get($values, '1.production', clone head($values));
$external_ip = #file_get_contents('http://ipecho.net/plain');
$values['1.production']->setValue("$external_ip/32");
$values['1.production']->setName('1.production');
$instance->getSettings()->getIpConfiguration()->setAuthorizedNetworks(array_values($values));
$instances->update('projectId', 'instanceId', $instance);

Guzzle Sends HTTP request to Google API, server 500 error

I use Guzzle to send HTTP request to Gmail API.
This part keeps causing a server 500 error, why is that ?
$data = new stdClass;
$data-> 'topicName' ='projects/sample.com:sample/topics/topic';
$data-> 'labelIds' = ["INBOX"];
$data-> 'labelFilterAction' = 'include';
Full code:
require_once __DIR__.'/vendor/autoload.php';
$client = new Google_Client();
$client->setScopes("https://www.googleapis.com/auth/gmail.readonly");
putenv('GOOGLE_APPLICATION_CREDENTIALS=sample.json');
$client->useApplicationDefaultCredentials();
// returns a Guzzle HTTP Client
$httpClient = $client->authorize();
$data = new stdClass;
$data->'topicName' ='projects/sample.com:sample/topics/topic';
$data-> 'labelIds' = ["INBOX"];
$data-> 'labelFilterAction' = 'include';
$request = new GuzzleHttp\Psr7\Request('POST', 'https://www.googleapis.com/gmail/v1/users/post#sample.com/watch',['Content-type'=>'application/json'],$data);
$response = $httpClient->send($request);
var_dump($response);
You should not have single quotes around you $data object's properties.
It should be:
$data->topicName ='projects/sample.com:sample/topics/topic';
$data->labelIds = ["INBOX"];
$data->labelFilterAction = 'include';

Updating Google Calendar - Fatal error: Call to undefined function dateTime()

I am trying to update Google Calendar using the PHP API. I have successfully been able to create Google Calendar Events and automatically get the ID for the event, but when I try and update the event, I get this error:
PHP Fatal error: Call to undefined function dateTime() in public_html/googleapi/calendarupdate.php on line 45. It is referring to the line:
$event->setStart.dateTime($startdatetime);
Here is my current PHP Code for the error:
<?php
header('Content-type: application/json');
require_once __DIR__ . '/google-api-php-client/src/Google/autoload.php';
$summary = $_POST["summary"];
$location = $_POST["location"];
$description = $_POST["description"];
$startdatetime = $_POST["startdatetime"];
$enddatetime = $_POST["enddatetime"];
$clientemail = $_POST["clientemail"];
$privatekey = $_POST["privatekey"];
$useremail = $_POST["useremail"];
$calendarid = $_POST["calendarid"];
$client_email = $clientemail;
$private_key = file_get_contents($privatekey);
$scopes = array('https://www.googleapis.com/auth/calendar');
$user_to_impersonate = $useremail;
$credentials = new Google_Auth_AssertionCredentials(
$client_email,
$scopes,
$private_key,
'notasecret', // Default P12 password
'http://oauth.net/grant_type/jwt/1.0/bearer', // Default grant type
$user_to_impersonate
);
$client = new Google_Client();
$client->setAssertionCredentials($credentials);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion();
}
$service = new Google_Service_Calendar($client);
$event = $service->events->get($useremail, $calendarid);
$event->setSummary($summary);
$event->setLocation($location);
$event->setStart.dateTime($startdatetime);
$event->setStart.timeZone('America/Los_Angeles');
$event->setEnd.dateTime($enddatetime);
$event->setEnd.timeZone('America/Los_Angeles');
$event->setDescription($description);
$updatedEvent = $service->events->update($useremail, $event->getId(), $event);
echo json_encode($updatedEvent);
My PHP code is based off of Google's API Documentation found here.
Ok, I actually managed to figure it out. I just had to change the line:
$event->setStart.dateTime($startdatetime);
To This:
$event->start->setDateTime($startdatetime);
I do the same general thing for the end datetime, except where it says start, I just put end. Just tested it and it worked perfectly. The site that helped me out can be found here.

Dialogflow V2 API - How to pass context and/or payload [PHP]

I am trying to send context and payload to the Dialogflow V2 API. I am able to successfully send a queryString and get a response from my agent. However, I need to pass context and payload parameters with this query and I cannot seem to find ANY help on this for PHP. Please see my code below. I am able to create the context object and the payload object (atleast I think its created), but how do I pass it to the API?
Any help would be appreciated as I am very new to dialogflow and have been struggling with this for a few days now.
function detect_intent_texts($projectId, $text, $sessionId, $context, $parameters, $languageCode = 'en-US') {
// new session
$test = array('credentials' => 'client-secret.json');
$sessionsClient = new SessionsClient($test);
$session = $sessionsClient->sessionName($projectId, $sessionId ?: uniqid());
//printf('Session path: %s' . PHP_EOL, $session);
// create text input
$textInput = new TextInput();
$textInput->setText($text);
$textInput->setLanguageCode($languageCode);
$contextStruct = new Struct();
$contextStruct->setFields($context['parameters']);
$paramStruct = new Struct();
$paramStruct->setFields($parameters['parameters']);
$contextInput = new Context();
$contextInput->setLifespanCount($context['lifespan']);
$contextInput->setName($context['name']);
$contextInput->setParameters($contextStruct);
$queryParams = new QueryParameters();
$queryParams->setPayload($paramStruct);
// create query input
$queryInput = new QueryInput();
$queryInput->setText($textInput);
// get response and relevant info
$response = $sessionsClient->detectIntent($session, $queryInput); // Here I don't know how to send the context and payload
$responseId = $response->getResponseId();
$queryResult = $response->getQueryResult();
$queryText = $queryResult->getQueryText();
$intent = $queryResult->getIntent();
$displayName = $intent->getDisplayName();
$confidence = $queryResult->getIntentDetectionConfidence();
$fulfilmentText = $queryResult->getFulfillmentText();
$returnResponse = array(
'responseId' => $responseId,
'fulfillmentText' => $fulfilmentText
);
$sessionsClient->close();
return $returnResponse;
}
Just as it happens, the moment I post my question, I get a result.
Thanks to this post How to set query parameters dialogflow php sdk.
I added the following to my code and it worked.
Added
$optionalsParams = ['queryParams' => $queryParams];
Changed
$response = $sessionsClient->detectIntent($session, $queryInput, $optionalsParams);

Categories