PHP cURL body elements - php

I am trying to connect our invoice service API to send e-invoices. I have API instructions, but I have no idea how to put all relevant fields to cURL body in the right way. I am using PHP form like this:
$curl = curl_init($url);
// Set the CURLOPT_RETURNTRANSFER option to true
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// Set the CURLOPT_POST option to true for POST request
curl_setopt($curl, CURLOPT_POST, true);
// Set the CURLOPT_INSECURE to disable certificate
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
// Set the request data as JSON using json_encode function
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_INFILESIZE, $fileSize);
// Set custom headers for RapidAPI Auth and Content-Type header
curl_setopt($curl, CURLOPT_HTTPHEADER, [
'x-api-mandator-uuid: mandator-api-id',
'x-api-key: mandator-api-key',
'Content-Type: application/json'
]);
// Execute cURL request with all previous settings
$response = curl_exec($curl);
// Close cURL session
curl_close($curl);
This is how body should be formatted:
curl --location --request POST 'https://api.address.here' \
--header 'Content-Type: application/json' \
--header 'x-api-key: API KEY HERE' \
--header 'x-api-mandator-uuid: MANDATOR ID HERE' \
--data-raw '{
"routingInstructions": {
"primaryDeliveryChannel": 3,
"sentUsingChannel": 0,
"eInvoiceNumber": "$customer-e-invoice address",
"eInvoiceOperator": "$eoperator"
},
"debtors": [
{
"debtorID": "$id",
"debtorType": 2,
"businessName": "$customername",
"businessID": "$businessid",
"businessOffice": "",
"personFirstName": "",
"personLastName": "",
"co": "",
"contactPerson": "",
"personSSN": "",
"postalAddress": {
"countryName": "Suomi",
"countryCode": "FI",
"streets": [
"$customer-street-addr"
],
"city": "$customer-city",
"zip": "$customer-zip"
},
"emails": [
"$customer-email"
],
"phoneNumbers": [
"$customer-phone"
]
}
],
"invoiceFile": {
"data": "PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZ....",
"filename": "invoice - einlasku.xml"
},
"attachments": [],
"setAssignmentInStatus": 1
I have invoice file in xml-format and it should be Base64 coded.
Can somebody guide me how to put all this info to cURL body in correct way?

In the PHP Curl documentation, there is CURLOPT_POSTFIELDS which accepts key=>value array so in your case something like
curl_setopt($curl, CURLOPT_POSTFIELDS, [
'routingInstructions' => [
'primaryDeliveryChannel' => 3
...
],
'debtors' => []
...
]);
However I can see you need to send file, which can be sent using CURLFile.
I am finding easier to use library such as Guzzle for advanced HTTP Post.

Related

perform a curl request with PHP

I am trying to make a call to an API using curl (from the backend of my application directly). It is the first time I use it so I digged around to learn how to do it.
The documentation say that this is the request:
curl --location -g --request POST '{{url}}/api/rest/issues/' \
--header 'Authorization: {{token}}' \
--header 'Content-Type: application/json' \
--data-raw '{
"summary": "This is a test issue",
"description": "This is a test description",
"category": {
"name": "General"
},
"project": {
"name": "project1"
}
}'
This should be the code if I execute it from the terminal (if I get it right). If I want to move execute it in a php script I have to convert this to something like:
<?php
$pars=array(
'nome' => 'pippo',
'cognome' => 'disney',
'email' => 'pippo#paperino.com',
);
//step1
$curlSES=curl_init();
//step2
curl_setopt($curlSES,CURLOPT_URL,"http://www.miosito.it");
curl_setopt($curlSES,CURLOPT_RETURNTRANSFER,true);
curl_setopt($curlSES,CURLOPT_HEADER, false);
curl_setopt($curlSES, CURLOPT_POST, true);
curl_setopt($curlSES, CURLOPT_POSTFIELDS,$pars);
curl_setopt($curlSES, CURLOPT_CONNECTTIMEOUT,10);
curl_setopt($curlSES, CURLOPT_TIMEOUT,30);
//step3
$result=curl_exec($curlSES);
//step4
curl_close($curlSES);
//step5
echo $result;
?>
that I will adapt to my needs. Is this correct? Is there another way to keep it as simple as the documented curl request?
I would use an HTTP client like Guzzle.
$client = new \GuzzleHttp\Client();
$response = $client->request('POST', 'http://www.miosito.it', [
'form_params' => [
'nome' => 'pippo',
'cognome' => 'disney',
'email' => 'pippo#paperino.com',
]
]);
echo (string) $response->getBody();
There are several ways to do curl. Your code seems okay, you can try out my code too.
$pars=array(
'nome' => 'pippo',
'cognome' => 'disney',
'email' => 'pippo#paperino.com',
);
If sometimes you need to send json encoded parameters then use below line.
// $post_json = json_encode($pars);
Curl code as per below
$apiURL = 'http://www.miosito.it';
$ch = #curl_init();
#curl_setopt($ch, CURLOPT_POST, true);
#curl_setopt($ch, CURLOPT_POSTFIELDS, $pars);
#curl_setopt($ch, CURLOPT_URL, $apiURL);
#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 "<br>Curl Errors: " . $curl_errors;
echo "<br>Status code: " . $status_code;
echo "<br>Response: " . $response;
Please let me know if there you need something else.

