Google API Client - Create user with another email - php

I started using the php quickstart to connect and create users. Everything works, but cannot add a second email address.
The help is confusing, and can't find an example.
My code so far:
// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Directory($client);
// USER DATA
$userName = 'Test';
$userSurname = 'User';
$userDocument = '12345678';
$userEmail = 'test#mail.com';
$name = new Google_Service_Directory_UserName();
$email = new Google_Service_Directory_UserEmail();
$user = new Google_Service_Directory_User();
// CREATE USER TO INSERT
$name->setGivenName($userName);
$name->setFamilyName($userSurname);
$name->setFullName($userName . ' ' . $userSurname);
$email->setAddress($userEmail);
$email->setType('home');
$user->setName($name);
$user->setHashFunction('SHA-1');
$user->setPassword(hash('sha1', $userDocument));
$user->setPrimaryEmail($userName . '.' . $userSurname . '#domain.com');
$user->setSuspended(false);
$user->setChangePasswordAtNextLogin(true);
$user->setEmails(array('address' => 'test#mail.com', 'type' => 'home', 'customType' => '', 'primary' => false)); // don't work
// $user->setEmails($email); // don't work either
$user->setOrgUnitPath('/org/path');
try
{
$createUserResult = $service->users->insert($user);
}

I find the error. The setEmails method receives an multidimensional array, so:
$user->setEmails(array(array('address' => 'test#mail.com', 'type' => 'home', 'customType' => '', 'primary' => false)));

Related

Soap, call a recovery service

