I'm updating a PHP application to create new email accounts in Google (using the Google Directory Service). I have no problem creating the account, but so far I've been unable to use the Google Gmail Service to set the sendAsEmail attribute (so that the alias will show up in the "From"). Also, var_dump($createSendAsResult) in the snippet below does not produce any output. Any help would be appreciated. Thanks!
Here's my code:
//Create account in Google
function createGoogleAccount($server_name, $acc_user, $acc_password)
{
$clientDir = getClientDir($server_name);
$dirService = new Google_Service_Directory($clientDir);
$userInstance = new Google_Service_Directory_User();
$nameInstance = new Google_Service_Directory_UserName();
$nameInstance -> setGivenName('Generic');
$nameInstance -> setFamilyName($acc_user);
$userInstance -> setOrgUnitPath("/generic_email");
$userInstance -> setName($nameInstance);
$userInstance -> setHashFunction("MD5");
$domain = getDomain($server_name);
$primary_email = $acc_user . '#' . $domain;
$userInstance -> setPrimaryEmail($primary_email);
$userInstance -> setPassword(hash("md5", $acc_password));
$optParams = array( );
$error_msg = null;
try
{
$createUserResult = $dirService->users->insert($userInstance, $optParams);
var_dump($createUserResult);
}
catch (Google_IO_Exception $gioe)
{
$error_msg = "Error in connection: ".$gioe->getMessage();
}
catch (Google_Service_Exception $gse)
{
$error_msg = "Service Exception: ".$gse->getMessage();
}
addSendAs($server_name, $acc_user, $domain); return $error_msg;
}
function addSendAs($server_name, $acc_user, $domain)
{
$clientGmail = getClientGmail($server_name);
$gmailService = new Google_Service_Gmail($clientGmail);
$primary_email = $acc_user . '#' . $domain;
$sendAsEmail = new Google_Service_Gmail_SendAs();
$alias = '';
if (($server_name == null) || (strpos($server_name, "dev") != false))
{
$alias = '#g.';
}
else
{
$alias = '#mail.';
}
$sendAsEmail -> setSendAsEmail($acc_user . $alias . $domain);
$sendAsEmail -> setIsDefault(TRUE);
$sendAsEmail -> setIsPrimary(TRUE);
$error_msg = null;
try
{
$createSendAsResult = $gmailService->users_settings_sendAs -> create($primary_email, $sendAsEmail);
var_dump($createSendAsResult);
}
catch (Google_IO_Exception $gioe)
{
$error_msg = "Error in connection: ".$gioe->getMessage();
}
catch (Google_Service_Exception $gse)
{
$error_msg = "Service Exception: ".$gse->getMessage();
}
}
Finally, after much experimentation with the code and some help from a couple of colleagues, I figured out what the problem is and how to solve it.
Apparently, Google needs time to set up a new user's account with email. When I added a 10-second delay - sleep(10) in php - that was sufficient for the account to be ready for calls to the Gmail API, including the creation of a SendAs alias.
Related
I have created following code. I have to download files from my Google Drive folder. The folder is shared. After downloading, I have to delete those files from the Google Drive.
I tried -
$file = $service->parents->delete($file_id,$folder_id); - It doesn't do anything, nor does it give any error.
$file = $service->files->trash($file_id); - It gives Error calling DELETE - (403) Insufficient permissions for this file" Error.
My code :
<?php
require_once "google/google-api-php-client/src/Google_Client.php";
require_once "google/google-api-php-client/src/contrib/Google_DriveService.php";
require_once "google/google-api-php-client/src/contrib/Google_Oauth2Service.php";
require_once "google/vendor/autoload.php";
$file_id = '1bJm_cqIRVh5RaVrqVXGRL0CSYwTBlZur';
$folder_id='1gEllj4B9TCnLPe_dnl1ujX4u8smLL-Ky';
$DRIVE_SCOPE = 'https://www.googleapis.com/auth/drive';
$SERVICE_ACCOUNT_EMAIL = 'service_account_email#domain.com';
$SERVICE_ACCOUNT_PKCS12_FILE_PATH = 'GoogleDriveApi-7cd8056e9eae.p12';
function buildService() {//function for first build up service
global $DRIVE_SCOPE, $SERVICE_ACCOUNT_EMAIL, $SERVICE_ACCOUNT_PKCS12_FILE_PATH;
$key = file_get_contents($SERVICE_ACCOUNT_PKCS12_FILE_PATH);
$auth = new Google_AssertionCredentials(
$SERVICE_ACCOUNT_EMAIL, array($DRIVE_SCOPE), $key);
$client = new Google_Client();
$client->setUseObjects(true);
$client->setAssertionCredentials($auth);
return new Google_DriveService($client);
}
function printFilesInFolder($service, $folderId) {
$pageToken = NULL;
$arrayFile=array();
do {
try {
$parameters = array();
if ($pageToken) {
$parameters['pageToken'] = $pageToken;
}
$children = $service->children->listChildren($folderId, $parameters);
$arrayFile=$children;
$pageToken = $children->getNextPageToken();
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
$pageToken = NULL;
}
} while ($pageToken);
return $arrayFile;
}
try {
$service = buildService();
$children=printFilesInFolder($service,$folder_id);
$myfile = fopen("D:/list.txt", "wb") or die("Unable to open file!");
foreach ($children->getItems() as $child) {
print "\r\nFile Id: " . $child->getId();
fwrite($myfile, $child->getId());
fwrite($myfile, "\r\n");
}
$file = $service->parents->delete($file_id,$folder_id);
$file = $service->files->trash($file_id);
fclose($myfile);
} catch (Exception $e) {
print "An error occurred1: " . $e->getMessage();
}
?>
Your error indicates that the user doesn't have a write access to the file, and an app is attempting to modify the particular file.
Suggested action: Report to the user that there is a need to ask for
those permissions in order to update the file. You may also want to
check user access levels in the metadata retrieved by
files.get and use that to change your UI to a read only UI.
I used yahoo oauth in my website. In code below that I found on github, for example $user -> query -> results -> profile -> givenName returns the first name of logged in user, $user -> query -> results -> profile -> familyName and so on.
I searched a lot but still I don't know how to get user's email address.
This is my code :
require('include/http.php');
require('include/oauth_client.php');
$client = new oauth_client_class;
$client->debug = false;
$client->debug_http = true;
$client->server = 'Yahoo';
$client->redirect_uri = 'http://www.example.com';
$client->client_id = '';
$application_line = __LINE__;
$client->client_secret = '';
if(($success = $client->Initialize()))
{
if(($success = $client->Process()))
{
if(strlen($client->access_token))
{
$success = $client->CallAPI(
'https://query.yahooapis.com/v1/yql',
'GET', array(
'q'=>'select * from social.profile where guid=me',
'format'=>'json'
), array('FailOnAccessError'=>true), $user);
}
}
$success = $client->Finalize($success);
}
if($client->exit)
exit;
if(strlen($client->authorization_error))
{
$client->error = $client->authorization_error;
$success = false;
}
if($success)
{
$yahname =$user->query->results->profile->givenName.$user->query->results->profile->familyName;
echo '<pre>', HtmlSpecialChars(print_r($user, 1)), '</pre>';
}
else
{
echo HtmlSpecialChars($client->error);
}
Please let me know if I am doing anything wrong.
I do not believe that the profile contains the users email address (it is not listed in the Yahoo profile docs). If you have requested the sdpp-w scope the the id token you get when exchanging an authorization code for an access token contains the email address of the user under the key email.
I am integrating warehouse management system (which is based on PHP) with PrestaShop1.6 and I am using PrestaShop Web Service for integration.
I have to make new products (which are created in warehouse management system) appear on PrestaShop 1.6 online store. Warehouse management system asks PrestaShop WebService to create new product on PrestaShop online store.
I have written this function showed below. It works good at my localhost, but on test server it receives HTTP status 503 after trying to update stock availability. All WebService methods (GET, PUT, DELETE, etc) are enabled on all WebService entities. I don't know how to debug this problem, can you help me?
By the way, I used this code as example: https://github.com/xabikip/PrestaShopWebService/blob/master/examples/createProduct.php
private function saveProduct($update, $webService, $root_path, $n_id, $n_id_category_default, $n_id_category, $n_price, $n_active, $n_avail4order, $n_show_price, $n_l_id, $n_name, $n_desc, $n_desc_short, $n_link_rewrite, $n_meta_title, $n_meta_description, $n_meta_keywords, $n_available_now, $n_available_later, $idtaglist, $cod, $quantity) {
$webService = new PrestaShopWebservice($this->ps_shop_path, $this->ps_ws_auth_key, $this->ps_ws_debug);
$xml = $webService->get(array('url' => $root_path . '/api/products?schema=blank'));
$resources = $xml->children()->children();
/*
many values of attributes of XML object $resources are assigned here, instead of this comment
*/
$id = "";
try {
$opt = array('resource' => 'products');
if(!$update){
$opt['postXml'] = $xml -> asXML();
$xml = $webService -> add($opt);
$id = $xml->product->id;
}
else{
$opt['putXml'] = $xml -> asXML();
$opt['id'] = $n_id;
$xml = $webService -> edit($opt);
$id = $n_id;
}
}
catch (PrestaShopWebserviceException $ex) {
echo '<b>Error : '.$ex->getMessage().'</b>';
}
$resources = $xml->children()->children();
$stock_available_id = $resources->associations->stock_availables->stock_available[0]->id;
/*
Here we get the sotck available with were product id
*/
try
{
$opt = array('resource' => 'stock_availables');
$opt['id'] = $stock_available_id;
$xml = $webService->get($opt);
}
catch (PrestaShopWebserviceException $e)
{
$trace = $e->getTrace();
if ($trace[0]['args'][0] == 404) die('1:Bad ID');
else if ($trace[0]['args'][0] == 401) die('1:Bad auth key');
else die('1:Other error '.$e->getMessage());
}
$resources = $xml->children()->children();
$resources->quantity = $quantity;
/*
There we call to save our stock quantity.
*/
try
{
$opt = array('resource' => 'stock_availables');
$opt['putXml'] = $xml->asXML();
$opt['id'] = $stock_available_id;
$xml = $webService->edit($opt);
echo "Successfully updated.";
}
catch (PrestaShopWebserviceException $e)
{
$trace = $e->getTrace();
if ($trace[0]['args'][0] == 404) die('2:Bad ID');
else if ($trace[0]['args'][0] == 401) die('2:Bad auth key');
else echo('Other error: '.$e->getMessage()); // function echoes this PrestaShopWebServiceException: "Other error: This call to PrestaShop Web Services returned an unexpected HTTP status of:503"
}
}
PUT request are closed by default in most of hosting. Did you check this with your hosting manager??
Anyway, you must activate Prestashop DEBUG MODE in order to know the exact reason of your error (after you solve this of course).
Good luck.
i am using the below code to connect to salesforce using php
require_once ('SforcePartnerClient.php');
require_once ('SforceHeaderOptions.php');
require_once ('SforceMetadataClient.php');
$mySforceConnection = new SforcePartnerClient();
$mySforceConnection->createConnection("cniRegistration.wsdl");
$loginResult = $mySforceConnection->login("username", "password.token");
$queryOptions = new QueryOptions(200);
try {
$sObject = new stdclass();
$sObject->Name = 'Smith';
$sObject->Phone = '510-555-5555';
$sObject->fieldsToNull = NULL;
echo "**** Creating the following:\r\n";
$createResponse = $mySforceConnection->create($sObject, 'Account');
$ids = array();
foreach ($createResponse as $createResult) {
print_r($createResult);
array_push($ids, $createResult->id);
}
} catch (Exception $e) {
echo $e->faultstring;
}
But the above code is connect to salesforce database.
But is not executing the create commands. it's giving me the below error message
Creating the following: Element {}item invalid at this location
can any one suggest me to overcome the above problem
MAK, in your sample code SessionHeader and Endpoint setup calls are missing
$mySforceConnection->setEndpoint($location);
$mySforceConnection->setSessionHeader($sessionId);
after setting up those, if you still see an issue, check the namespace urn
$mySforceConnection->getNamespace
It should match targetNamespace value in your wsdl
the value of $mySforceConnection should point to the xml file of the partner.wsdl.xml.
E.g $SoapClient = $sfdc->createConnection("soapclient/partner.wsdl.xml");
Try adding the snippet code below to reference the WSDL.
$sfdc = new SforcePartnerClient();
// create a connection using the partner wsdl
$SoapClient = $sfdc->createConnection("soapclient/partner.wsdl.xml");
$loginResult = false;
try {
// log in with username, password and security token if required
$loginResult = $sfdc->login($sfdcUsername, $sfdcPassword.$sfdcToken);
}
catch (Exception $e) {
global $errors;
$errors = $e->faultstring;
echo "Fatal Login Error <b>" . $errors . "</b>";
die;
}
// setup the SOAP client modify the headers
$parsedURL = parse_url($sfdc->getLocation());
define ("_SFDC_SERVER_", substr($parsedURL['host'],0,strpos($parsedURL['host'], '.')));
define ("_SALESFORCE_URL_", "https://test.salesforce.com");
define ("_WS_NAME_", "WebService_WDSL_Name_Here");
define ("_WS_WSDL_", "soapclient/" . _WS_NAME_ . ".wsdl");
define ("_WS_ENDPOINT_", 'https://' . _SFDC_SERVER_ . '.salesforce.com/services/wsdl/class/' . _WS_NAME_);
define ("_WS_NAMESPACE_", 'http://soap.sforce.com/schemas/class/' . _WS_NAME_);
$urlLink = '';
try {
$client = new SoapClient(_WS_WSDL_);
$sforce_header = new SoapHeader(_WS_NAMESPACE_, "SessionHeader", array("sessionId" => $sfdc->getSessionId()));
$client->__setSoapHeaders(array($sforce_header));
} catch ( Exception $e ) {
die( 'Error<br/>' . $e->__toString() );
}
Please check the link on Tech Thought for more details on the error.
I got some problem with php-sample.
I want to add users, but there were something went wrong.
Please help me!!
Here is code that I used:
<!DOCTYPE html>
<?php
require_once "vendor/autoload.php";
require_once "autoload.dist.php";
require_once "client/JasperClient.php";
require_once "client/User.php";
require_once "client/Role.php";
$client = new Jasper\JasperClient(
"localhost", // Hostname
8080, // Port
"jasperadmin", // Username
"jasperadmin", // Password
"/jasperserver-pro", // Base URL
"organization_1"
); // Organization (pro only)
$newUser = new Jasper\User("BI_User", // username
"superSTRENGTHpassw0rd", // password
"clever#email.com", // email
"Business Intelligence User", // description
"organization_1", // parent organization
"true" // enabled
);
$role = new Jasper\Role("ROLE_USER", NULL, "false");
$newUser->addRole($role);
try {
$client->putUsers($newUser);
}
catch (Exception $e) {
printf("Could not add new user: %s", $e->getMessage());
}?>
And Here is the error message that I got:
Could not add new user: Unexpected HTTP code returned: 400 Body of response:
Apache Tomcat/6.0.26 - Error report HTTP Status 400 - type Status
reportmessage description The request sent by the client was syntactically
incorrect ().Apache Tomcat/6.0.26
Ask I spent time google so much on that problem, I have found the solution.
Here is my solution whether someone are interested.
<?php
require_once "vendor/autoload.php";
require_once "autoload.dist.php";
use Jaspersoft\Client\Client;
use Jaspersoft\Dto\User\User;
use Jaspersoft\Dto\Role\Role;
function registerUsers(){
$client = new Client(
"localhost",
"8080",
"superuser",
"superuser",
"/jasperserver-pro",
"null"
);
$file_path = 'data/userlist.csv';
$handle = fopen($file_path,'r');
$array_users = array();
$i=0;
while (!feof($handle) !==false){
$line = fgetcsv($handle,1024,',');
$i++;
if($i==1) continue;
if(!empty($line)){
for($c = 0; $c < count($line); $c++){
$username = $line[0];
$password = $line[1];
$email = $line[2];
$fullname = $line[3];
$tenantId = $line[4];
$enabled = $line[5];
$user = new User($username, $password, $email,
$fullname, $tenantId, $enabled);
$role = new Role('ROLE_USER', null, 'false');
$array_users[$c] = $user;
$array_users[$c]->addRole($role);
try {
$client->userService()->addUsers($array_users[$c]);
} catch (Exception $e) {
printf('Could not add new user: %s', $e->getMessage());
}
}
}
}
}?>
And here is my csv data file:
User Name,Password,Email Address,Full Name,Tenant ID,Enable
User1,superSTRENGTHpassw0rd,clever#email.com,User One,a,true
User2,superSTRENGTHpassw0rd,clever#email.com,User One,a,true
User3,superSTRENGTHpassw0rd,clever#email.com,User One,a,true
User6,superSTRENGTHpassw0rd,clever#email.com,User One,organization_1,true
User7,superSTRENGTHpassw0rd,clever#email.com,User One,organization_1,true
User8,superSTRENGTHpassw0rd,clever#email.com,User One,b,true
User9,superSTRENGTHpassw0rd,clever#email.com,User One,b,true
User10,superSTRENGTHpassw0rd,clever#email.com,User One,c,true
User11,superSTRENGTHpassw0rd,clever#email.com,User One,c,true