Google MyBusiness REST API update posts PATCH method request error

I want to update a specific post on google my business. I already got the account_id, location_id, and the post_id. I am using the url https://mybusiness.googleapis.com/v4/{name=accounts/*/locations/*/localPosts/*} and doing PATCH method in my backend. But when I do an update it gets me an
"code": 2,
"field": "update_mask",
"message": "update_mask is required"
I cant understand the update_mask thing in google. Can someone tell me what I should do about this? I am using laravel btw and curl library for http request. Here is my code
public function updatePost(Request $request ){
$url = 'https://mybusiness.googleapis.com/v4/accounts/'.$request->account_id.'/locations/'.$request->location_id.'/localPosts/'.$request->post_id;
$body['languageCode'] = "en-US";
$body['summary'] = $request->summary;
$body['callToAction'] = ['actionType'=> 'Call'];
$body['media'][] = ['mediaFormat'=> 'PHOTO', "sourceUrl" => $request->imageURL];
//Static Token only since for testing
$headers = array(
'Content-Type: application/json',
'Accept: application/json',
'Authorization: Bearer '.'ya29.a0AfH6SMB_1iUG11qj72p-pn_gCkOjUEf-ctvTGnJZ6FNTUy0Q3dYP54TMvI0cr8o0ditLp7CaWOUX5CTWn4v2kyQ-hZKSyuEJu_rBYX7uxvX373I9iVRxoypIZ6xhWDYTr-A_DHcaxGPVs1yz5u-fkYvU-xDppkASNbg'
);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PATCH');
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($body));
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($curl);
dd($response);
}
The full message
{
"error": {
"code": 400,
"message": "Request contains an invalid argument.",
"status": "INVALID_ARGUMENT",
"details": [
{
"#type": "type.googleapis.com/google.mybusiness.v4.ValidationError",
"errorDetails": [
{
"code": 2,
"field": "update_mask",
"message": "update_mask is required"
}
]
}
]
}
}
The docs for patch method
https://developers.google.com/my-business/reference/rest/v4/accounts.locations.localPosts/patch
You need to set query parameters for the upateMask like following.
https://mybusiness.googleapis.com/v4/accounts/2323232334343/locations/232323232/localPosts/23232323232?updateMask=summary
However, I can not edit the other field, for example, title.
Did you find the way of editting the others?
Its clear state that you need to set query parameter 'updatemask' to a field that you want to update. Check this doc for details.

Razorpay x Api call BAD_REQUEST_ERROR using Laravel

I am trying to integrate razorpay x api for creating contacts and this is the sample api request data from razorpay. reference_id and notes are optional.
curl -u <YOUR_KEY>:<YOUR_SECRET> \
-X POST https://api.razorpay.com/v1/contacts \
-H "Content-Type: application/json" \
-d '{
"name":"Gaurav Kumar",
"email":"gaurav.kumar#example.com",
"contact":"9123456789",
"type":"employee",
"reference_id":"Acme Contact ID 12345",
"notes":{
"notes_key_1":"Tea, Earl Grey, Hot",
"notes_key_2":"Tea, Earl Grey… decaf."
}
}'
and below is my curl function data sent to razorpay.
$user=User::find($request->input('user_id'));
$payload= '{
"name":"'.$user->name.'",
"email":"'.$user->email.'",
"contact":"'.$user->mobile_number.'"
"type":"customer"
}';
$key="test_key";
$secret="secret_key";
$url = 'https://api.razorpay.com/v1/contacts';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type:application/json']);
curl_setopt($ch, CURLOPT_USERPWD, $key . ":" . $secret);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
print_r($result);
curl_close($ch);
I am getting response as name field is required, eve though I have sent all the request fields in the request parameter. Please suggest me if my curl function is correct or not. below is the response from api call
{
"error":
{
"code": "BAD_REQUEST_ERROR",
"description": "The name field is required.",
"metadata": {},
"field": "name"
}
}
Please specify the request method:
curl_setopt($ch, CURLOPT_POST, 1);

