How to provide a nested SObject for foreign key field - php

I am trying to create a new opportunity from USSD App in salesforce via php rest api. I am parsing the record Type id instead of the record type name. Below is the Snippet for creating new opportunity.
public function log_case_opp( $sobject = 'Opportunity', $recordType = '012D00000003H8DIAU', $name='XXXXXX', $account, $stage, $currency='KES - Kenyan Shilling', $close_date ) {
$url = "$this->instance_url/services/data/v24.0/sobjects/{$sobject}/";
$content = json_encode(array("Name" => "{$name}",
"RecordType" => "{$recordType}",
"Account" => "{$account}",
"StageName" => "{$stage}",
"CurrencyIsoCode" => "{$currency}",
"CloseDate" => "{$close_date}"
));
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,
array("Authorization: OAuth $this->access_token",
"Content-type: application/json"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $content);
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($status == 400 && $json_response['error_description'] == 'expired authorization code') {
//access code has been expired
die('ERROR : new code required');
}elseif ( $status != 201 ) {
die("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));
}
curl_close($curl);
$response = json_decode($json_response, true);
return $response["id"];
}
When trying to create the opportunity am getting the error below
[{"message":"The value provided for foreign key reference RecordType is not a nested SObject","errorCode":"INVALID_FIELD"}]
Please help on what am doing wrong or not doing

i have been able to solve this error by adding Id to the reference fields i.e. changing the $content code block to :
$content = json_encode(array("Name" => "{$name}",
"RecordTypeId" => "{$recordType}",
"AccountId" => "{$account}",
"StageName" => "{$stage}",
"CurrencyIsoCode" => "{$currency}",
"CloseDate" => "{$close_date}"
));

Related

Trying to get attendees set in google calendar API / PHP

I´m trying to create an event and that part works, but it will not for some reason send out the invitations / attendees in the calendar system with google API using PHP. It does create the event but that also it. So I hope someone can help me figuring out what I´m doing wrong.
myfile.php
// Event details
parameters = { title: $("#event-title").val(),
event_time: {
start_time: $("#event-type").val() == 'FIXED-TIME' ? $("#event-start-time").val().replace(' ', 'T') + ':00' : null,
end_time: $("#event-type").val() == 'FIXED-TIME' ? $("#event-end-time").val().replace(' ', 'T') + ':00' : null,
event_date: $("#event-type").val() == 'ALL-DAY' ? $("#event-date").val() : null
},
'attendees': [
{'email': 'test#dds-slagelse.dk'},
],
all_day: $("#event-type").val() == 'ALL-DAY' ? 1 : 0,
};
$("#create-event").attr('disabled', 'disabled');
$.ajax({
type: 'POST',
url: 'ajax.php',
data: { event_details: parameters },
dataType: 'json',
success: function(response) {
$("#create-event").removeAttr('disabled');
alert('Event created with ID : ' + response.event_id);
},
error: function(response) {
$("#create-event").removeAttr('disabled');
alert(response.responseJSON.message);
}
});
ajax.php file
session_start();
header('Content-type: application/json');
require_once('google-calendar-api.php');
error_log($_SESSION['access_token']);
try {
// Get event details
$event = $_POST['event_details'];
error_log(__LINE__);
$capi = new GoogleCalendarApi();
error_log(__LINE__);
// Get user calendar timezone
$user_timezone = $capi->GetUserCalendarTimezone($_SESSION['access_token']);
error_log(__LINE__);
// Create event on primary calendar
error_log($event['attendees0']);
$event_id = $capi->CreateCalendarEvent('primary', $event['title'], $event['all_day'], $event['event_time'], $event['attendees'], $user_timezone, $_SESSION['access_token']);
error_log(__LINE__);
echo json_encode([ 'event_id' => $event_id ]);
}
catch(Exception $e) {
error_log($e->getMessage());
header('Bad Request', true, 400);
echo json_encode(array( 'error' => 1, 'message' => $e->getMessage() ));
}
google-calendar.api.php
class GoogleCalendarApi
{
public function GetAccessToken($client_id, $redirect_uri, $client_secret, $code) {
$url = 'https://accounts.google.com/o/oauth2/token';
$curlPost = 'client_id=' . $client_id . '&redirect_uri=' . $redirect_uri . '&client_secret=' . $client_secret . '&code='. $code . '&grant_type=authorization_code';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
$data = json_decode(curl_exec($ch), true);
$http_code = curl_getinfo($ch,CURLINFO_HTTP_CODE);
if($http_code != 200)
throw new Exception('Error : Failed to receieve access token');
return $data;
}
public function GetUserCalendarTimezone($access_token) {
$url_settings = 'https://www.googleapis.com/calendar/v3/users/me/settings/timezone';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url_settings);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer '. $access_token));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$data = json_decode(curl_exec($ch), true); //echo '<pre>';print_r($data);echo '</pre>';
$http_code = curl_getinfo($ch,CURLINFO_HTTP_CODE);
if($http_code != 200)
throw new Exception($http_code);
return $data['value'];
}
public function GetCalendarsList($access_token) {
$url_parameters = array();
$url_parameters['fields'] = 'items(id,summary,timeZone)';
$url_parameters['minAccessRole'] = 'owner';
$url_calendars = 'https://www.googleapis.com/calendar/v3/users/me/calendarList?'. http_build_query($url_parameters);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url_calendars);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer '. $access_token));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$data = json_decode(curl_exec($ch), true); //echo '<pre>';print_r($data);echo '</pre>';
$http_code = curl_getinfo($ch,CURLINFO_HTTP_CODE);
if($http_code != 200)
throw new Exception('Error : Failed to get calendars list');
return $data['items'];
}
//'primary', $event['title'], $event['all_day'], $event['event_time'], $event['attendees'], $user_timezone, $_SESSION['access_token']
public function CreateCalendarEvent($calendar_id, $summary, $all_day, $event_time, $event_attendees, $event_timezone, $access_token) {
$url_events = 'https://www.googleapis.com/calendar/v3/calendars/' . $calendar_id . '/events';
$curlPost = array('summary' => $summary);
if($all_day == 1) {
$curlPost['start'] = array('date' => $event_time['event_date']);
$curlPost['end'] = array('date' => $event_time['event_date']);
}
else {
$curlPost['start'] = array('dateTime' => $event_time['start_time'], 'timeZone' => $event_timezone);
$curlPost['end'] = array('dateTime' => $event_time['end_time'], 'timeZone' => $event_timezone);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url_events);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer '. $access_token, 'Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($curlPost));
$data = json_decode(curl_exec($ch), true);
$http_code = curl_getinfo($ch,CURLINFO_HTTP_CODE);
if($http_code != 200)
throw new Exception($http_code);
return $data['id'];
}
}
I hope this make sense as I have tried so many attempts that I have lost track of it.
The Form Data that is send (after what i can figure out from google chrome is the following:
event_details[title]: Privat
event_details[event_time][start_time]: 2018-08-11T13:00:00
event_details[event_time][end_time]: 2018-08-11T15:30:00
event_details[event_time][event_date]:
event_details[attendees][0][email]: test#dds-slagelse.dk
event_details[all_day]: 0
ADyson, thanks for your help / hint. It was the missing curl that was the solution.
$curlPost['attendees'] = $event_attendees;
I hope it wont be to much of a bother, but it seems that it does not send out the invites for the events as hoped, even thought it does add the "guests" to the event.
The starting point for this solution is found here: http://usefulangle.com/post/29/google-calendar-api-create-event-php and if someone can please helt me to get * "sendNotifications"=>true * inserted or set correctly I would be very thankful. (would like to see how that parameter / function is set).
Best Regards
Jess
This help to me:
$curlPost['attendees'] = [['email'=>$event_data['attendees']]];
$curlPost['sendUpdates'] = array("sendUpdates"=>"all");
$curlPost['reminders'] = array('useDefault' => true, 'overrides' => array('method' => 'email','minutes' => 20));

how to use api key parameter to post json data with manual api key using curl

How do I insert json post data with curl and api key parameter.
In the following code I'm trying to add an apikey parameter in the url.
index.php:
$data = array(
// 'name' => '100236',
// 'age' => '265',
'nric' => '123546',
'id' => '266',
'fullname'=>'sairam',
'gender' => 'M',
'password' => '123546',
'address'=>'jlnklmanalpoi',
'postcode' => '502103',
'state' => 'telangana',
'contact1'=>'+60123654',
'email' => 'email#email.com',
'rank'=>'AM',
'expirydate'=>'14-07-2017'
);
$post_json = json_encode($data);
$api_key = '99999your9999api999keyd4eae7c3';
$endpoint = 'http://localhost/apib/data.php?key=.$api_key ';
$ch = #curl_init();
#curl_setopt($ch, CURLOPT_POST, true);
#curl_setopt($ch, CURLOPT_POSTFIELDS, $post_json);
#curl_setopt($ch, CURLOPT_URL, $endpoint);
#curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
#curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = #curl_exec($ch);
$status_code = #curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curl_errors = curl_error($ch);
#curl_close($ch);
echo "curl Errors: " . $curl_errors;
echo "\nStatus code: " . $status_code;
echo "\nResponse: " . $response;
?>
am unable to use api key below page :
this is end point data.php
$_POST = json_decode(file_get_contents('php://input'), true);
if (isset($_POST['nric'],$_POST['id'],$_POST['fullname'],$_POST['gender'],$_POST['password'],$_POST['address'],$_POST['postcode'],$_POST['state'],$_POST['contact1'],$_POST['email'],$_POST['rank'],$_POST['expirydate'])) {
global $db;
$db = mysqli_connect("localhost", "root", "", "ilde");
if($db === false)
{
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$nric=mysqli_real_escape_string($db,$_POST["nric"]);
$id =(int)$_POST["id"];
$fullname=mysqli_real_escape_string($db,$_POST["fullname"]);
$gender=mysqli_real_escape_string($db,$_POST["gender"]);
i want to use secure url with apikey manually.please help me to solve this. how to insert json post data with curl and api key parameter.please help me below is my code i am trying to add apikey parameter in url
Try below endpoint:
$endpoint = 'http://localhost/apib/data.php?key='.$api_key.' ';

salesforce rest api invalid session id error when using access token

I am trying to retrieve data from salesforce using the REST api and CURL in PHP.
I perform the authentication request and recieve an 'instance_url' and 'access_token' but after performing a query request using those, i receive an "INVALID_SESSION_ID" error.
my authentication request code:
function get_sf_auth_data() {
$post_data = array(
'grant_type' => 'password',
'client_id' => 'xxxxxxxxxxxxxxxxxxxxxx', //My client id (xxx... for this example)
'client_secret' => '111111111111', // My client secret (111... for this example)
'username' => 'my_user_name',
'password' => 'my_user_password'
);
$headers = array(
'Content-type' => 'application/x-www-form-urlencoded;charset=UTF-8'
);
$curl = curl_init('https://login.salesforce.com/services/oauth2/token');
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
$response = curl_exec($curl);
curl_close($curl);
// Retrieve and parse response body
$sf_access_data = json_decode($response, true);
echo '*********' . $sf_response_data['instance_url'] . '********';
echo '*********' . $sf_response_data['access_token'] . '********';
return $sf_access_data;
}
My query request code:
function get_user_sfid($sf_access_data, $user_id_number){
$sql = "SELECT Id, Name
FROM Account
WHERE ID__c = '$user_id_number'";
$url = $sf_access_data['instance_url'] . '/services/data/v20.0/query/?q=' . urlencode($sql);
$headers = array(
'Authorization' => 'OAuth ' . $sf_access_data['access_token']
);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$json_response = curl_exec($curl);
curl_close($curl);
var_dump($json_response); // This prints out the response where i got the error
$response = json_decode($json_response);
return $response['id'];
}
The response to the query request as is:
[{"message":"Session expired or invalid","errorCode":"INVALID_SESSION_ID"}]
I have also tried using this guide (http://developer.force.com/cookbook/recipe/interact-with-the-forcecom-rest-api-from-php) as reference but it uses an "authorization_code" authentication and not a password one.
EDIT
The app has full access in salesforce and both api version and authentication data are correct
I found the solution.
I defined my headers array as:
$headers = array(
"Authorization" => "OAuth " . $sf_access_data['access_token']
);
When i should have defined it as:
$headers = array(
"Authorization: OAuth " . $sf_access_data['access_token']
);

Alternative way to write cUrl in PHP

I am trying to create a service on hook.io to load token from another API.
public function loadToken()
{
$computedHash = base64_encode(hash_hmac ( 'md5' , $this->authServiceUrl , $this->password, true ));
$authorization = 'Authorization: Bearer '.$this->username.':'.$computedHash;
$curl = curl_init();
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, '');
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json' , $authorization ));
curl_setopt($curl, CURLOPT_URL, $this->authServiceUrl);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($curl);
$obj = json_decode($result);
$info = curl_getinfo($curl);
curl_close($curl);
if($info['http_code'] != '200')
{
// print error from the server
echo($obj);
return NULL;
}
return $obj;
}
But it turns out hook.io doesn't support cUrl in PHP . I know it can done directly with php but i don't know how.
edit :
i used file_get_contents now it's give some other error now.
$username = '';
$password = '';
$authServiceUrl = '';
$computedHash = base64_encode(hash_hmac ( 'md5' , $authServiceUrl , $password, true ));
$authorization = 'Authorization: Bearer '.$username.':'.$computedHash;
// Create map with request parameters
// Build Http query using params
// Create Http context details
$contextData = array (
'method' => 'POST',
'header' => "Content-Type: application/json". $authorization ,
);
// Create context resource for our request
$context = stream_context_create (array ( 'http' => $contextData ));
// Read page rendered as result of your POST request
$result = file_get_contents (
$authServiceUrl, // page url
false,
$context);
I have added the error in comments below
Actually, hook.io has curl support as far as I know. But if you want to try other alternatives, you can use file_get_contents. It has support for custom context and parameters.
$opts = [
'http' => [
'method' => 'POST',
'headers' => ['Authorization' => 'Bearer ' . $this->username . ':' . $computedHash]
]
];
$context = stream_context_create($opts);
$file = file_get_contents('http://www.hook.io/example/', false, $context);

mailchimp http error: you must specify a apikey

I'm the using MailChimp 2.0 api and trying to post a lists/subscribe call using php. The call is returning an error "You must specify a apikey value".
Here's the code that makes the post:
function json_post ($url, $params)
{
print '<p>url = ' . $url . '</p>';
$data = json_encode ($params);
print '<p>data = ' . $data . '</p>';
$handle = curl_init ($url);
curl_setopt ($handle, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt ($handle, CURLOPT_POST_FIELDS, $data);
curl_setopt ($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($handle, CURLOPT_HTTPHEADER, array ('Content-Type: application/json',
'Content-Length: ' . strlen($data_string)));
$result = curl_exec ($handle);
print '<p>curl_error: ' . curl_errno ($handle) . '</p>';
return $result;
}
The print statements show:
url = https://us10.api.mailchimp.com/2.0/lists/subscribe.json
data = {"apikey":"...","id":"...","email":{"email":"test1#abc.com"},"merge_vars":{"groupings":{"name":"test"}}}
curl_error: 0
{"status":"error","code":-100,"name":"ValidationError","error":"You must specify a apikey value"}
I presume there's something wrong with the syntax. The api key is cut & pasted from my mailchimp account page. I've tried it with and without the -us10 suffix. Any ideas?
To subscribe:
$email='';
$apikey='';
$listId='';
$data = array(
'email_address'=>$email,
'apikey'=>$apikey,
'merge_vars' => array(),
'id' => $listId,
'double_optin' => false,
'update_existing' => true,
'replace_interests' => false,
'send_welcome' => false,
'email_type' => 'html'
);
$submit_url = "http://us6.api.mailchimp.com/1.3/?method=listSubscribe";
$payload = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $submit_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, urlencode($payload));
$result = curl_exec($ch);
curl_close ($ch);
$data = json_decode($result);
if (isset($data->error) and $data->error){
//Error
} else {
//Ok
}
Cases where you get "API Key Missing" but the API Key is definitely there usually comes from JSON Syntax errors, which MailChimp doesn't catch specifically. You'll want to make sure that JSON isn't getting double-encoded or anything like that.
In this case, it is probably CURLOPT_POST_FIELDS -- the actual PHP Constant you're looking for is CURLOPT_POSTFIELDS.
You should use Guzzle or another HTTP library to ensure you're not double-encoding your JSON or otherwise getting tripped up by the Curl library's verbosity.

Categories