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;
?>
Related
I have been building a private web based app for my shopify store that caters more towards our business needs. While i am able to do a dump of "all-orders", or "all-products", etc to Mysql, i haven't been able to figure out executing the shopify order creation webhook to insert a new order when created in Shopify to a Mysql database.
Instead i would need to run my script every "x" times to see if there is a new order (This could if i'm not mistaken lead to exceeding my API limit if i am running other API calls concurrently).
I understand the process of events however i am struggling to execute!
1. New order created in Shopify by Customer &or Admin.
2. Triggers webhook and sends Json to desired url i.e(https://mydomain//new-order.php). -> [Struggling]
3. When this happens the Json is decoded. -> [Struggling]
4. Assigned to a variable. -> [This i can do]
5. Inserted into a Mysql database. -> [This i can do]
=> Question:
How do you once you have created the webhook (in Shopify) get it to trigger your code to run thereafter and execute?
below is the code that i have put together, but when i sent a test hook the database isn't being updated.
All in the [new-orders.php] file (Broken up to show my train of thought):
[1] Private app credentials for connecting to Shopify store.
<?php
$api_url = https://apikey:password#my-store.shopify.com';
$shopify = $api_url . '/admin/webhooks.json';
[2] Create an array for the webhook argumnets when the webhook is triggered & assign to variable $webhooks.
$arguments = array(
'topic' => 'order/creation',
'address' => 'https://mydomain//new-order.php'
);
$webhooks = $api_url . '/admin/webhooks.json', $arguments;
[3] Decode the webhook data.
$webhook_content = '';
$webhook = fopen('php://input' , 'rb');
while(!feof($webhook)){ //loop through the input stream while the end of file is not reached
$webhook_content .= fread($webhook, 4096); //append the content on the current iteration
}
fclose($webhook); //close the resource
$orders = json_decode($webhook_content, true); //convert the json to array
[4] Add the new order to the Mysql database table.
// not sure if a foreach loop is necessary in this case?
foreach($orders as $order){
$servername = "mysql.servername.com";
$database = "database_name";
$username = "user_name";
$password = "password";
$sql = "mysql:host=$servername;dbname=$database;";
// Create a new connection to the MySQL database using PDO, $my_Db_Connection is an object
try {
$db = new PDO($sql, $username, $password);
//echo "<p> DB Connect = Success.</p>";
} catch (PDOException $error) {
echo 'Connection error: ' . $error->getMessage();
}
$order_id = $order['id'];
$order_number = $order['name'];
$f_name = $order['billing_address']['name'];
$payment_gateway = $order['gateway'];
$financial_status = $order['financial_status'];
$order_value = $order['total_price'];
$order_status = $order['#'];
$shipping_province = $order['shipping_address']['province'];
$created_at = $order['created_at'];
$updated_at = $order['updated_at'];
$shipping_method = $order['shipping_lines'][0]['title'];
$stmt = $db->query("INSERT INTO orders(order_id, order_number, cust_fname, payment_gateway, financial_status, order_value, order_status, ship_to, created_at, updated_at, shipping_method)
VALUES ('$created_at', '$order_id', '$order_number', '$f_name', '$payment_gateway', '$financial_status', '$order_value', '$order_status', '$shipping_province', '$created_at', '$updated_at', '$shipping_method')");
}
?>
Any help would be greatly appreciated and i hope i have given enough context to the issue i am currently facing. If any other information is required i will try my best to explain why i have done something the way i have.
Regards,
Update, managed to figure this out and for those of you potentially struggling with the following this is how i solved.
There are 2 aspect here!
1. Setting up the webhook [Shopify -> Notifications -> webhooks].
2. The php file that processes the webhook.
1. -> Create Webhook in shopify and point to where you php url [example.com/Process-webhook.php]
2. -> Process-webhook.php
php code
// Load variables
$webhook_content = NULL;
// Get webhook content from the POST
$webhook = fopen('php://input' , 'rb');
while (!feof($webhook)) {
$webhook_content .= fread($webhook, 4096);
}
fclose($webhook);
// Decode Shopify POST
$webhook_content = json_decode($webhook_content, TRUE);
$servername = "server_name";
$database = "database";
$username = "user_name";
$password = "password";
$sql = "mysql:host=$servername;dbname=$database;";
// Create a new connection to the MySQL database using PDO, $my_Db_Connection is an object
try {
$db = new PDO($sql, $username, $password);
//echo "<p> DB Connect = Success.</p>";
} catch (PDOException $error) {
echo 'Connection error: ' . $error->getMessage();
}
//Assign to variable
$order_id = $webhook_content['id'];
$order_number = $webhook_content['name'];
$f_name = $webhook_content['billing_address']['name'];
$payment_gateway = $webhook_content['gateway'];
$financial_status = $webhook_content['financial_status'];
$pick_status = $webhook_content['NULL'];
$pack_status = $webhook_content['NULL'];
$fulfill_status = $webhook_content['NULL'];
$order_value = $webhook_content['total_price'];
$order_status = $webhook_content['NULL'];
$shipping_province = $webhook_content['shipping_address']['province'];
// I wanted to insert the variant_id's and quantity as a string in one column. With this i can unserialise and use when needed
$items = [];
foreach($webhook_content["line_items"] as $item) {
$items[$item["variant_id"]]['quantity'] = $item["quantity"];
}
$items = serialize($items);
$created_at = $webhook_content['created_at'];
$updated_at = $webhook_content['updated_at'];
$shipping_method = $webhook_content['shipping_lines'][0]['title'];
$stmt = $db->query("INSERT INTO orders(order_id,
order_number,
cust_fname,
payment_gateway,
financial_status,
order_value,
order_status,
ship_to,
items,
created_at,
updated_at,
shipping_method)
VALUES ('$order_id',
'$order_number',
'$f_name',
'$payment_gateway',
'$financial_status',
'$order_value',
'$order_status',
'$shipping_province',
'$items',
'$created_at',
'$updated_at',
'$shipping_method')");
?>
I am trying to upload using client on twilio and trying buy a twilio number.
Also, I need to get a dynamic voice URL in order to record a conference call dynamically.
<?php
require_once 'vendor/autoload.php'; // Loads the library
use Twilio\Rest\Client;
// Your Account Sid and Auth Token from twilio.com/user/account
$sid = "*********************";
$token = "*******************";
$client = new Client($sid, $token);
$numbers = $client->availablePhoneNumbers('US')->local->read(
array("areaCode" => "424")
);
$twilioNumber = $numbers[0]->phoneNumber;
$newNumber = $client->incomingPhoneNumbers->create(
[
"voiceUrl" => "host url",
"voiceMethod" => "GET"
]
);
if ($newNumber) {
return $twilioNumber;
} else {
return 0;
}
//
In the voiceUrl parameter i am passing a conference call connect code hosted link but its not getting updated to twilio account dynamically.
You can use like
require 'Services/Twilio.php';
$account_id = ACCOUNT_SID;
$auth_token = AUTH_TOKEN;
$number = $_REQUEST['id'];
$client = new Services_Twilio($account_id, $auth_token);
try{
$number= $client->account->incoming_phone_numbers->create(array('PhoneNumber' =>'+'.$number));
$number_sid=$number->sid;
$number1 = $client->account->incoming_phone_numbers->get($number_sid);
$number1->update(array("VoiceUrl" => "http://11.11.1.111/test/twilio_call_response.php","SmsUrl"=>"http://11.11.1.111/test/incomingsms.php","VoiceFallbackUrl"=>"http://11.11.1.111/test/fall_backurl.php"));
$phone_number=str_replace('+','',$numbers);
$allocate='1';
}catch(Exception $e){
echo $err = "Error purchasing number: {$e->getMessage()}";
}
echo $phone_number;
I am developing an SMS Based Registration System and so far I'm at the stage of testing my system. All of a sudden, I was not able to receive any messages from my server when I tried to register via SMS it must receive a confirmation messages. Here's what i did when using PHP nusoap.
Register.php
<?php
// This will allow user to register via SMS.
error_reporting( E_ALL );
// load the nusoap libraries. These are slower than those built in PHP5 but
require_once('nusoap.php');
// create the client and define the URL endpoint
$soapclient = new nusoap_client('http://www.mnccyf.info/soap_book.php?wsdl');
// set the character encoding, utf-8 is the standard.
$soapclient->soap_defencoding = 'UTF-8';
$soapclient->call('sendSMS', array( 'uName' => '48dwi5',
'uPin' => '159597',
'MSISDN' => '09152886810',
'messageString' => 'Registered Successfully',
'Display' => '1',
'udh' => '',
'mwi' => '',
'coding' => '0' ),
"http://ESCPlatform/xsd");
?>
Inquiry.php
<?php
// This will allow user to inquire about the latest news within the organization.
error_reporting( E_ALL );
// load the nusoap libraries. These are slower than those built in PHP5 but
require_once('nusoap.php');
$soapclient = new nusoap_client('http://www.mnccyf.info/soapquery_server.php?wsdl');
// set the character encoding, utf-8 is the standard.
$soapclient->soap_defencoding = 'UTF-8';
// Call the SOAP method, note the definition of the xmlnamespace as the third in the call and how the posted message is added to the message string
$soapclient->call('sendSMS', array( 'uName' => '48dwi5',
'uPin' => '159597',
'MSISDN' => '09152886810',
'messageString' => 'Summer Camp 2013',
'Display' => '1',
'udh' => '',
'mwi' => '',
'coding' => '0' ),
"http://ESCPlatform/xsd");
?>
incoming_sms.php
<?php
require_once('nusoap.php');
function sendSMS($number,$soapclient)
{
$x=sendSMS("09152886810",$soapclient);
}
# Load XML string from input
$xml = simplexml_load_file('php://input');
# Parse the XML for parameters
$sms = array();
$nodes = $xml->xpath('/message/param');
foreach($nodes as $node)
{
$param = (array) $node;
$sms[$param['name']] = $param['value'];
}
if($sms['messageType'] == 'SMS-NOTIFICATION') {
sendSMS();
list($action, $messagetype, $source, $type) =explode (" ",$soapclient);
}elseif($sms['messageType'] == 'SMS') {
sendSMS();
list($action, $name, $age, $localchurch, $district) = explode(" ",$soapclient);
}elseif($sms['messageType'] == 'SMS') {
sendSMS();
list($action, $event,$location,$time) = explode(" ", $soapclient);
}
else {
echo "Unsupported Message Type";
}
?>
register_soapserver.php
<?php
//call library
require_once ('nusoap.php');
//using soap_server to create server object
$server = new nusoap_server;
$server ->configureWSDL('http://iplaypen.globelabs.com.ph:1881/axis2/services/Platform?
wsdl','urn:http://iplaypen.globelabs.com.ph:1881/axis2/services/Platform?wsdl');
//register a function that works on server
$server->register('reg');
// create the function
function reg()
{
$connect = mysql_connect("localhost","root","jya0312#");
if (!$connect)
{
die("Couldnt connect" . mysql_error());
}
mysql_select_db("cyfdb", $connect);
$sql = "INSERT INTO mydb(name, age,localchurch,district) VALUES ('{$_POST [name]}','{$_POST[age]}','{$_POST[localchurch]}','{$_POST[district]}')";
mysql_close($connect);
}
// create HTTP listener
$server->service($HTTP_RAW_POST_DATA);
exit();
?>
soapquery_server.php
<?php
//call libraryrequire_once ('nusoap.php');
//using soap_server to create server object
$server = new nusoap_server;
$server ->configureWSDL('http://iplaypen.globelabs.com.ph:1881/axis2/services/Platform? wsdl','urn:http://iplaypen.globelabs.com.ph:1881/axis2/services/Platform? wsdl');
//register a function that works on server
$server->register('getquery');
// create the function
function getquery()
{
$link=mysql_connect("localhost", "root", "jya0312#") or die("Cannot connect to DB!");
mysql_select_db("cyfdb") or die("Cannot select DB!");
$sql = "SELECT event,location,time from activity";
while($r = mysql_fetch_array($sql)){
$items[] = array('event'=>$r['event'],
'location'=>$r['location'],
'date'=>$r['date']);
}
return $items;
$mysql_close($link);
}
// create HTTP listener
$server->service($HTTP_RAW_POST_DATA);
exit();
?>
I've been researching this and trying many variations based off my understanding of how to update a record in an SObject, but I keep getting the following error:
SoapFault exception: [sf:INVALID_TYPE] INVALID_TYPE: Must send a concrete entity type. in /home/public_html/soapclient/SforceBaseClient.php:509
I am able to login successfully to the page, but when I execute the code below, I am getting the error listed above.
$fieldsToUpdate = array (
"Name"=>$_POST['Name']
);
$sObject = new SObject();
$sObject->Id = $_POST['prospectID']; // this is the Id of the record
$sObject->fields = $fieldsToUpdate;
$sObject->type = 'Prospect__c'; // this is the API name of custom object
try {
$response = $mySforceConnection->update($sObject);
} catch (Exception $e) {
echo $e;
}
I am using PHP Toolkit 13.0 from the Force.com developer docs, but not able to get to the bottom of this error. Also, I am using the Enterprise WSDL in sandbox mode, and have the proper wsdl xml assigned.
Thanks.
sObject is the base type for all other Salesforce objects that can be updated. When using the enterprise API (SOAP), you'll need to pass instances that derive from sObject. (Lead, Contact, and Account are examples)
Here is the documentation for the update() method as well.
You need to supply an object type as the second update() argument. Also, the first argument of the update() method must be an array of objects you'd like to update:
$response = $mySforceConnection->update(array($object), 'Prospect__c');
Also, you do not need to use any object classes provided by the toolkit, a simple StdClass should work:
$prospect = new StdClass();
$prospect->Id = '006....';
$prospect->Name 'Foobar';
$response = $mySforceConnection->update(array($prospect), 'Prospect__c');
FYI, I have never found a way to update multiple object types at once, but you can update a batch of the same type of objects, hence why the first parameter needs to be an array. The Salesforce toolkit doesn't automatically account for someone passing a single object (i.e. it doesn't wrap it in an array for you). I have always used an abstraction layer between my application logic and Salesforce's SOAP toolkit, which provides conveniences like I just described.
if your are using Partner wsdl
<?php
// SOAP_CLIENT_BASEDIR - folder that contains the PHP Toolkit and your WSDL
// $USERNAME - variable that contains your Salesforce.com username (must be in the form of an email)
// $PASSWORD - variable that contains your Salesforce.com password
define("SOAP_CLIENT_BASEDIR", "../../soapclient");
require_once (SOAP_CLIENT_BASEDIR.'/SforcePartnerClient.php');
require_once ('../userAuth.php');
try {
$mySforceConnection = new SforcePartnerClient();
$mySoapClient = $mySforceConnection->createConnection(SOAP_CLIENT_BASEDIR.'/partner.wsdl.xml');
$mylogin = $mySforceConnection->login($USERNAME, $PASSWORD);
/*--------------------------------------------------------\
| Please manage the values for OBJECT ID from file
| userAuth.php
\--------------------------------------------------------*/
$fieldsToUpdate = array (
'FirstName' => 'testupdate',
'City' => 'testupdateCity',
'Country' => 'US'
);
$sObject1 = new SObject();
$sObject1->fields = $fieldsToUpdate;
$sObject1->type = 'Lead';
$sObject1->Id = $UPDATEOBJECTID1;
$fieldsToUpdate = array (
'FirstName' => 'testupdate',
'City' => 'testupdate',
'State' => 'testupdate',
'Country' => 'US'
);
$sObject2 = new SObject();
$sObject2->fields = $fieldsToUpdate;
$sObject2->type = 'Lead';
$sObject2->Id = $UPDATEOBJECTID2;
$sObject2->fieldsToNull = array('Fax', 'Email');
$response = $mySforceConnection->update(array ($sObject1, $sObject2));
print_r($response);
} catch (Exception $e) {
print_r($mySforceConnection->getLastRequest());
echo $e->faultstring;
}
?>
else for enterprises wsdl use
<?php
// SOAP_CLIENT_BASEDIR - folder that contains the PHP Toolkit and your WSDL
// $USERNAME - variable that contains your Salesforce.com username (must be in the form of an email)
// $PASSWORD - variable that contains your Salesforce.com password
define("SOAP_CLIENT_BASEDIR", "../../soapclient");
require_once (SOAP_CLIENT_BASEDIR.'/SforceEnterpriseClient.php');
require_once ('../userAuth.php');
try {
$mySforceConnection = new SforceEnterpriseClient();
$mySoapClient = $mySforceConnection->createConnection(SOAP_CLIENT_BASEDIR.'/enterprise.wsdl.xml');
$mylogin = $mySforceConnection->login($USERNAME, $PASSWORD);
/*--------------------------------------------------------\
| Please manage the values for OBJECT ID from file
| userAuth.php
\--------------------------------------------------------*/
$sObject1 = new stdclass();
$sObject1->Id = $UPDATEOBJECTID1;
$sObject1->FirstName = 'testupdate';
$sObject1->City = 'testupdateCity';
$sObject1->Country = 'US';
$sObject2 = new stdclass();
$sObject2->Id = $UPDATEOBJECTID2;
$sObject2->FirstName = 'testupdate';
$sObject2->City = 'testupdate';
$sObject2->State = 'testupdate';
$sObject2->Country = 'US';
$sObject2->fieldsToNull = array('Fax', 'Email');
$response = $mySforceConnection->update(array ($sObject1, $sObject2), 'Lead');
print_r($response);
} catch (Exception $e) {
print_r($mySforceConnection->getLastRequest());
echo $e->faultstring;
}
?>
I have sugar crm instance and i was trying to get some data from it using soap service.
Below is the code which i am using for it.
When i run the same code , sometimes it is returning correct data, sometimes it not.
Can any one tell me what the problem is??
include "nusoap.php";
$client = new soapclient('http://asdf.net/test/urbancrm_2009_06_22/soap.php');
// Login to SugarCRM
$auth_array = array(
'user_auth' => array(
'user_name' => '******',
'password' => '*******'
),
);
$response = $client->call('login', $auth_array);
if (!$response['error']['number']){
// Successfully logged in
$session_id = $response['id'];
//$response = $client->call('get_entry_list',array('session'=>$session_id , 'module_name'=>'Users', 'query'=>'', 'order_by'=>'','offset'=>'','select_fields'=>array('id','user_name')));
$response = $client->call('get_entry_list',array('session'=>$session_id , 'module_name'=>'itf_Apartments', "query"=>"itf_apartments_cstm.neighborhood_c='Loop'", 'order_by'=>'','offset'=>'','select_fields'=>array('name','studio','convertible','one_bedroom','one_bedroom_plus_den','two_bedroom','two_bedroom_plus_den','penthouse','photo_c','building_type_c','neighborhood_c')));
//$response = $client->call('get_entry_list',array('session'=>$session_id , 'module_name'=>'itf_Apartments', 'query'=>'itf_apartments_cstm.urbanlux_id_c="1"', 'order_by'=>'','offset'=>'','select_fields'=>array('name','studio','convertible','one_bedroom','one_bedroom_plus_den','two_bedroom','two_bedroom_plus_den','penthouse',)));
//store id and user name as a key value pair in array
//echo "---";
print_r($response);
} else {
echo "else";
print_r($response);
}
?>
You need to convert the password to MD5 before you pass for authentication.