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);
Related
I'm trying validate url for comment form.
Then I thought ”Safe Browsing Lookup API” looked good.
However, the following code only returns an empty array in $result.
What can I do to improve this code?
code:
<?php
$api_key = 'xxx';
$url = 'https://safebrowsing.googleapis.com/v4/threatMatches:find?key=' . $api_key;
$data = [
"client"=>[
"clientId" => "yourcompanyname",
"clientVersion" => "1.5.2"
],
"threatInfo"=>[
"threatTypes" =>["MALWARE", "SOCIAL_ENGINEERING"],
"platformTypes" =>["WINDOWS"],
"threatEntryTypes"=>["URL"],
"threatEntries" =>[
["url"=>"http://goooogleadsence.biz/"],
["url"=>"http://www.urltocheck2.org/"],
["url"=>"http://activefile.ucoz.com/"]
]
]
];
$data_json = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
$result = curl_exec($ch);
var_dump($result); // -> string(3) "{}"
curl_close($ch);
I am trying to call the GitHubAPI but when I do curl_exec() the response is a simple string. I would like to get a JSON response. My code is as follows:
if(isset($_GET['code']))
{
global $CLIENTID, $CLIENTSECRET;
$CODE = $_GET['code'];
$postfields = array('client_id' => $CLIENTID, 'client_secret' => $CLIENTSECRET, 'code' => $CODE);
$json_fields = json_encode($postfields);
$ch = curl_init("https://github.com/login/oauth/access_token");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
//curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type"=>"x-www-form-urlencoded", "Accept"=>"application/json"));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
$gitResponse = curl_exec($ch);
curl_close ($ch);
if($gitResponse)
{
echo var_dump($gitResponse);
}
else
{
echo "Error";
}
}
else
{
echo '<a href="https://github.com/login/oauth/authorize?client_id='.$CLIENTID.'" title="Login with Github">
LOGIN
</a>';
}
I've tried with CURLOPT_HTTPHEADER but it didn't work so I commented it.
What I receive is good but it is a string instead of a JSON respone so I can't use the fields of the response.
Thank you!
Add this to your code:
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));
This will request the server to return a JSON string, then you can turn that to an array to use:
if($gitResponse)
{
$result = json_decode($gitResponse,true);
}
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 have implemented for creating stream target through php with the help of curl.
<?php
$service_url = 'http://localhost:8087/v2/servers/_defaultServer_/vhosts/_defaultVHost_/applications/liveSource';
$curl = curl_init($service_url);
$curl_post_data ='
{
"restURI": "http://localhost:8087/v2/servers/_defaultServer_/vhosts/_defaultVHost_/applications/testlive"
"stream_target": {
"name": “defaultTarget”,
"provider": "rtmp",
"username": "liveSource",
"password": "Welcomehere",
"stream_name": “customTarget”,
"primary_url": "http://localhost:8087/v2/servers/_defaultServer_/vhosts/_defaultVHost_/applications/liveSource",
} "https://api.cloud.wowza.com/api/v1/stream_targets"
}';
$headers = array(
'Content-Type: application/json; charset=utf-8',
'Accept: application/json; charset=utf-8'
);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
curl_setopt($curl, CURLOPT_VERBOSE, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$curl_response = curl_exec($curl);
curl_close($curl);
echo $curl_response;
?>
But it is showing error as success as false with code 401
{"message":"The request requires user authentication","success":false,"wowzaServer":"4.4.0","code":"401"}
If you are trying to create a stream target in Wowza Streaming engine, I would start with a simple example as follows:
<?php
// Modify values here
$entryName = "ppSource";
$appName = "live";
$streamName = "myStream";
$userName = "user";
$password = "pass";
$profile = "rtmp";
$server = "localhost";
// End modification
$url = "http://{$server}:8087/v2/servers/_defaultServer_/vhosts/_defaultVHost_/applications/{$appName}/pushpublish/mapentries/{$entryName}";
$json = "{
\"restURI\": \"http://{$server}:8087/v2/servers/_defaultServer_/vhosts/_defaultVHost_/applications/{$appName}/pushpublish/mapentries/{$entryName}\",
\"serverName\":\"_defaultServer_\",
\"sourceStreamName\": \"{$streamName}\",
\"entryName\": \"{$entryName}\",
\"profile\": \"{$profile}\",
\"host\": \"{$server}\",
\"application\":\"{$appName}\",
\"userName\":\"{$userName}\",
\"password\":\"{$password}\",
\"streamName\":\"{$streamName}\"
}'";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HEADER ,0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER ,1);
// curl_setopt($ch, CURLOPT_USERPWD, "user:pass");
// curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Accept:application/json; charset=utf-8',
'Content-type:application/json; charset=utf-8',
'Content-Length: '.strlen($json)));
$contents = curl_exec($ch);
curl_close($ch);
$obj = json_decode($contents);
var_dump($obj);
However if you are trying to initiate a live stream through our cloud api, here is a small example (only) of what your request might look like:
// Modify values here
$cloudApiKey = "xxxxxxxxxxx";
$cloudApiAccessKey="xxxxxxxxxx";
// End modification
$url = "https://api.cloud.wowza.com/api/v1/live_streams";
$json = "{
\"live_stream\": {
\"id\": \"1234abcd\",
\"name\": \"MyLiveStream\",
\"transcoder_type\": \"transcoded\",
\"billing_mode\": \"pay_as_you_go\",
\"broadcast_location\": \"us_west_california\",
\"recording\": false,
\"encoder\": \"wowza_gocoder\",
\"delivery_method\": \"push\",
\"use_stream_source\": false,
\"aspect_ratio_width\": 1280,
\"aspect_ratio_height\": 720,
\"connection_code\": \"033334\",
\"connection_code_expires_at\": \"2015-11-25T12:06:38.453-08:00\",
\"source_connection_information\": {
\"primary_server\": \"6022e9.entrypoint.cloud.wowza.com\",
\"host_port\": 1935,
\"application\": \"app-464b\",
\"stream_name\": \"32a5814b\",
\"disable_authentication\": false,
\"username\": \"client2\",
\"password\": \"1234abcd\"
},
\"player_responsive\": true,
\"player_countdown\": false,
\"player_embed_code\": \"in_progress\",
\"player_hds_playback_url\": \"http://wowzadev-f.akamaihd.net/z/32a5814b_1#7217/manifest.f4m\",
\"player_hls_playback_url\": \"http://wowzadev-f.akamaihd.net/i/32a5814b_1#7217/master.m3u8\",
\"hosted_page\": true,
\"hosted_page_title\": \"MyLiveStream\",
\"hosted_page_url\": \"in_progress\",
\"hosted_page_sharing_icons\": true
}
}";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HEADER ,0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER ,1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Accept:application/json; charset=utf-8',
'Content-type:application/json; charset=utf-8',
'wsc-api-key: '.$cloudApiKey,
'wsc-access-key: '.$cloudApiAccessKey,
);
$contents = curl_exec($ch);
curl_close($ch);
This is obtained from the examples page and modified to fit into a PHP related request.
Thanks,
Matt
I'm trying to POST using php. In the API it's suggested the following format.
// post url, keys are added here.
{
"EmailAddress": "john.smith#acmeconsulting.co",
"ActivityEvent": 112,
"ActivityNote": "Note for the activity",
"ActivityDateTime": "yyyy-mm-dd hh:mm:ss",
"FirstName": "John",
"LastName" : "Smith",
"Phone" : "+919845098450",
"Score": 10
}
My code in PHP :
$firstName='Test5';
$activityEvent=201;
$emailAddress='test10#test.com';
$activityNote='Note note note';
$phone='999999999';
$date='2015-07-21 12:48:10';
$data_string['ActivityEvent']=$activityEvent;
$data_string['EmailAddress']=$emailAddress;
$data_string['ActivityNote']=$activityNote;
$data_string['Phone']=$phone;
$data_string['ActivityDateTime']=$date;
//json_encode($data_string);
try
{
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type:application/json',
'Content-Length:'.strlen($data_string)
));
$json_response = curl_exec($curl);
curl_close($curl);
} catch (Exception $ex) {
curl_close($curl);
}
This code is not working as expected. I'm not getting any update there. Is the code correct?
Have you tried this?
$object = new StdClass;
$object->ActivityEvent = 201;
$object->EmailAddress = 'john.smith#acmeconsulting.co';
//add more properties here
echo json_encode($object);
$datastring = array(
'firstName' => 'John',
'lastName' => 'Smith',
...........);
$ch = curl_init("YOUR_URL_HERE");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $datastring );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
the result will be stored in the $result variable