This is my code:
$contact_data = json_encode(array(
"name" => "Jimmy Jimmy",
"email" => "jimmy#example.com",
"phone" => "555-555-555",
"mobile" => "312-312-213"
));
$url = $domain."api/v2/contacts";
$ch = curl_init($url);
$header[] = "Content-type: application/json";
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_USERPWD, "$apiKey");
curl_setopt($ch, CURLOPT_POSTFIELDS, $contact_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec($ch);
$info = curl_getinfo($ch);
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$headers = substr($server_output, 0, $header_size);
$response = substr($server_output, $header_size);
if($info['http_code'] == 201) {
echo "Contact created successfully, the response is given below \n";
echo "Response Headers are \n";
echo $headers."\n";
echo "Response Body \n";
echo "$response \n";
} else {
if($info['http_code'] == 404) {
echo "Error, Please check the end point \n";
} else {
echo "Error, HTTP Status Code : " . $info['http_code'] . "\n";
echo "Headers are ".$headers."\n";
echo "Response is ".$response;
}
}
curl_close($ch);
When I executed this piece of code , I received this errors message:
Response is {"description":"Validation failed","errors":[{"field":"last_name","message":"It should be a/an String","code":"missing_field"},{"field":"life_cycle_status","message":"It should be a/an String","code":"missing_field"}]}
The documentation nothing mentioned about these fields : last_name & life_cycle_status to create a new contact in freshdesk. Any idea what am i doing wrong ? thx
[UPDATE]
$contact_data = json_encode(array(
"name" => "Jimmy Jimmy",
"email" => "jimmy#example.com",
"phone" => "555-555-555",
"mobile" => "312-312-213"
"life_cycle_status" => "asdasdsa",
"last_name" =>"dasdasdad"
));
With these new items, I got this message error:
Response is {"description":"Validation failed","errors":[{"field":"life_cycle_status","message":"Unexpected/invalid field in request","code":"invalid_field"},{"field":"last_name","message":"Unexpected/invalid field in request","code":"invalid_field"}]}
These fields are not default for the Freshdesk Contact entity but are, probably, defined as required in the backend (Check Admin > Customer fields in the backend of Freshdesk)
This means we have to define them as custom_fields as indicated in the Freshdesk API documentation here.
This means your POST array would look something like this
$contact_data = json_encode(array(
'name' => 'Jimmy Jimmy',
'email' => 'jimmy#example.com',
'custom_fields' => [
// put all your custom fields here
'last_name' => 'Jimmy',
'life_cycle_status' => 'value'
]
));
Well you already have the answer - you did read that error message yes?
Response:
{
"description": "Validation failed",
"errors":[
{
"field":"last_name",
"message":"It should be a/an String",
"code":"missing_field"
},
{
"field":"life_cycle_status",
"message":"It should be a/an String",
"code":"missing_field"
}
]
}
Meaning:
last_name and life_cycle_status both need to be a String and cannot be empty.
Related
I'm building a simple domain availability checker using the Godaddy api.
I'm using Laravel 9 for the application.
It gives back available and already registered results, but if I add a string without domain extension like: somename
so no .com or.org etc. then I get an ("Undefined array key "available") error message.
On my view file I only have a simple form with one input field where the user can enter the domain name to be checked.
In my controller I validate the input:
$validator = Validator::make($request->all(), [
'userDomain' => ['required', 'string', 'max:191']
]);
I also have my API keys and base url stored in variables:
$API_KEY_OTE = "apikey";
$API_SECRET_OTE = "apisecret";
$OTE_BASE_URL = "https://api.ote-godaddy.com";
Then I remove some unwanted characters from the input
$request->userDomain = str_replace('www.', '', $request->userDomain);
$request->userDomain = str_replace('http://', '', $request->userDomain);
$request->userDomain = str_replace('https://', '', $request->userDomain);
I put together the url for curl like this:
$url = $OTE_BASE_URL . "/v1/domains/available?domain=" . $request->userDomain;
Then I have the curl settings like this:
$header = array(
'Authorization: sso-key '.$API_KEY_OTE.':'.$API_SECRET_OTE.''
);
$ch = curl_init();
$timeout = 60;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
$result = curl_exec($ch);
curl_close($ch);
$checkDomain = json_decode($result, true);
Then i check the result with a series of if / else if statements:
if($checkDomain['available'] == 1 || $checkDomain['available'] == true) {
return redirect()->back()->with('successMsg', 'The domain name ' . $request->userDomain . ' is available! Click here to register it on Godaddy!');
} else if($checkDomain['available'] == '' || $checkDomain['available'] == 0 || $checkDomain['available'] == false) {
return redirect()->back()->with('failureMsg', 'Sorry! The domain name ' . $request->userDomain . ' is already registered! Try a different name.');
}
else if($checkDomain['code']) {
return redirect()->back()->with('failureMsg', $checkDomain['fields'][0]['message']);
} else {
return redirect()->back()->with('failureMsg', 'Please enter a valid domain name!');
}
This is a successful response body that comes from godaddy:
{
"available": true,
"currency": "USD",
"definitive": true,
"domain": "string",
"period": 0,
"price": 0
}
and this is an invalid response body:
{
"code": "string",
"fields": [
{
"code": "string",
"message": "string",
"path": "string",
"pathRelated": "string"
}
],
"message": "string"
}
You must first check if it's error response or success response, only then try to use one of it's keys:
if (isset($checkDomain['available'])) {
if (!empty($checkDomain['available'])) {
return redirect()->back()->with('successMsg', 'The domain name ' . $request->userDomain . ' is available! Click here to register it on Godaddy!');
}
return redirect()->back()->with('failureMsg', 'Sorry! The domain name ' . $request->userDomain . ' is already registered! Try a different name.');
} elseif (isset($checkDomain['code'])) {
return redirect()->back()->with('failureMsg', $checkDomain['fields'][0]['message']);
}
return redirect()->back()->with('failureMsg', 'Please enter a valid domain name!');
I recently work with kraken.io API and I'm trying to integrate this API wuth my PHP CodeIgniter framework. So I followed the documentation but I got stuck when I used curl
This is my source code below ..
require_once(APPPATH.'libraries/kraken-php-master/Kraken.php');
$kraken = new Kraken("SOME_KEY", "SOME_SECRET");
$params = array(
"file" => base_url()."include/".$dataIn['logo'],
"wait" => true
);
$dataj='{"auth":{"api_key": "SOME_KEY", "api_secret": "SOME_SECRET"},"file":'.base_url()."include/".$dataIn['logo'].',wait":true}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.kraken.io/v1/upload");
curl_setopt($ch, CURLOPT_HTTPHEADER,array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataj);
$response = curl_exec($ch);
curl_close($ch);
$data = $kraken->upload($params);
print_r($response);exit();
And I got this result
"{"success":false,"message":"Incoming request body does not contain a valid JSON object"}1"
So can anyone please help me,
And thanks in advance,
DONT POST YOUR API_KEY AND API_SECRET
The error message is quite clear, your json object is not valid. For instance this would be a valid JSON object for your request:
{
"auth": {
"api_key": "SOME",
"api_secret": "SECRET"
},
"file": "somefile.txt",
"wait": true
}
In your php code you are setting up a $params array but then you don't use it. Try this:
$dataj='{"auth":{"api_key": "SOME_KEY", "api_secret": "SOME_SECRET"},"file":"' . $params["file"]. '", "wait":true}';
You can validate your JSON HERE
You should use json_encode function to generate your JSON data
$dataj = json_encode([
"auth" => [
"api_key" => "API_KEY",
"api_secret" => "API_SECRET"
],
"file" => base_url() . "include/" . $dataIn['logo'],
"wait" => true
]);
EDIT:
Here is an example from https://kraken.io/docs/upload-url so you don't need to use curl
require_once("Kraken.php");
$kraken = new Kraken("your-api-key", "your-api-secret");
$params = array(
"file" => "/path/to/image/file.jpg",
"wait" => true
);
$data = $kraken->upload($params);
if ($data["success"]) {
echo "Success. Optimized image URL: " . $data["kraked_url"];
} else {
echo "Fail. Error message: " . $data["message"];
}
I am using SparkPost PHP API to send e-mail to recipient but I am facing this error. Currently I have set up all the necessary field but I still have problems with large e-mails. I can easily send small text but I'm having difficulties with large data.
[{"message":"required field is missing","description":"At least one of 'text' or 'html' needs to exist in 'content'","code":"1400"}]
My code is:
for ($j = 0; $j < count($result1arr); $j++) {
try {
SparkPost::setConfig(["key" => "XXXXX"]);
$results = Transmission::send(array(
"from" => "test#universityfood.co",
"html" => $resultarr['mailBody'],
"text" => $resultarr['mailBody'],
"subject" => $resultarr['subject'],
"recipientList" => $result1arr[$j]['groupName']
));
$_SESSION['success_message'] = 'Email sended successfully to Recipient List with ID : ' . $data['recipients_id'];
$qry = "DELETE from mailQueue where mailQueueId={$result1arr[$j]['mailQueueId']}";
$res = $conn->query($qry);
$sql1 = "INSERT INTO sendMailHistory (schoolName,noOfMailSent) VALUES ('{$result1arr[$j]['originalGroupId']}','{$results['results']['total_accepted_recipients']}')";
$result1 = $conn->query($sql1);
$chc = curl_init();
curl_setopt($chc, CURLOPT_URL, "https://api.sparkpost.com/api/v1/recipient-lists/{$result1arr[$j]['groupName']}");
curl_setopt($chc, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($chc, CURLOPT_HEADER, FALSE);
curl_setopt($chc, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($chc, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($chc, CURLOPT_HTTPHEADER, array(
"Accept: application/json",
"Authorization: XXXXX"
));
$response = curl_exec($chc);
curl_close($chc);
header('Location: ../index.php');
exit;
return true;
} catch (\Exception $exception) {
echo $exception->getMessage();
}
}
This is happening because $resultarr['mailBody'] is not defined.
Are you sure the array $resultarr exists? If so, the mailBody element must be missing.
You may supply either a text portion or an html portion, or both. But if you supply neither you will get the error: At least one of 'text' or 'html' needs to exist in 'content'.
In this case neither are being supplied because $resultarr['mailBody'] being undefined causes the text and html elements of the array to be undefined.
I am trying to integrate our app with Exact Online website using OAuth2,or more specifically i am trying to create hour registration which should include "Employee","Project","Hours","Hours type".
function registerTime($access_token_for_data) {
//$dataToFilterAccounts = array('$filter' => 'IsSales eq true');
$dataToRetrieveFromEmployees = array('$select' => 'ID');
// $queryToFilterAccounts = http_build_query($dataToFilterAccounts);
$queryToRetrieveFromEmployees = http_build_query($dataToRetrieveFromEmployees);
// $dataToFilterItems = array('$filter' =>'IsSalesItem eq true');
$dataToRetrieveProjects = array('$select' => 'ID');
//$queryToFilterItems = http_build_query($dataToFilterItems);
$queryToRetrieveProjects = http_build_query($dataToRetrieveProjects);
$urlProjects = 'https://start.exactonline.nl/api/v1/638842/project/Projects';
$urlEmployees = 'https://start.exactonline.nl/api/v1/638842/payroll/Employees';
$curlProjects = curl_init($urlProjects);
$curlEmployees = curl_init($urlEmployees);
$headers = array(
'Authorization: Bearer ' . $access_token_for_data,
'Accept: application/json',
'Content-type: application/json'
);
curl_setopt($curlProjects, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curlProjects, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curlProjects, CURLOPT_URL, $urlProjects . '?' . $queryToRetrieveProjects);
curl_setopt($curlProjects, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($curlEmployees, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curlEmployees, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curlEmployees, CURLOPT_URL, $urlEmployees . '?' . $queryToRetrieveFromEmployees);
curl_setopt($curlEmployees, CURLOPT_CUSTOMREQUEST, 'GET');
$resultProjects = curl_exec($curlProjects);
$resultEmployees = curl_exec($curlEmployees);
$projectsData = json_decode($resultProjects, true);
$projectID = $projectsData["d"]["results"]["0"]["ID"];
$employeesData = json_decode($resultEmployees, true);
$employeeID = $employeesData["d"]["results"]["0"]["ID"];
curl_close($curlProjects);
curl_close($curlEmployees);
$urlTimeTransaction = 'https://start.exactonline.nl/api/v1/638842/project/TimeTransactions';
$curlTimeTransacation = curl_init($urlTimeTransaction);
$content = json_encode(array("Project" => $projectID, "Employee" => $employeeI));
curl_setopt($curlTimeTransacation, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curlTimeTransacation, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curlTimeTransacation, CURLOPT_POST, true);
curl_setopt($curlTimeTransacation, CURLOPT_POSTFIELDS, $content);
$createdTimeTransaction = curl_exec($curlTimeTransacation);
$status = curl_getinfo($curlTimeTransacation, CURLINFO_HTTP_CODE);
if ($status != 201) {
die("Error: call to URL $curlTimeTransacation failed with status $status, response $createdTimeTransaction, curl_error " . curl_error($curlTimeTransacation) . ", curl_errno " . curl_errno($curlTimeTransacation));
}
echo "HTTP status $status creating time registartion<br/><br/>";
curl_close($curlTimeTransacation);
}
And this is the error i get
Error: call to URL Resource id #56 failed with status 500, response { "error": { "code": "", "message": { "lang": "", "value": "Mandatory: Employee\r\nMandatory: Hours\r\nMandatory: Hour type" } } }, curl_error , curl_errno 0
But when i try to include any of these mandatroy fileds i get:
Error: call to URL Resource id #56 failed with status 400, response { "error": { "code": "", "message": { "lang": "", "value": "Error processing request stream. The property name 'Hours' specified for type 'Exact.Web.Api.Models.TimeTransaction' is not valid." } } }, curl_error , curl_errno 0
please note that /api/v1/638842 contains your division ID. You might want to change that into a variable.
Regarding your problem: please note that the error messages contain text to be consumed by humans. The actual technical names can be different. I always do it the other way around: I query the existing data and look at all fields, and then I know what to send. You can use the Query Tool for Exact Online in the app center of Exact to do the query on REST api of Exact Online (but I am biased because involved).
As Guido pointed out correctly, there is no field named Hours in the TimeTransaction on projects, there is a field named Hours on the manufacturing TimeTransaction. This is a little confusing, especially since the error message isn't very clear.
You need to set Quantity on TimeTransactions in order to specify the hours on a project's time transaction.
I want to create an app with ios platform set up from the .p12 file. How do I do that?
This is the method for creating app:
class AppHandler
{
public $USER_AUTH_KEY = 'Insert your key here';
public function create($name, $apns_p12 = null, $apns_p12_password = null, $gcm_key = null, $android_gcm_sender_id = null)
{
$fields = array(
'name' => $name,
'apns_p12' => $apns_p12,
'apns_p12_password' => $apns_p12_password,
'gcm_key' => $gcm_key,
'android_gcm_sender_id' => $android_gcm_sender_id
);
$fields = json_encode($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/apps");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8',
"Authorization: Basic " . $this->USER_AUTH_KEY));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
try {
$response = curl_exec($ch);
if (!$response) {
throw new Exception("App wasn't created");
}
} catch (Exception $e) {
echo 'Error: ', $e->getMessage(), "\n";
} finally {
curl_close($ch);
}
$response = json_decode($response, true);
$return = array(
'id' => $response['id'],
'basic_auth_key' => $response['basic_auth_key']
);
return $return;
}
...
And this is the method with 2 ways of getting the insides of .p12 file:
public function getP12($pkcs12, $password = NULL): string
{
/*
// Way 1:
$pkcs12 = file_get_contents($pkcs12);
$encoded = base64_encode($pkcs12);
return $encoded;
*/
// Way 2:
$cert_store = file_get_contents($pkcs12);
if (!$cert_store) {
echo "Error: can't read file.\n";
exit;
}
$pkcs12Read = openssl_pkcs12_read($cert_store, $cert_info, $password);
if ($pkcs12Read) {
$result = base64_encode($cert_info['cert']);
return $result;
} else {
echo "Error: can't read cert.\n";
exit;
}
}
According to onesignal's doc I have to send apns_p12 as my apple push notification p12 certificate file, converted to a string and Base64 encoded.
And I do that this way:
$obj = new AppHandler();
$response = $obj->create('TestName', $obj->getP12('cert.p12', 'password'), 'password')
It creates an app with given name, however, the platform is not set up.
What do you mean by "the platform is not set up"? What error are you getting and where?
By the way, I finally gave up trying code the intricacies of APNS programming and instead went with AWS' Simple Notification Service: https://aws.amazon.com/sns. It handles both Apple and Google notifications by using the API to set up topics and subscribers, plus you can send up to 1 million notifications per month free.
Ok, I got it. I simply needed to add apns_env parameter:
$fields = array(
'name' => $name,
'apns_env' => $apns_env,
'apns_p12' => $apns_p12,
'apns_p12_password' => $apns_p12_password,
'gcm_key' => $gcm_key,
'android_gcm_sender_id' => $android_gcm_sender_id
);
And I should've taken insides of the file and converted them to a string and Base64 encoded like that:
public function getP12($pkcs12): string
{
$apns_12 = base64_encode(file_get_contents($pkcs12));
return $apns_12;
}