I'm currently trying to get a list of all users inside the domain and the logic I'm using is the following:
$service = new Google_Service_Directory($client);
$optParams = array(
'customer' => 'my_customer',
'maxResults' => 500,
'orderBy' => 'email',
);
$results = $service->users->listUsers($optParams);
$users = $results->getUsers();
foreach($users as $user) {
$usersemails = $user->getPrimaryEmail();
echo $usersemails.'<br>';
}
The problem is I only get a max of 500 users. I figure out that I have to use the next page token so I tried this:
$service = new Google_Service_Directory($client);
$optParams = array(
'customer' => 'my_customer',
'maxResults' => 500,
'orderBy' => 'email',
'pageToken' => NULL,
);
$results = $service->users->listUsers($optParams);
$pageToken = $results->getNextPageToken();
$users = $results->getUsers();
while($pageToken);
foreach($users as $user) {
$usersemails = $user->getPrimaryEmail();
echo $usersemails.'<br>';
}
But I'm getting the following message:
504 Gateway Time-out. The server didn't respond in time.
Is there a problem with the code I'm using or is this a problem with the server?
After checking many times I was able to find out that the problem was that I was not properly writing the code. I have modified my code and now it works fine. In case anybody else goes through the same problem perhaps this might help. This is the final code:
$service = new Google_Service_Directory($client);
$pageToken = NULL;
$optParams = array(
'customer' => 'my_customer'
);
try {
do {
if ($pageToken){
$optParams['pageToken'] = $pageToken;
}
$results = $service->users->listUsers($optParams);
$pageToken = $results->getNextPageToken();
$users = $results->getUsers();
foreach($users as $user) {
$usersemails = $user->getPrimaryEmail();
echo $usersemails.'<br>';
}
} while($pageToken);
} catch (Exception $e) {
print 'An error occurred: ' . $e->getMessage();
}
Related
I'm using AlexaCRM and I tried sending a lead with a lookup field. I don't have any problems with other fields. This is my code:
use AlexaCRM\CRMToolkit\Client as OrganizationService;
use AlexaCRM\CRMToolkit\Settings;
use AlexaCRM\CRMToolkit\Entity\EntityReference;
try {
$options = [
'serverUrl' => 'urldelcrm',
'username' => 'user',
'password' => 'pass',
'authMode' => 'OnlineFederation',
];
$serviceSettings = new Settings( $options );
$service = new OrganizationService( $serviceSettings);
$lead = $service->entity('lead');
$lead->firstname = $data['fields']['name'];
//...Lookup field:
$guid = "1111111-1111-111-11-11" // guid campaign
$lead->campaignid = new EntityReference('campaign', $guid );
$leadId = $lead->create();
} catch (\Exception $e) {
// echo $e->getMessage();
}
But when I peek in the CRM the field, "campaignid" is empty. Then I printed the $lead variable and the "campaignid" is empty too.
Also I tried,
$lead->campaignid = $service->entity( 'campaign', $guid );
Instead of EntityReference('campaign', $guid).
What is wrong here?
Here is my code:
public static function test(){
try{
$apiContext = ApiContext::create(
'test', 'bcy', 'v1',
new SimpleTokenCredential('my_token'),
array( 'mode' => 'sandbox','log.LogEnabled' => false, 'log.FileName' => 'BlockCypher.log', 'log.LogLevel' => 'DEBUG') );
$input = new \BlockCypher\Api\TXInput();
$input->addAddress("input_address");
$output = new \BlockCypher\Api\TXOutput();
$output->addAddress("output_address ");
$output->setValue(1000); // Satoshis
/// Tx
$tx = new \BlockCypher\Api\TX();
$tx->addInput($input);
$tx->addOutput($output);
$request = clone $tx;
$txClient = new TXClient($apiContext);
try {
$output = $txClient->create($tx);
} catch (Exception $ex) {
dd("Created TX", "TXSkeleton", null, $request, $ex);
exit(1);
}
dd("Created TX", "TXSkeleton", $output->getTx()->getHash(), $request, $output);
return $output;
}
catch (\BlockCypher\Exception\BlockCypherConnectionException $ex) {
echo $ex->getData();
die;
}
}
This is what I use to create CreateTransaction api but when I change the mode from bcy to btc it gives error for checking url get/post
code source :: click here
And here the response I'm getting also it came in catch so it's a error I have create api for generate address and create input address from there and make account on block.io and make a address for out from there to use in this api beside from these my account on blockcypher in free and nothing purchase in it
{
"errors":[
{
"error":"Unable to find a transaction to spend for address CCrB7dvBT1bqNfWxupKPH9v8yN7xukmqUF."
},
{
"error":"Error building transaction: Address 33cjwDAyNeAPVUMWqh9hdRxdmwdTE4kyTx is of unknown size.."
},
{
"error":"Not enough funds after fees in 0 inputs to pay for 0 outputs, missing -22200."
},
{
"error":"Error validating generated transaction: Transaction missing input or output."
}
],
"tx":{
"block_height":-1,
"block_index":-1,
"hash":"d21633ba23f70118185227be58a63527675641ad37967e2aa461559f577aec43",
"addresses":[
],
"total":0,
"fees":0,
"size":10,
"preference":"low",
"relayed_by":"116.193.163.150",
"received":"2017-11-14T10:20:43.757719705Z",
"ver":1,
"double_spend":false,
"vin_sz":0,
"vout_sz":0,
"confirmations":0,
"inputs":[
],
"outputs":[
]
}
}
I am working it on test purpose so use test main
I have installed it from github
I find one way of doing this thing here is my code
<?php
try
{
$apiContext = ApiContext::create(env('BlockCypher_net') , env('BlockCypher_cn') , env('BlockCypher_v') , new SimpleTokenCredential(env('BlockCypher_key')) , array(
'log.LogEnabled' => true,
'log.FileName' => 'BlockCypher.log',
'mode' => 'sandbox',
'log.LogLevel' => 'DEBUG'
));
$input = new BlockCypherApiTXInput();
$input->addAddress($user['address']);
$output = new BlockCypherApiTXOutput();
$output->addAddress($data['address12']);
$value_btc = 100000000 * ($data['btc12'] + 1 * ($data['btc12'] / 100));
// dd($value_btc);
$output->setValue($value_btc);
$tx = new BlockCypherApiTX();
$tx->addInput($input);
$tx->addOutput($output);
$request = clone $tx;
$params = array(
'includeToSignTx' => 1,
'script_type' => 'mutlisig-n-of-m',
);
$txClient = new TXClient($apiContext);
try
{
$txSkeleton = $txClient->create($tx, $params);
$privateKeys = array(
$user['private']
);
$txSkeleton = $txClient->sign($txSkeleton, $privateKeys);
$txSkeleton = $txClient->send($txSkeleton);
return array(
'success' => 0
);
// dd($txSkeleton->getTx()->getHash());
}
catch(BlockCypherExceptionBlockCypherConnectionException $ex)
{
return array(
'success' => 0,
'msg' => $ex->getData()
);
}
return $txSkeleton->getTx()->getHash();
}
catch(BlockCypherExceptionBlockCypherConnectionException $ex)
{
return array(
'success' => 0,
'msg' => $ex->getData()
);
}
it's work for me hope it will help you drop comment if get any error.
I have this code and trying to var dump my res but am not getting anything, i have installed minishlink web push in my root directory and this is my code plz check
send_push.php
require __DIR__ . '/vendor/autoload.php';
use Minishlink\WebPush\WebPush;
// CONNECT TO THE DATABASE
include_once("php_includes/conn.php");
session_start();
if (isset($_SESSION['user_id'])) {
$userid = $_SESSION['user_id'] ;
}
$sam= "SELECT endpoint,p256dh,auth FROM endpointurl WHERE userid = ? ";
$stmt=$conn->prepare($sam);
$stmt->bind_param('i',$userid);
$stmt->execute();
$stmt->bind_result($endpoint,$p256dh,$key);
$stmt->fetch();
$stmt->close();
$auth = array(
'VAPID' => array(
'subject' => 'https://*****.com',
'publicKey' => '*********',
'privateKey' => '*************', // in the real world, this would be in a secret file
),
);
//exit($subscriber['endpoint'].' : '.$subscriber['auth'].' : '.$subscriber['p256dh']);
$webPush = new WebPush($auth);//some problem here
echo $endpoint ;//not even echoing this
$res = $webPush->sendNotification(
$endpoint,
'{"title":"hello","msg":"yes it works","icon":"/icons/cam.png","badge":"/icons/cam.png","url":"https://*****.com"}',
str_replace(['_', '-'], ['/', '+'],$p256dh),
str_replace(['_', '-'], ['/', '+'],$key),
true
);
var_dump($res) ;
it is not even echoing $endpoint after creating a new webpush();
Hi maybe u can try to put this foreach after sendNotification function.
foreach ($webPush->flush() as $report) {}
You can leave the foreach empty or you can debug the foreach if you want
foreach ($webPush->flush() as $report) {
$endpoint = $report->getRequest()->getUri()->__toString();
if ($report->isSuccess()) {
$result = "[v] Message sent successfully for subscription {$endpoint}.";
} else {
$result = "[x] Message failed to sent for subscription {$endpoint}: {$report->getReason()}";
}
}
Using the SoundCloud PHP wrapper, I can successfully update a song’s title, privacy, genre, tags. But I can't figure out what I'm doing wrong with regard to the streamable property. When I send a true value to track[streamable], it remains false.
Here’s what I’m working with:
<?php
require_once 'Soundcloud.php';
require './globaldatabase.php';
$access_token = $_POST['access_token'];
$trackid = $_POST['trackid'];
$title = $_POST['title'];
$genre = $_POST['genre'];
$tag_list = $_POST['tag_list'];
$privacy = $_POST['privacy'];
$release = $_POST['release'];
$streamable = true;
if($privacy=='disabled'){
$streamable = false;
$privacy = 'private';
}
$client = new Services_Soundcloud($sc_clientid, $sc_clientsecret);
$client->setAccessToken($access_token);
try {
$track = json_decode($client->get('tracks/'.$trackid));
$client->put('tracks/' . $track->id, array(
'track[title]' => $title,
'track[genre]' => $genre,
'track[tag_list]' => $tag_list,
'track[sharing]' => $privacy,
'track[release]' => $release,
'track[streamable]' => $streamable
));
$return = $client->get('tracks/' . $track->id);
$return_array[] = json_decode($return);
echo json_encode($return_array);
} catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
exit($e->getMessage());
}
?>
Try setting the track attribute api_streamable to true.
All the question about examples are like 2 years old, and I can't find ANY working example for current API client version (https://github.com/google/google-api-php-client). Every single one is missing something or throwing exception....
Could anybody provide working example? There is no documentation AT ALL, anywhere.
This is the most working one:
<?php
require_once 'inc/google-api/autoload.php'; // or wherever autoload.php is located
$client = new Google_Client();
$client->setApplicationName("whatever");
$client->setDeveloperKey("some key");
$service = new Google_Service_Bigquery($client);
$postBody = "[
'datasetReference' => [
'datasetId' => $datasetId,
'projectId' => $projectId,
],
'friendlyName' => $name,
'description' => $description,
'access' => [
['role' => 'READER', 'specialGroup' => 'projectReaders'],
['role' => 'WRITER', 'specialGroup' => 'projectWriters'],
['role' => 'OWNER', 'specialGroup' => 'projectOwners'],
],
]";
$dataset = $service->datasets->insert($projectId, new Google_Dataset($postBody));
$postBody = "[
'tableReference' => [
'projectId' => 'test_project_id',
'datasetId' => 'test_data_set',
'tableId' => 'test_data_table'
]
]";
$table = $service->tables->insert($projectId, $datasetId, new Google_Table($postBody));
?>
But I am getting Fatal errors about Google_Dataset and Google_Table not defined...
Here is a code that
properly creates a Google_Client
runs a job async
displays the running job ID and status
You need to have:
service account created (something like ...#developer.gserviceaccount.com)
your key file (.p12)
service_token_file_location (writable path to store the JSON from the handshake, it will be valid for 1h)
code sample:
function getGoogleClient($data = null) {
global $service_token_file_location, $key_file_location, $service_account_name;
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$old_service_token = null;
$service_token = #file_get_contents($service_token_file_location);
$client->setAccessToken($service_token);
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name, array(
'https://www.googleapis.com/auth/bigquery',
'https://www.googleapis.com/auth/devstorage.full_control'
), $key
);
$client->setAssertionCredentials($cred);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
$service_token = $client->getAccessToken();
}
return $client;
}
$client = getGoogleClient();
$bq = new Google_Service_Bigquery($client);
/**
* #see https://developers.google.com/bigquery/docs/reference/v2/jobs#resource
*/
$job = new Google_Service_Bigquery_Job();
$config = new Google_Service_Bigquery_JobConfiguration();
$config->setDryRun(false);
$queryConfig = new Google_Service_Bigquery_JobConfigurationQuery();
$config->setQuery($queryConfig);
$job->setConfiguration($config);
$destinationTable = new Google_Service_Bigquery_TableReference();
$destinationTable->setDatasetId(DATASET_ID);
$destinationTable->setProjectId(PROJECT_ID);
$destinationTable->setTableId('table1');
$queryConfig->setDestinationTable($destinationTable);
$sql = "select * from publicdata:samples.github_timeline limit 10";
$queryConfig->setQuery($sql);
try {
// print_r($job);
// exit;
$job = $bq->jobs->insert(PROJECT_ID, $job);
$status = new Google_Service_Bigquery_JobStatus();
$status = $job->getStatus();
// print_r($status);
if ($status->count() != 0) {
$err_res = $status->getErrorResult();
die($err_res->getMessage());
}
} catch (Google_Service_Exception $e) {
echo $e->getMessage();
exit;
}
//print_r($job);
$jr = $job->getJobReference();
//var_dump($jr);
$jobId = $jr['jobId'];
if ($status)
$state = $status['state'];
echo 'JOBID:' . $jobId . " ";
echo 'STATUS:' . $state;
You can grab the results with:
$res = $bq->jobs->getQueryResults(PROJECT_ID, $_GET['jobId'], array('timeoutMs' => 1000));
if (!$res->jobComplete) {
echo "Job not yet complete";
exit;
}
echo "<p>Total rows: " . $res->totalRows . "</p>\r\n";
//see the results made it as an object ok
//print_r($res);
$rows = $res->getRows();
$r = new Google_Service_Bigquery_TableRow();
$a = array();
foreach ($rows as $r) {
$r = $r->getF();
$temp = array();
foreach ($r as $v) {
$temp[] = $v->v;
}
$a[] = $temp;
}
print_r($a);
You can see here the classes that you can use for your other BigQuery calls. When you read the file, please know that file is being generated from other sources, hence it looks strange for PHP, and you need to learn reading it in order to be able to use the methods from it.
https://github.com/google/google-api-php-client/blob/master/src/Google/Service/Bigquery.php
like:
Google_Service_Bigquery_TableRow