I have error 400 Invalid endpoint in my code :
$this->load->library('PHPRequests');
$headers = array(
'X-CleverTap-Account-Id' => 'xxxx-xxx-xxx-xxxx',
'X-CleverTap-Passcode' => 'xxx-xxx-xxx',
'Content-Type' => 'application/json; charset=utf-8'
);
$data = '{ "d": [ { "FBID": "34322423", "ts": 1468308340, "type": "event", "evtName": "Product viewed", "evtData": { "Product name": "Casio Chronograph Watch", "Category": "Mens Watch", "Price": 59.99, "Currency": "USD" } } ] }';
$response = Requests::post('https://api.clevertap.com/1/upload', $headers, $data);
echo "<pre>";
print_r($response);
echo "</pre>";
please help me solve this problem
Have you tried the curl example using your API account credentials? My guess is you are not using the correct ones and getting the 400 error.
Once you get the CURL example working then you should be able to modify your PHP code to match.
You can find out more about the authentication here
https://developer.clevertap.com/docs/authentication
Related
I've been trying to implement the FedEx rates and transit times API in a PHP script.
I successfully connected with it to get the bearer token.
But when I try to get rates for a simple shipment, it responds with random gibberish.
I don't even get any errors. That's what frustrating.
Here is my code:
ini_set('display_errors', 1);
error_reporting(-1);
$access_url = 'https://apis-sandbox.fedex.com/oauth/token';
$access_headers = ['Content-Type' => 'application/x-www-form-urlencoded'];
$access_fields = "grant_type=client_credentials&client_id=...&client_secret=...";
$resp = curl_me($access_url, $access_headers, $access_fields);
$access_token = json_decode($resp)->access_token;
$rate_url = 'https://apis-sandbox.fedex.com/rate/v1/rates/quotes';
$rate_hdrs = [
'Authorization' => 'Bearer '.$access_token,
'X-locale' => 'en_US',
'Content-Type' => 'application/json'
];
$rate_flds = '{
"accountNumber": {
"value": "..."
},
"requestedShipment": {
"shipper": {
"address": {
"streetLines": [
"..."
],
"city": "...",
"stateOrProvinceCode": "...",
"postalCode": "...",
"countryCode": "US",
"residential": false
}
},
"recipient": {
"address": {
"postalCode": "...",
"countryCode": "US"
}
},
"shipDateStamp": "2022-12-06",
"pickupType": "DROPOFF_AT_FEDEX_LOCATION",
"requestedPackageLineItems": [{
"declaredValue": {
"amount": 123,
"currency": "USD"
},
"weight": {
"units": "LB",
"value": 12
},
"dimensions": {
"length": 12,
"width": 12,
"height": 12,
"units": "IN"
}
}],
"documentShipment": false,
"packagingType": "YOUR_PACKAGING",
"groupShipment": true
},
"carrierCodes": [
"FDXE"
]
}';
$field = build_post_fields($rate_flds);
$resp = curl_me($rate_url, $rate_hdrs, $field);
var_dump($resp);
Here are the two functions I'm using:
function curl_me($url, $headers, $postfields){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
$response = curl_exec($ch);
echo curl_error($ch);
curl_close($ch);
return $response;
}
function build_post_fields( $data,$existingKeys='',&$returnArray=[]){
if(($data instanceof CURLFile) or !(is_array($data) or is_object($data))){
$returnArray[$existingKeys]=$data;
return $returnArray;
}
else{
foreach ($data as $key => $item) {
build_post_fields($item,$existingKeys?$existingKeys."[$key]":$key,$returnArray);
}
return $returnArray;
}
}
The second function is from Yisrael Dov's answer to this question.
When I used the first function to get the access token, it worked flawlessly. But I can't figure out why the second time I used it responded with: string(176) "��� �#��W朢%jނ��d�]���(R������I���oFgHY�ת��r҆IH/"�Eq�zi����MJ{��6� �..."
I tried all kinds of different was of encoding and decoding the JSON string. But I get gibberish every time.
I've tried running that gibberish through various decoders, but of course they all returned NULL.
I was expecting at least some kind of error or warning.
Any ideas would be appreciated.
$rate_hdrs = [
'Authorization: Bearer '.$access_token,
'X-locale: en_US',
'Content-Type: application/json',
];
look this: PHP cURL custom headers
Thanks to everyone for the awesome input!
I'm new to CURL, so pardon my not recognizing these mistakes.
I combined Sammitch's comments with Walter KT's answer.
Sammitch was right: the response was gzip encoded. I added curl_setopt($ch, CURLOPT_ENCODING, "gzip"); to my function, and finally got the response (with some handy errors to work through).
I also got rid of the build_post_fields() function.
I'm trying to create a new client in my API using php cURL. Clients, products and everything that is created is by POST method. This is my code:
$json='{
"data": {
"type": "customers",
"attributes": {
"tax_registration_number": "5555555550",
"business_name": "Test customer",
"contact_name": "Mr. Test",
"website": "https://www.testurl.pt",
"phone_number": "2299999999",
"mobile_number": "9299999999",
"email": "test#testcustomer.pt",
"observations": "This is only a test",
"internal_observations": "This is good customer",
"not_final_customer": null,
"cashed_vat": null,
"tax_country_region": "PT-MA"
},
"relationships": {
"main_address": {
"data": {
"type": "addresses",
"id": 1
}
},
"addresses": {
"data": [
{
"type": "addresses",
"id": 1
},
{
"type": "addresses",
"id": 2
}
]
}
}
}
}';
print($json);
Here I iniciate the cURL, I have the token and the authorization already:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,($url));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,($json));
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/vnd.api+json',
'Accept: application/json',
'Authorization: Bearer ' . $token,
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
var_dump ($response);
$response=json_decode($response,true);
curl_close ($ch);
This is the response that I have:
string(329) "{"errors":[{"status":"500 Internal Server Error","code":"JA006","detail":"Erro de sistema JA006: erro interno na base de dados. Por favor contacte o suporte técnico.","meta":{"internal-error":"in JsonapiJson::Value::operator[](ArrayIndex)const: requires arrayValue"}}],"jsonapi":{"version": "1.0","meta":{"libversion":"2.4.1"}}}"
Can someone please help me?
Thanks!
The API error states this: in JsonapiJson::Value::operator[](ArrayIndex)const: requires arrayValue.
Are you sure that JSON is the correct format? It seems like you are probably providing an object in the JSON where the server expects an array of objects. For example, check if data, or relationships, or addresses should be arrays.
My top guess would be instead of:
"addresses": {
"data": [
{
"type": "addresses",
"id": 1
},
{
"type": "addresses",
"id": 2
}
]
}
Maybe it's supposed to be
"addresses":[
{
"type": "addresses",
"id": 1
},
{
"type": "addresses",
"id": 2
}
]
I certainly can't tell you for sure, since I don't know the API you are trying to use, but I highly suspect it's a case like this where it's expecting an array, but you're providing an object.
My task is to authenticate on this api
https://api.getresponse.com/v3/accounts
Then need to save on the following api
https://api.getresponse.com/v3/POST/contacts
data must be in the following format
{
"name": "Hemant Maurya",
"email": "xyz#yahoo.com",
"dayOfCycle": "0",
"campaign": {
"campaignId": "6mzZL"
},
"tags": [
{
"tagId": "Xw"
},
{
"tagId": "Nn"
}
],
"scoring": 25,
"customFieldValues": [
{
"customFieldId": "n",
"value": [
"white"
]
}
],
"ipAddress": "14.143.38.111"
}
Following code can authenticate
$url = "https://api.getresponse.com/v3/accounts";
$headers = array();
$headers[] = "X-Auth-Token: api-key 17fbe43cc8a23daaf36b35093c77djet";//api key is fake at the moment
$state_ch = curl_init();
curl_setopt($state_ch, CURLOPT_URL, $url);
curl_setopt($state_ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($state_ch, CURLOPT_HTTPHEADER, $headers);
$state_result = curl_exec ($state_ch);
$state_result = json_decode($state_result);
$debug = 1;
print_r($state_result);
The response is as following
{
"accountId": "fjnfd",
"firstName": "first name",
"lastName": "last name",
"email": "xyz.com#gmail.com",
"phone": "+3798798",
"companyName": "",
"state": "state address",
"city": "city address",
"street": "street address",
"zipCode": "226010",
"countryCode": {
"countryCodeId": "100",
"countryCode": "IN"
},
"industryTag": {
"industryTagId": null
},
"numberOfEmployees": null,
"timeFormat": "12h",
"timeZone": {
"name": "Asia/Kolkata",
"offset": "+09:30"
},
"href": "https://api.getresponse.com/v3/accounts"
}
I am not getting how to save the data tried GetResponseAPI3.class.php from Github but it's not happening.
get response documentation
Links that can Help
Authentication
Saving contacts
You may vote it down but I have been trying for last 3 days and it's not happening.
The thing is that you don't need to send a request to https://api.getresponse.com/v3/accounts to authenticate your calls. The data that you receive means your authentication headers are probably correct, so can directly proceed to sending POST requests to https://api.getresponse.com/v3/contacts. Your payload looks fine so you should make it successfully.
I'm currently working on a website to control my SmartBulbs at home via a webpage. To do so I use the provided API.
I tried my code with an example json response from the manufacturers website. Everything worked fine and all the lights listed in the example response where represented by divs with the names of the lights.
When I tried my code at home (called the API like in the code) I got a valid response but I also got an error which stated Illegal string offset 'label'. What am I doing wrong?
Everything worked fine when I used the example response. The response when I use the API looks the same for me. Shouldn't it also work then?
You can find everything down below. If you need some mor information just ask :)
php code
function get_lights(){
$link = "https://api.lifx.com/v1/lights/all";
$authToken = "I inserted my token here and got a valid response";
$ch = curl_init($link);
$headers = array('Authorization: Bearer ' . $authToken);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, $headers);
$response = curl_exec($ch);
$json = json_decode($response, true);
$html = null;
foreach($json as $object)
{
$html.= '<div class="element" onclick="get_info();">' . $object['label'] . '</div>';
}
return $html;
}
example response
[
{
"id": "d3b2f2d97452",
"uuid": "8fa5f072-af97-44ed-ae54-e70fd7bd9d20",
"label": "Left Lamp",
"connected": true,
"power": "on",
"color": {
"hue": 250.0,
"saturation": 0.5,
"kelvin": 3500
},
"infrared": "1.0",
"brightness": 0.5,
"group": {
"id": "1c8de82b81f445e7cfaafae49b259c71",
"name": "Lounge"
},
"location": {
"id": "1d6fe8ef0fde4c6d77b0012dc736662c",
"name": "Home"
},
"last_seen": "2015-03-02T08:53:02.867+00:00",
"seconds_since_seen": 0.002869418,
"product": {
"name": "LIFX+ A19",
"company": "LIFX",
"identifier": "lifx_plus_a19",
"capabilities": {
"has_color": true,
"has_variable_color_temp": true,
"has_ir": true,
"has_multizone": false
}
}
}
]
my API response
[
{
"id":"d073d513bfd6",
"uuid":"02ea5835-9dc2-4323-84f3-3b825419008d",
"label":"MainLight",
"connected":true,
"power":"on",
"color":{
"hue":27.581597619592586,
"saturation":0.0,
"kelvin":2500
},
"zones":null,
"brightness":0.49999237048905165,
"group":{
"id":"d5aa0e1180293e0af56607cbe47f4940",
"name":"MyRoom"
},
"location":{
"id":"451e4b376a38062cdd10c54ab2698975",
"name":"My Home"
},
"product":{
"name":"Color 1000",
"identifier":"lifx_color_a19",
"company":"LIFX",
"capabilities":{
"has_color":true,
"has_variable_color_temp":true,
"has_ir":false,
"has_multizone":false
}
},
"infrared":null,
"last_seen":"2017-02-18T21:40:58.164+00:00",
"seconds_since_seen":0.001675218
}
]
You're setting the wrong option for your cURL handle:
$ch = curl_init($link);
$headers = array('Authorization: Bearer ' . $authToken);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
I am trying to create a paypal payment using php. I keep getting a 400 malformed request error. I believe my problem is with the following string:
$postData ='
{
"intent": "sale"
"redirect_urls": {
"return_url": ' . $url_success .',
"cancel_url": ' . $url_cancel .'
},
"payer": {
"payment_method": "paypal"
},
"transactions": [
{
"amount": {
"total": "' . $saleTotal .'",
"currency": "USD"
},
"description": "Test payment."
}
]
}
';
I am then sending the string using cURL in the following line
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
Here is my string printed out:
{ "intent": "sale" "redirect_urls": { "return_url":
"http://localhost/~user/test/controller/PayPalTestView.php", "cancel_url":
"http://localhost/~user/test/controller/CancelTestView.php" }, "payer": {
"payment_method": "paypal" }, "transactions": [ { "amount": { "total": "8.31782",
"currency": "USD" }, "description": "Test payment." } ] }
Here is the response I get:
{"name":"MALFORMED_REQUEST","message":"The request JSON is not well
formed.","information_link":
"https://developer.paypal.com/webapps/developer/docs/api/#MALFORMED_REQUEST",
"debug_id":"7d56ae815e584"}
I'm pretty sure the problem is in $postData, although I have no idea what's wrong. I tried following this example: Paypal REST API Bad Request, but it still isn't working. My problem is similar to that example in that I am sending and receiving the authentication token successfully. My problem is just when trying to send the payment API call. Does anyone see what I'm doing wrong? Thank you!
I got the same problem before. What I did is put the data first in array:
$data = array( "intent"=>"sale",
"redirect_urls"=>array(
"return_url"=>"<return site>",
"cancel_url"=>"<cancel site>"
),
"payer"=>array(
"payment_method"=>"paypal"
),
"transactions"=>array(
array(
"amount"=>array(
"total"=>"7.47",
"currency"=>"USD"
),
"description"=>"This is the payment transaction description."
)
)
);
and the http header:
$header = array(
"Content-Type:application/json",
"Authorization:Bearer <token here>"
);
then on the postfield, encode your data using json_encode:
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
I hope this will help.