Salesforce error: Element {}item invalid at this location - php

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.

Related

Getting a new accesstoken

I am trying to retrieve a new access token with my refresh token. Before I run a script to retrieve a new access token I want to check if my access token is still valid.
I am trying to do this with exceptions:
try
{
// Connect
$session = new SoapClient("../webservices/session.asmx?wsdl", array('trace' => 1));
$result = $session->AccessTokenLogon($accessTokenparams);
}
catch (SoapFault $e)
{
// Check if AcccessToken returns TokenInvalid
if ($result->AccessTokenLogonResult == "TokenInvalid")
{
// AccessToken is not valid anymore
// ..
// Run script to get new access token
// ..
// $_SESSION["access_token"] = $access_token;
}
else
{
// AccessToken is valid
echo "AccessToken is valid";
}
}
finally
{
// Run script with valid AccessToken
global $result, $session;
$cluster = $result->cluster;
$qq = new domDocument();
$qq->loadXML($session->__getLastResponse());
$newurl = $cluster . '/webservices/processxml.asmx?wsdl';
try
{
$client = new SoapClient($newurl);
$header = new SoapHeader('http://www.website.com/', 'Header', array('AccessToken' =>$_SESSION["access_token"]));
}
catch (SoapFault $e)
{
echo $e->getMessage();
}
try
{
echo '<br /><br />XML Result:<br /><br />';
$xml = ""; // XML request
$result = $client->__soapCall('ProcessXmlString', array(array('xmlRequest'=>$xml)), null, $header);
}
catch (SoapFault $e)
{
echo $e->getMessage();
}
}
With a valid access token the script is working. The XML request is posted to the webservice.
The script is not working when the accesstoken is not valid anymore. The script stores the new accesstoken in the session: $_SESSION["access_token"] = $access_token; but is not running the 'finally' part after retrieving a new accesstoken.
Does someone know how I can fix this and run the 'finally' after retrieving a new accesstoken?

Error calling DELETE - (403) Insufficient permissions for this file" | Google Drive API

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.

Softlayer API PHP error Function ("setObjectFilter") is not a valid method for this service

I tried to use object filter to get valid device:
Below is the php code:
$client= SoftLayer_SoapClient::getClient('SoftLayer_Account', null, $username, $apiKey);
$filter = new stdClass();
$filter->applicationDeliveryControllers = new stdClass();
$filter->applicationDeliveryControllers->billingItem = new stdClass();
$filter->applicationDeliveryControllers->billingItem->id = new stdClass();
$filter->applicationDeliveryControllers->billingItem->id->operation = new stdClass();
$filter->applicationDeliveryControllers->billingItem->id->operation = $bId;
$client->setObjectFilter($filter);
try {
$mask ='mask[id, name]';
$client->setObjectMask($mask);
$myInstance = $clientNetscaler->getApplicationDeliveryControllers();
} catch(exception $ex) {
}
I got the following error in my run time environment:
There was an error querying the SoftLayer API: Function
("setObjectFilter") is not a valid method for this service
The error came from line $client->setObjectFilter($filter);
Anybody has any idea of why there's such error?
For me the filter is working fine. Just in case, I copied my code. Please make sure you have PHP 5.2.3 or higher and the PHP extension for SOAP. Also try re-downloading the Softlayer PHP client https://github.com/softlayer/softlayer-api-php-client and try again.
Regards
<?php
require_once ('/SoapClient.class.php');
$apiUsername = 'set me';
$apiKey = 'set me';
$accountService = Softlayer_SoapClient::getClient('SoftLayer_Account', null,$apiUsername, $apiKey);
$bId = 51774239;
$filter = new stdClass();
$filter->applicationDeliveryControllers = new stdClass();
$filter->applicationDeliveryControllers->billingItem = new stdClass();
$filter->applicationDeliveryControllers->billingItem->id = new stdClass();
$filter->applicationDeliveryControllers->billingItem->id->operation = new stdClass();
$filter->applicationDeliveryControllers->billingItem->id->operation = $bId;
$accountService->setObjectFilter($filter);
$mask ='mask[id, name]';
$accountService->setObjectMask($mask);
try {
$myInstance = $accountService->getApplicationDeliveryControllers();
print_r($myInstance);
} catch (Exception $e) {
die('Unable to executre the request. ' . $e->getMessage());
}

Getting blank data in a SalesForce integration with PHP

I am trying integration with SalesForce using SOAP webservice.
I can build a connection with PHP and SOAP after that if I'm trying to call my method that is authenticate user, I am not getting any data, I'm getting blank.
Below is the code
define("USERNAME", "xxxxxxxxxxx");
define("PASSWORD", "xxxxxxxxxxx");
define("SECURITY_TOKEN", "xxxxxxxxxxx");
require_once ('soapclient/SforcePartnerClient.php');
require_once ('soapclient/SforceHeaderOptions.php');
// Login
$sfdc = new SforcePartnerClient();
$SoapClient = $sfdc->createConnection('soapclient/PartnerWSDL.xml');
$loginResult = false;
$loginResult = $sfdc->login('USERNAME', 'PASSWORD' . 'SECURITY_TOKEN');
// Define constants for the web service. We'll use these later
$parsedURL = parse_url($sfdc->getLocation());
define ("_SFDC_SERVER_", substr($parsedURL['host'],0,strpos($parsedURL['host'], '.')));
define ("_WS_NAME_", 'CustomerPortalServices');
define ("_WS_WSDL_", _WS_NAME_ . '.xml');
define ("_WS_ENDPOINT_", 'https://' . _SFDC_SERVER_ . '.salesforce.com/services/wsdl/class/' . _WS_NAME_);
//echo _WS_ENDPOINT_;
define ("_WS_NAMESPACE_", 'http://soap.sforce.com/schemas/class/' . _WS_NAME_);
// SOAP Client for Web Service
$client = new SoapClient('http://localhost/SFDC/soapclient/CustomerPortalServices_WSDL.xml');
$sforce_header = new SoapHeader(_WS_NAMESPACE_, "SessionHeader", array("sessionId" => $sfdc->getSessionId()));
$client->__setSoapHeaders(array($sforce_header));
// username and password sent from Form
echo $myusername=addslashes($_POST['login_username']);
echo $mypassword=addslashes($_POST['login_password']);
try {
// call the web service via post
$wsParams=array(
'username'=>'abc#gmail.com',
'password'=>'mypassword'
);
print_r($wsParams);
$response = $client->authenticateUser($wsParams);
// dump the response to the browser
print_r($response);
//header("location: index.php");
// this is really bad.
} catch (Exception $e) {
global $errors;
$errors = $e->faultstring;
echo "Ooop! Error: <b>" . $errors . "</b>";
die;
}
This is the method i am calling
global class CustomerPortalServicesNew {
webService static Summary authenticateUserNew(String uname,String passwd) {
System.debug('##'+'Entered in the authenticateUser');
List<contact> checkConList = new List<Contact>([select id,Email, Password__c, AccountId from contact where Email =:uname]);
System.debug('##'+'contact '+checkConList);
for(contact c:checkConList){
system.debug('##'+'Iterating in contactList'+checkConList);
if(c.Password__c==passwd){
system.debug('##'+c.AccountId);
return getAccountSummary(c.AccountId);
}
else{
system.debug('##'+'password has not matched');
return null;
}
}
system.debug('##'+'class finished');
return null;
}
I am getting response like this
object(stdClass)[8]
public 'result' =>
object(stdClass)[9]
not getting data
I think you need to print:
print_r($response->result);
If it's not working, try a var_dump($response)

PHP REST API got error when try to add New Users to Jasperserver

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

Categories