I am using HackerRank as a test evaluation on my website. I am using it's API to send invite to my users for the test. I am calling it's API using CURL in PHP but i get error "invalid access token".
I use this code.
function httpPost($url,$params)
{
$postData = '';
//create name value pairs seperated by &
foreach($params as $k => $v)
{
$postData .= $k . '='.$v.'&';
}
$postData = rtrim($postData, '&');
$arr = array();
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Content-Type" => "application/x-www-form-urlencoded",
"Accept" => "application/json"
));
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch,CURLOPT_FOLLOWLOCATION,TRUE);
curl_setopt($ch,CURLOPT_MAXREDIRS,2);//only 2 redirects
curl_setopt($ch, CURLOPT_POST, count($postData));
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
$output=curl_exec($ch);
if($output === false)
{
$arr[]= "Error Number:".curl_errno($ch)."<br>";
$arr[]= "Error String:".curl_error($ch);
}
curl_close($ch);
$arr[]= $output;
return $arr;
}
$data = array(
'test_id'=> test_id_integer,
'username'=> "EMAIL_ID",
'access_token'=> 'API_KEY'
);
var_dump(httpPost("www.hackerrank.com/x/api/v2/tests/test_id_integer/candidates",$data));
Related
I'm trying to validate api data with POST request using cURL but getting no response.
API documentation
<?php
$url = "https://widget.packeta.com/v6/api/pps/api/widget/validate";
$data = array(
"Parameters" => array(
"apiKey" => "XXXXXX",
"id" => "9346",
)
);
$encoded = json_encode($data);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $encoded);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$resp = curl_exec($ch);
$decoded = json_decode($resp);
print_r($decoded);
curl_close($ch);
?>
Does anyone know what is wrong?
SOLUTION:
Turns out i was missing CURL_HTTPHEADER.
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Content-Type: application/json",
"Accept: application/json"
));
Try to write:
$ch = curl_init();
instead of :
$ch = curl_init($url);
Eventualy you can use a try ... catch to get the error:
<?php
// Define variables
define('API_KEY', 'XXXXXX');
$url = "https://widget.packeta.com/v6/api/pps/api/widget/validate";
$id = "9346";
// Prepare data
$data = array(
"Parameters" => array(
"apiKey" => API_KEY,
"id" => $id,
)
);
$encoded = json_encode($data);
try {
// Initialize cURL
$ch = curl_init();
// Set cURL options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $encoded);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Execute cURL request
$resp = curl_exec($ch);
if($resp === false) {
throw new Exception(curl_error($ch));
}
// Decode response and print it
$decoded = json_decode($resp);
print_r($decoded);
// Close cURL session
curl_close($ch);
} catch (Exception $e) {
echo 'Error: ' . $e->getMessage();
}
?>
I want to send charging request through php which I have sent via postman and it worked, but when I try this with php I m getting error response.
I have tried to send the request using curl and used function to send the request. But, after hitting the php I m getting the response that "invalid request" .
Here is the code snippet:
<?php
define('TML_CHARGE_URL2', 'http://sandbox-apigw.mytelenor.com.mm/v1/mm/en/customers/products/vas');
$client_id="MDq0MdGtZUGZWfanE8k2fva7GsLvwS0I";
$client_secret="GEzAxTE6YYSfLEAD";
$accessToken="ytSxhvjSUfNEurD5M6SOJPm6XAfu";
/* CP & Product Codes */
$cpid="15";
$login="apigwtest";
$password="apigwtestpwd";
$client_id="175612092873562378";
$msisdn="9791000601";
$prod_code = "APIGW_TEST";
$requestParamList = array("cpID" => $cpid,
"clientTransactionId" => $client_id,
"loginName" => $login,
"password" => $password,
"id" => array (
"type" => "MSISDN",
"value" => $msisdn
),
"productCode" => $prod_code
);
function callAPI($apiURL, $requestParamList) {
$jsonResponse = "";
$responseParamList = array();
$JsonData =json_encode($requestParamList);
$postData = 'JsonData='.urlencode($JsonData);
$ch = curl_init($apiURL);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
echo $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); //get status code
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($postData),
'Authorization: Bearer ytSxhvjSUfNEurD5M6SOJPm6XAfu'
)
);
echo $jsonResponse = curl_exec($ch);
$responseParamList = json_decode($jsonResponse,true);
return $responseParamList;
}
function oneshotpayment($requestParamList) {
return callAPI(TML_CHARGE_URL, $requestParamList);
}
function subscription_payment($requestParamList) {
return callAPI(TML_CHARGE_URL2, $requestParamList);
}
echo subscription_payment($requestParamList);
?>
The error response is like below:
{
"transactionId": "",
"timestamp": "2017-08-13T17:28:24+06:30",
"recipientMsisdn": "",
"code": "500.023.003",
"error": "Internal Server Error",
"message": "Request input is malformed or invalid"
}
You need to change your callAPI method.
1) You dont need to do urlencode after you have done json_encode
2) Remove unnecessory concatination of 'JsonData='. in string.
change you method like below
function callAPI($apiURL, $requestParamList) {
$postData = "";
$responseParamList = array();
$postData =json_encode($requestParamList);
$ch = curl_init($apiURL);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
echo $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); //get status code
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($postData),
'Authorization: Bearer ytSxhvjSUfNEurD5M6SOJPm6XAfu'
)
);
echo $jsonResponse = curl_exec($ch);
$responseParamList = json_decode($jsonResponse,true);
return $responseParamList;
}
I am facing MALFORMED_REQUEST in paypal API
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://api.sandbox.paypal.com/v1/payments/payment");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{
\"intent\":\"authorize\",
\"payer\":{
\"payment_method\":\"credit_card\",
\"funding_instruments\":[{
\"credit_card\":{
\"number\":\"5555555555554444\",
\"type\":\"mastercard\",
\"expire_month\":07,
\"expire_year\":22,
\"cvv2\":123,
\"first_name\":\"FName\",
\"last_name\":\"Lname\",
\"billing_address\":{
\"line1\":\"address,\",
\"city\":\"City\",
\"state\":\"state\",
\"postal_code\":\"postal_code\",
\"country_code\":\"country_code\"
}
}
}]
},
\"transactions\":[{
\"amount\":{
\"total\":\"10\",
\"currency\":\"CAD\",
\"details\":{
\"subtotal\":\"10\",
\"tax\":\"0\",
\"shipping\":\"0\"
}
}
}]}");
curl_setopt($ch, CURLOPT_POST, 1);
$headers = array();
$headers[] = "Content-Type: application/json";
$headers[] = "Authorization: Bearer myAccessToken";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
Here I am calling curl for authorization with paypal
jsonlint.com shows this json format is ok
But still I am getting response like,
{"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":"9d7454a8637ae"}
Not getting exactly where I am wrong? Does any one know? Thanks in advance!
Your problem is the 07 in "expire_month": 07. I assume this value is meant to be a string. Not sure what you pasted in to jsonlint but it wasn't the JSON in your question.
As indicated in the comments, don't roll your own JSON. Use the tools available
$data = [
'intent' => 'authorize',
'payer' => [
'payment_method' => 'credit_card',
'funding_instruments' => [[
'credit_card' => [
'number' => '5555555555554444',
'type' => 'mastercard',
'expire_month' => '07',
'expire_year' => '22',
'hopefully you get the idea' => 'by now'
]
]]
]
];
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
As the error indicates, your JSON is not formed correctly.You need not pass \ to escape your request parameters . Try removing those or try this sample code which works out of the box.
<?php
$data = 'response_type=token&grant_type=client_credentials';
$headers_arr = array();
$headers_arr[]="Accept-Encoding:application/json;charset=utf-8";
$headers_arr[]="Accept-Language:en_US";
// $headers_arr[]="Authorization:Bearer AZHFuBBAIG1rP98P7Svn2WOVatM5KAllu6KvrTE8GGT4gt9vdfj8TtR_1Cer:EBTMERCurtbf_4auykCeGWYGvwsy147bSb3xCuYpohmouVBGTaYFUIRwWgbx";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.sandbox.paypal.com/v1/oauth2/token");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);// this is used to bypass the SSL protocol, not recommended.
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);// this is used to bypass the SSL protocol, not recommended.
curl_setopt($ch, CURLOPT_TIMEOUT, 45);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, "ARLg-BBMeTGLU5IHCsdIKEC_R_sMAkWM-yLsI5W5u9RuhvNhgolhYv-1cWmr:EJdAYxDx29McgMKOWjGK1OLHyaIxQBRuV9sWgfFSeMKGVBe-1jdiNgv5TLtP");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers_arr);
$result = curl_exec($ch);
$res = json_decode($result);
$access_token = $res->access_token;
//now create a paypal payment
$headers_arr = array();
$headers_arr[]="Content-Type:application/json;charset=utf-8";
$headers_arr[] = "Authorization: Bearer $access_token";
// echo '<pre>';
// print_r($headers_arr);
$data_string = '{
"intent":"authorize",
"payer":{
"payment_method":"credit_card",
"funding_instruments":[
{
"credit_card":{
"number":"4446283285273500",
"type":"visa",
"expire_month":11,
"expire_year":2018,
"cvv2":"874",
"first_name":"Betsy",
"last_name":"Buyer",
"billing_address":{
"line1":"111 First Street",
"city":"Saratoga",
"state":"CA",
"postal_code":"95070",
"country_code":"US"
}
}
}
]
},
"transactions":[
{
"amount":{
"total":"7.47",
"currency":"USD",
"details":{
"subtotal":"7.41",
"tax":"0.03",
"shipping":"0.03"
}
},
"description":"This is the payment transaction description."
}
]
}';
// echo data_string;
$chs = curl_init();
curl_setopt($chs, CURLOPT_URL, 'https://api.sandbox.paypal.com/v1/payments/payment');
curl_setopt($chs, CURLOPT_POST, true);
curl_setopt($chs, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($chs, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($chs, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($chs, CURLOPT_TIMEOUT, 45);
curl_setopt($chs, CURLOPT_RETURNTRANSFER, true);
curl_setopt($chs, CURLOPT_POST, 1);
curl_setopt($chs, CURLOPT_HTTPHEADER, $headers_arr);
if(curl_exec($chs) === false)
{
echo 'Curl error: ' . curl_error($chs);
}
$results = curl_exec($chs);
$res = json_decode($results);
echo 'ress=<pre>';
print_r($results);
I have the following php Curl code, to submit a form and get the tables of result
<?php
function httpPost($url,$params)
{
//echo 1;
$postData = '';
//create name value pairs seperated by &
foreach($params as $k => $v)
{
$postData .= $k . '='.$v.'&';
}
rtrim($postData, '&');
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POST, count($postData));
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$output=curl_exec($ch);
curl_close($ch);
//return $params;
return $output;
}
$params = array(
"form_hf_0"=>null,
"searchMode:edit"=>"Births",
"searchSwitch:birthContainer:regNumber:regNumber"=>null,
"searchSwitch:birthContainer:regNumber:regYear"=>null,
"searchSwitch:birthContainer:subjectName:familyName:edit"=>"smith",
"searchSwitch:birthContainer:subjectName:givenName:edit"=>null,
"searchSwitch:birthContainer:subjectName:otherNames:edit"=>null,
"searchSwitch:birthContainer:fatherGivenName:edit"=>null,
"searchSwitch:birthContainer:fatherOtherNames:edit"=>null,
"searchSwitch:birthContainer:motherGivenName:edit"=>null,
"searchSwitch:birthContainer:motherOtherNames:edit"=>null,
"searchSwitch:birthContainer:dateOfEvent:range:edit"=>true,
"searchSwitch:birthContainer:dateOfEvent:switchGroup:range:dateFrom:day"=>01,
"searchSwitch:birthContainer:dateOfEvent:switchGroup:range:dateFrom:month"=>01,
"searchSwitch:birthContainer:dateOfEvent:switchGroup:range:dateFrom:year"=>1788,
"searchSwitch:birthContainer:dateOfEvent:switchGroup:range:dateTo:day"=>31,
"searchSwitch:birthContainer:dateOfEvent:switchGroup:range:dateTo:month"=>12,
"searchSwitch:birthContainer:dateOfEvent:switchGroup:range:dateTo:year"=>1913,
"searchSwitch:birthContainer:district:edit"=>null,
"search-button"=>"Search"
);
$param1 = array("username"=>"sa","password"=>"1");
echo httpPost("https://lifelink.bdm.nsw.gov.au/lifelink/familyhistory/search?0-2.IFormSubmitListener-mainContent-form",$params);
?>
The form link is here:https://lifelink.bdm.nsw.gov.au/lifelink/familyhistory/search?0
I have nothing printed.
Can anyone pointed where is wrong?
The result is here http://ec2-54-213-181-25.us-west-2.compute.amazonaws.com/htdocs/lib/CURL/curl.php
Nothing in the table as normal search with family name "smith", range date 1788 to 1914.
Is the correct way to send $json data via CURL? in PHP,
I have my $json data in one php, I can send the data information via POST using CURL to my api,??
Do you have some examples, thanks a lot!!
Yes. You can do.
Eg.
// $json_string : Your json String
$ch = curl_init('http://api.example.com/post');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($json_string))
);
$result = curl_exec($ch);
Please find before post:
http://bavotasan.com/2011/post-url-using-curl-php/
In some key on $data, put your $json.
Example
function post_to_url($url, $data) {
$fields = '';
foreach($data as $key => $value) {
$fields .= $key . '=' . $value . '&';
}
rtrim($fields, '&');
$post = curl_init();
curl_setopt($post, CURLOPT_URL, $url);
curl_setopt($post, CURLOPT_POST, count($data));
curl_setopt($post, CURLOPT_POSTFIELDS, $fields);
curl_setopt($post, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($post);
curl_close($post);
}
$json = json_encode($your_json); //Your json data
$data = array(
"name" => "c.bavota",
"website" => "http://bavotasan.com",
"twitterID" => "bavotasan",
"json" => $json
);
post_to_url("http://yoursite.com/post-to-page.php", $data);