I can't retrieve the intent from my wit.ai call

I am starting to use Wit.ai to enhance a small bot I made. I am able to make a request to the wit.ai by doing:
function sendToWitAI($query){
$witRoot = "https://api.wit.ai/message?";
$witVersion = "20170822";
$witURL = $witRoot . "v=" . $witVersion . "&q=" . $query;
$ch = curl_init();
$header = array();
$header[] = "Authorization: Bearer xxxxxxxx";
curl_setopt($ch, CURLOPT_URL, $witURL);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER,$header);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);
curl_close ($ch);
return $server_output;
}
However, when receiving the output I just get the same message I sent. For example, if the user types "I want to make a reservation" my $server_output is now "I want to make a reservation" after all that chunk of code above.
Still, I know it reaches wit successfully because I can see it in the logs there and I know the bot says (from wit.ai):
{
"confidence": null
"action": null
"type": "action"
}
On top of this, if I just do a curl with the same query:
curl -XPOST 'https://api.wit.ai/converse?v=20170822&session_id=123abc&q=I%20want%20to%20make%20a%20reservation' \
> -H "Content-Type: application/json" \
> -H "Accept: application/json" \
> -H 'Authorization: Bearer xxxxxxxx'
I get the following output:
{
"confidence" : null,
"type" : "action",
"action" : null,
"entities" : {
"contact" : [ {
"suggested" : true,
"value" : "reservation",
"type" : "value",
"confidence" : 0.95062723294726
} ],
"intent" : [ {
"confidence" : 0.98638622681962,
"value" : "make_reservation"
} ]
}
}
I'm not sure where my error is or what I'm missing to properly handle use of the value like I need.
I've been googling non-stop but I can't find anything after they (wit.ai) deprecated "stories" and there's seldom anything about handling the response.
You're using 2 different end points: /message and /converse.
The log you pasted is from /converse so I'm not even sure your first call went through. Can you try a curl to /message like this
curl -XGET 'https://api.wit.ai/message?v=20170307&q=I%20want%20to%20make%20a%20reservation' \
-H 'Authorization: Bearer $TOKEN'

SSL Curl POST of JSON data from Google App Engine for PHP

I'm trying to use the MailChimp API (Version 2) to add an email subscriber to a List. I'm using the Google App Engine with Version 5.5 of PHP.
The response the API Server is supposed to give me should look something like below:
{
"email": "example email",
"euid": "example euid",
"leid": "example leid"
}
However, I don't get any response or error message from the server. I do get false when I use var_dump.
Here is my code:
$api_url_str = "https://us6.api.mailchimp.com/2.0/lists/subscribe";
$api_data_str = '{
"apikey": "'.$my_api_key.'",
"id": "'.$my_list_id.'",
"email": {"email": "'.$my_email_addr.'"},
"double_optin": false,
"merge_vars":
{
"FNAME": "'.$my_first_name.'",
"LNAME": "'.$my_last_name.'",
"OPTIN_IP": "'.$my_ip_address.'",
"OPTIN_TIME": "2015-05-22 10:22:09"
}
}';
$ch = curl_init($api_url_str);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $api_data_str);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($api_data_str)));
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$api_response_str = curl_exec($ch);
curl_close($ch);
The above code works (as expected) when I run it on my local PC (also PHP 5.5).
Anyone have this issue?
After trying a couple of things, I stumbled on the following solution that works (I got the relevant code from here).
Here's the full code:
$api_url_str = "https://us6.api.mailchimp.com/2.0/lists/subscribe";
$api_data_str = '{
"apikey": "'.$my_api_key.'",
"id": "'.$my_list_id.'",
"email": {"email": "'.$my_email_addr.'"},
"double_optin": false,
"merge_vars":
{
"FNAME": "'.$my_first_name.'",
"LNAME": "'.$my_last_name.'",
"OPTIN_IP": "'.$my_ip_address.'",
"OPTIN_TIME": "2015-05-22 10:22:09"
}
}';
$json_data = $api_data_str;
$context = array(
'http' => array(
'user_agent' => 'PHP-MCAPI/2.0',
'method' => 'POST',
'header' => "Content-type: application/json\r\n".
"Connection: close\r\n" .
"Content-length: " . strlen($json_data) . "\r\n",
'content' => $json_data
)
);
$context = stream_context_create($context);
$api_response_str = file_get_contents($api_url_str, false, $context);
I'm not sure if it's prone to the breakage I've just recently experienced with CURL on Google PHP App Engine though, but for now it will have to do. I had a test script that I used to test Mandrill mail sends that worked with App Engine about a month ago, but it doesn't anymore, probably the same issue with CURL.
I hope this helps someone with the same challenge.

Categories