I am new to SOAP. For a project, I need to use "Force.com Toolkit for PHP".
I made the first call to open a Salesforce session and retrieve the session ID , which will be used to call the recovery service of customer information. ( It's ok, i have the ID session)
I know that the customer information flows is called using the session ID obtained with the first call, but i don't how to do the second call ! I also have another WSDL file ( CallInListCustomer.wsdl.xml )
I also the customers informations flow addresses (found in WSDL ). I'm not sure , but i must the call in "post" format...
can you help me ?
<?php
session_start();
define("USERNAME", "my_username");
define("PASSWORD", "my_password");
define("SECURITY_TOKEN", "my_token");
require_once ('soapclient/SforcePartnerClient.php');
$mySforceConnection = new SforcePartnerClient();
$mySforceConnection->createConnection("Partner.wsdl.xml");
$mySforceConnection->login(USERNAME, PASSWORD.SECURITY_TOKEN);
// Now we can save the connection info for the next page
$_SESSION['location'] = $mySforceConnection->getLocation();
$_SESSION['sessionId'] = $mySforceConnection->getSessionId();
$sessionId = $_SESSION['sessionId'];
echo $sessionId;
// Here, i don't know how to call the recovery service of customer information with allInListCustomer.wsdl.xml
?>
Thanks for all
Here is my code.
Create separate file to store salesforce org details.
SFConfig.php
<?php
/*----------------------------------------------------------------
* We will define salesforce user anem and password with token.
* This file we used / include in every time when we need to
* communicate withy salesforce.
* ---------------------------------------------------------------*/
$USERNAME = "Your salesforce user name";
$PASSWORD = "Your password with security token";
?>
Get account data from salesforce
GetAccountData.php
<?php
// SET SOAP LIB DIRCTORY PATH
define("SOAP_LIB_FILES_PATH", "/<Put Your file location>/soapclient");
// Access sf config file
require_once ('/<Put Your file location>/SFConfig.php');
// Access partner client php lib file
require_once (SOAP_LIB_FILES_PATH.'/SforcePartnerClient.php');
try {
echo "\n******** Inside the try *******\n";
// Sf connection using ( SOAP ) partner WSDL
$mySforceConnection = new SforcePartnerClient();
$mySforceConnection->createConnection(SOAP_LIB_FILES_PATH.'/YourWSDLName.wsdl.xml');
$mySforceConnection->login($USERNAME, $PASSWORD);
echo "\n******** Login with salesforce is done *******\n";
// query for featch Versand data with last run datetime
$query = "SELECT Id, Name
FROM Account;
// Send query to salesforce
$response = $mySforceConnection->query($query);
// Store the query result
$queryResult = new QueryResult($response);
$isError = false ;
echo "Results of query '$query'<br/><br/>\n";
// Show result array
for ($queryResult->rewind(); $queryResult->pointer < $queryResult->size; $queryResult->next()) {
$record = $queryResult->current();
// Id is on the $record, but other fields are accessed via
// the fields object
echo "\nVersand value : ".$record->Abmelder__c."\n";
}
} catch (Exception $e) {
$GLOBALS['isTimeEnter'] = true;
echo "entered catch****\n";
echo "Exception ".$e->faultstring."<br/><br/>\n";
}
?>
Also if you want to call another services then just call using "$mySforceConnection" variable as per above.
For Example: (Create Contact)
$records = array();
$records[0] = new SObject();
$records[0]->fields = array(
'FirstName' => 'John',
'LastName' => 'Smith',
'Phone' => '(510) 555-5555',
'BirthDate' => '1957-01-25'
);
$records[0]->type = 'Contact';
$records[1] = new SObject();
$records[1]->fields = array(
'FirstName' => 'Mary',
'LastName' => 'Jones',
'Phone' => '(510) 486-9969',
'BirthDate' => '1977-01-25'
);
$records[1]->type = 'Contact';
$response = $mySforceConnection->create($records);
$ids = array();
foreach ($response as $i => $result) {
echo $records[$i]->fields["FirstName"] . " "
. $records[$i]->fields["LastName"] . " "
. $records[$i]->fields["Phone"] . " created with id "
. $result->id . "<br/>\n";
array_push($ids, $result->id);
}
Please check below link for more details:
https://developer.salesforce.com/page/Getting_Started_with_the_Force.com_Toolkit_for_PHP
I find the solution, here my code :
<?php
// salesforce.com Username, Password and TOken
define("USERNAME", "My_username");
define("PASSWORD", "My_password");
define("SECURITY_TOKEN", "My_token");
// from PHP-toolkit ( https://developer.salesforce.com/page/Getting_Started_with_the_Force.com_Toolkit_for_PHP )
require_once ('soapclient/SforcePartnerClient.php');
$mySforceConnection = new SforcePartnerClient();
$mySforceConnection->createConnection("Partner.wsdl.xml");
$mySforceConnection->login(USERNAME, PASSWORD.SECURITY_TOKEN);
// I Get the IDSESSION
$sessionId = $mySforceConnection->getSessionId();
// I create a new soapClient with my WSDL
$objClient = new SoapClient("my_service.wsdl.xml", array('trace' => true));
// I create the header
$strHeaderComponent_Session = "<SessionHeader><sessionId>$sessionId</sessionId></SessionHeader>";
$objVar_Session_Inside = new SoapVar($strHeaderComponent_Session, XSD_ANYXML, null, null, null);
$objHeader_Session_Outside = new SoapHeader('https://xxxxx.salesforce.com/services/Soap/class/myservice', 'SessionHeader', $objVar_Session_Inside);
$objClient->__setSoapHeaders(array($objHeader_Session_Outside));
// i call the service
$objResponse = $objClient->getinfo(array ( 'Zone' => "123456"));
// here i get the result in Json
$json = json_encode( (array)$objResponse);
echo $json;
?>

Tabs not showing up in envelope created from template

I'm trying to create a embedded envelope based on a template. The problem I am having is that in the created envelope the tabs I have created are missing.
I searched around and found the role assignment and used that and still no luck. When I look at the XML the role is the same as the template as well as the routing order and ID.
I tried setting the template so that I can't delete any recipients and I get the error:
Uncaught SoapFault exception: [soap:Client] Required recipient in the template has not been provided. Recipient not satisfied for role, Signer, in template Test Form
Here is my PHP to create and send the envelope, a lot of this is code used from the documentation:
// Get the recipient from a post
$rcp1 = new Recipient(); // First recipient to put in recipient array
$rcp1->UserName = $_POST['Name'];
$rcp1->Email = $_POST['Email'];
$rcp1->Type = RecipientTypeCode::Signer;
$rcp1->ID = "1";
$rcp1->RoutingOrder = 1;
$rcp1->CaptiveInfo = new RecipientCaptiveInfo();
$rcp1->CaptiveInfo->ClientUserId = 1;
$rcp1->RoleName = "Signer";
$rcp1->RequireIDLookup = FALSE;
// Create Role Assignments
$assign = new TemplateReferenceRoleAssignment();
$assign->RecipientID = $rcp1->ID;
$assign->RoleName = $rcp1->RoleName;
// Use a server-side template
$templateRef = new TemplateReference();
$templateRef->TemplateLocation = TemplateLocationCode::Server;
$templateRef->RoleAssignments = $assign;
$templateRef->Template = "****";
// Construct the envelope info
$envInfo = new EnvelopeInformation();
$envInfo->AccountId = $AccountID;
$envInfo->Subject = "This is the Subject";
$envInfo->EmailBlurb = "I have no Idea What a blurb is";
// Send creates draft with all the template info
$createEnvelopeFromTemplatesparams = new CreateEnvelopeFromTemplates();
$createEnvelopeFromTemplatesparams->TemplateReferences = array($templateRef);
$createEnvelopeFromTemplatesparams->Recipients = array($rcp1);
$createEnvelopeFromTemplatesparams->EnvelopeInformation = $envInfo;
$createEnvelopeFromTemplatesparams->ActivateEnvelope = true;
$env = $api->CreateEnvelopeFromTemplates($createEnvelopeFromTemplatesparams);
$envStatus = $env->CreateEnvelopeFromTemplatesResult;
// Construct the recipient token authentication assertion and specify
// ID, start time, method, and domain
$assertion = new RequestRecipientTokenAuthenticationAssertion();
$assertion->AssertionID = guid();
$assertion->AuthenticationInstant = nowXsdDate();
$assertion->AuthenticationMethod = RequestRecipientTokenAuthenticationAssertionAuthenticationMethod::Password;
$assertion->SecurityDomain = "Request Recipient Token Test";
// Construct the URLs based on UserName
$recip = $envStatus->RecipientStatuses->RecipientStatus[0];
$urls = new RequestRecipientTokenClientURLs();
$urlbase = getCallbackURL('pop.php');
$urls->OnSigningComplete = $urlbase . "?event=SignComplete&uname=" . $recip->UserName;
$urls->OnViewingComplete = $urlbase . "?event=ViewComplete&uname=" . $recip->UserName;
$urls->OnCancel = $urlbase . "?event=Cancel&uname=" . $recip->UserName;
$urls->OnDecline = $urlbase . "?event=Decline&uname=" . $recip->UserName;
$urls->OnSessionTimeout = $urlbase . "?event=Timeout&uname=" . $recip->UserName;
$urls->OnTTLExpired = $urlbase . "?event=TTLExpired&uname=" . $recip->UserName;
$urls->OnIdCheckFailed = $urlbase . "?event=IDCheck&uname=" . $recip->UserName;
$urls->OnAccessCodeFailed = $urlbase . "?event=AccesssCode&uname=" . $recip->UserName;
$urls->OnException = $urlbase . "?event=Exception&uname=" . $recip->UserName;
// Send
$requestRecipientTokenparams = new RequestRecipientToken();
$requestRecipientTokenparams->EnvelopeID = $envStatus->EnvelopeID;
$requestRecipientTokenparams->ClientUserID = $recip->ClientUserId;
$requestRecipientTokenparams->Username = $recip->UserName;
$requestRecipientTokenparams->Email = $recip->Email;
$requestRecipientTokenparams->AuthenticationAssertion = $assertion;
$requestRecipientTokenparams->ClientURLs = $urls;
$response = $api->RequestRecipientToken($requestRecipientTokenparams);
$tokenUrl = $response->RequestRecipientTokenResult;
echo '<iframe src="' . $tokenUrl . '" width="100%" height="720px"></iframe>';
This is the recipient info that is returned when I RequestTemplate():
[0] => Recipient Object
(
[ID] => 1
[UserName] =>
[SignerName] =>
[Email] =>
[Type] => Signer
[AccessCode] =>
[AddAccessCodeToEmail] =>
[RequireIDLookup] =>
[IDCheckConfigurationName] =>
[PhoneAuthentication] =>
[SignatureInfo] =>
[CaptiveInfo] =>
[CustomFields] =>
[RoutingOrder] => 1
[IDCheckInformationInput] =>
[AutoNavigation] =>
[RecipientAttachment] =>
[Note] =>
[RoleName] => Signer
[TemplateLocked] =>
[TemplateRequired] => 1
[TemplateAccessCodeRequired] =>
[DefaultRecipient] =>
[SignInEachLocation] =>
)
This might be due to you instatiating the templateRoleAssignments as an object and not an array. Since you're using the SOAP api and not REST have you seen the DocuSign SOAP SDK up on Github? That has sample code and projects for 5 different environments including PHP (PHP, Java, C#, Ruby, and Salesforce):
https://github.com/docusign/DocuSign-eSignature-SDK
Looking at a function defined in the PHP project I see the following:
function createFinalRoleAssignments($recipients) {
$roleAssignments[] = new TemplateReferenceRoleAssignment();
foreach ($recipients as $r) {
$assign = new TemplateReferenceRoleAssignment();
$assign->RecipientID = $r->ID;
$assign->RoleName = $r->RoleName;
array_push($roleAssignments, $assign);
}
// eliminate 0th element
array_shift($roleAssignments);
return $roleAssignments;
}
Notice how $roleAssignments is declared as an array using square brackets [], I have a strong feeling that is causing your error. Try defining your roleAssignments the same way and that will probably work.

Create Facebook Event for group page using a SQL database and post using graph api

I have been trying to post to an event that has already been created in a mySQL database and use facebook's graph api to post it to a group page. I am able to post an array created right in the code, but I would like to post an array that I am pulling in from a POST command. Here is what I have.
public function get_event()
{
require_once 'application/php-sdk/facebook.php';
$config = array(
'appId' => '1407968509465242',
'secret' => '***********************',
'cookie' => false,
'fileUpload' => true
);
$id = $_POST['eventsDrp'];
$this->load->model('mdl_facebook_event');
$output = $this->mdl_facebook_event->get_event($id);
print_r ($output);
$facebook = new Facebook($config);
// Set the current access token to be a long-lived token.
$facebook->setExtendedAccessToken();
$access_token = $facebook->getAccessToken();
$page_id = '594922100555123';
$page_access_token = '*******************';
// Declare the variables we'll use to demonstrate
// the new event-management APIs
$event_id = 0;
$event_name = "New Event API Test Event";
$event_start = '2012-04-24T22:01:00+0000';
$event_privacy = "SECRET"; // We'll make it secret so we don't annoy folks.
// We'll create an event in this example.
// We'll need create_event permission for this.
$params = array(
'name' => $event_name,
'start_time' => $event_start,
'privacy_type' => $event_privacy,
'access_token' => $page_access_token,
'page_id' => $page_id //where $page_id is the ID of the page you are managing
);
// Create an event
$ret_obj = $facebook->api("/$page_id/events", 'POST', $output);
if(isset($ret_obj['id'])) {
// Success
$event_id = $ret_obj['id'];
echo ('Event ID: ' . $event_id);
} else {
echo ("Couldn't create event.");
}
// Convenience method to print simple pre-formatted text.
function printMsg($msg) {
echo "<pre>$msg</pre>";
}
I am trying to post the array from $output. I have tried to post from $params and everything works fine. When I try and post from $output I get Fatal error:
Uncaught OAuthException: Invalid token: "594922100555123". An ID has already been specified.

Google Groups Directory API - Add user to group - PHP Function

How do I use this function?
I have a userid and a group id.
The error message I get when I try to add my fields has to do with the Google_Member instance. How would I use this in my PHP code?
BTW it is from the Google Apps API
/**
* Add user to the specified group. (members.insert)
*
* #param string $groupKey Email or immutable Id of the group
* #param Google_Member $postBody
* #param array $optParams Optional parameters.
* #return Google_Member
*/
public function insert($groupKey, Google_Member $postBody, $optParams = array()) {
$params = array('groupKey' => $groupKey, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('insert', array($params));
if ($this->useObjects()) {
return new Google_Member($data);
} else {
return $data;
}
}
Follow the instructions listed here to setup the application in Google Console and to enable Domain Delegation of Authority.
http://jamespeckham.com/wordpress/?p=9 (Thank you JDPeckham)
Download the client from: https://code.google.com/p/google-api-php-client/downloads/list
Here is my working code:
require_once "google-api-php-client/src/Google_Client.php";
require_once "google-api-php-client/src/contrib/Google_DirectoryService.php";
require_once "google-api-php-client/src/contrib/Google_Oauth2Service.php";
session_start();
const GROUP_SCOPE = 'https://www.googleapis.com/auth/admin.directory.group';
const SERVICE_ACCOUNT_EMAIL = '.....#developer.gserviceaccount.com';
const SERVICE_ACCOUNT_PKCS12_FILE_PATH = '/path/to/...privatekey.p12';
const CLIENT_ID = '....apps.googleusercontent.com';
$userEmail = 'email-address-with-admin-rights#domain.com';
$key = file_get_contents(SERVICE_ACCOUNT_PKCS12_FILE_PATH);
$auth = new Google_AssertionCredentials(SERVICE_ACCOUNT_EMAIL, array(GROUP_SCOPE), $key, 'notasecret', 'http://oauth.net/grant_type/jwt/1.0/bearer', $userEmail);
$client = new Google_Client();
$client->setClientId(CLIENT_ID); // from API console
$client->setApplicationName("Project Name from API Console");
$client->setUseObjects(true);
$client->setAssertionCredentials($auth);
$member = new Google_Member(array('email' => 'abc#testing.com',
'kind' => 'admin#directory#member',
'role' => 'MEMBER',
'type' => 'USER'));
$service = new Google_DirectoryService($client);
$results = $service->members->insert('mailing-list-name#domain.com', $member);
print '<h2>Response Result:</h2><pre>' . print_r($results, true) . '</pre>';
require_once $_SERVER['DOCUMENT_ROOT'] . '/../vendor/autoload.php';
$updateName = $_POST["name"];
$updateEmail = $_POST["email"];
//USING A SERVICE ACCOUNT TO CALL GOOGLE CLIENT
putenv('GOOGLE_APPLICATION_CREDENTIALS=/home/myserver/mywebsite/credentialsfile.json');
$client = new Google\Client();
// MY ACCOUNT DATA HERE
$client_id = 'clientid';
$service_account_name = 'serviceaccountemailhere'; //Email Address
$key_file_location = '/home/myserver/mywebsite/mykeyfile.json'; //key.p12
$agencyAdminGroupKey = 'emailforGroupKey#gmial.com'; //agency admins group key
$memberKey = $updateEmail; //$memberemail
$domain = 'yourwebsite.com';
if (getenv('GOOGLE_APPLICATION_CREDENTIALS')) {
// use the application default credentials
$client->useApplicationDefaultCredentials();
} else {
echo missingServiceAccountDetailsWarning();
return;
}
// set the scope(s) that will be used
//$client->setScopes(array('https://www.googleapis.com/auth/admin.directory.group'));
$client->setScopes(array('https://www.googleapis.com/auth/admin.directory.group'));
// this is needed only if you need to perform
// domain-wide admin actions, and this must be
// an admin account on the domain; it is not
// necessary in your example but provided for others
$client->setSubject('yourgoogleaccountemail#domain.com');
$client->setApplicationName("Client_Library_Examples");
$client->setDeveloperKey("paste-your-developer-key");
$service = new Google_Service_Directory($client);
$member = new Google_Service_Directory_Member( array('email' => $updateEmail,
'kind' => 'admin#directory#member',
'role' => 'MEMBER',
'type' => 'USER',
"deliverySettings" => 'DAILY'));
//GET request to google groups server
// $results = $service->members->listMembers($groupKey);
$results = $service->members->insert($agencyAdminGroupKey, $member);
Here are some useful links:
https://github.com/googleapis/google-api-php-client
https://developers.google.com/admin-sdk/directory/v1/quickstart/php
https://developers.google.com/resources/api-libraries/documentation/admin/directory_v1/php/latest/class-Google_Service_Directory_Groups.html
https://developers.google.com/admin-sdk/directory/reference/rest/v1/members

Google contacts API is ignoring the userDefinedField setting

I am trying to add a contact while at the same time including a userDefinedField. The code below works and adds the contact with the correct information however the userDefined field is missing. If I purposefully misspell one of the attributes, when I post the api falls over telling me it is missing an element, however if I fix the misspelling it does not include the userDefined Field.
Maybe I am missing something tiny but I really cannot see why it would simply be ignored. Does anyone have any ideas?
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
Zend_Loader::loadClass('Zend_Gdata_Gapps');
Zend_Loader::loadClass('Zend_Gdata_Query');
$email = "<email>";
$password = "<password>";
$contactName = $requestData['name'];
$contactAddress = $requestData['email'];
$client = Zend_Gdata_ClientLogin::getHttpClient($email, $password,"cp");
$gdata = new Zend_Gdata($client);
$entry = $gdata->newEntry();
$extensionElements = $entry->getExtensionElements();
$extension = new Zend_Gdata_App_Extension_Element('email', null,'http://schemas.google.com/g/2005');
$attributes['address'] = array('name'=>'address', 'value' =>$contactAddress);
$attributes['rel'] = array('name'=>'rel', 'namespaceUri'=>null,'value' => 'http://schemas.google.com/g/2005#work');
$attributes['primary'] = array('name'=>'primary', 'namespaceUri' =>null, 'value' => 'true');
$extension->setExtensionAttributes($attributes);
$attributes = null;
// adds the new email extension element to the entry's exenstions elemensts array
array_push( $extensionElements, $extension );
$extension = new Zend_Gdata_App_Extension_Element('userDefinedField', null, 'http://schemas.google.com/contact/2008');
$attributes['key'] = array('name'=>'key', 'value' =>'customGUID');
$attributes['value'] = array('name'=>'value', 'value' => $this->guid());
$extension->setExtensionAttributes($attributes);
$attributes = null;
array_push( $extensionElements, $extension );
$extension = new Zend_Gdata_App_Extension_Element('groupMembershipInfo', null, 'http://schemas.google.com/contact/2008');
$attributes['deleted'] = array('namespaceUri'=>null,'name'=>'deleted', 'value' => 'false');
if ("manufacturers" == strtolower($contactgroup)) {
$attributes['href'] = array('namespaceUri'=>null,'name'=>'href', 'value' => $MANUFACTURER_GROUP_URI);
} elseif ("distributors" == strtolower($contactgroup)) {
$attributes['href'] = array('namespaceUri'=>null,'name'=>'href', 'value' => $DISTRIBUTOR_GROUP_URI);
} elseif ("clients" == strtolower($contactgroup)) {
$attributes['href'] = array('namespaceUri'=>null,'name'=>'href', 'value' => $CLIENT_GROUP_URI);
}
$extension->setExtensionAttributes($attributes);
array_push( $extensionElements, $extension );
$entry->setExtensionElements($extensionElements);
$entry->title = $gdata->newTitle($contactName);
$entry->setExtensionElements($extensionElements);
$entryResult = $gdata->insertEntry($entry,"http://www.google.com/m8/feeds/contacts/$email/full");
I have already received a lot of help from the following posts, but didn't see anything to fix the issue:
http://www.google.com/support/forum/p/apps-apis/thread?tid=22ec941b7ac4ffc1&hl=en
http://groups.google.com/group/google-contacts-api/browse_thread/thread/be92586871a56046/95ec69573ca0f490?pli=1
http://www.ibm.com/developerworks/opensource/library/x-phpgooglecontact/index.html
I managed to figure it out.
I was not specifying which version of the API to use, so as soon as I specified the latest version using the below code, the userDefinedField appeared in Contacts as required.
$gdata->setMajorProtocolVersion(3);
$gdata->setMinorProtocolVersion(null);
Hope this helps others with similar questions.

Categories