PHP CURL POST method is giving 500 response code - php

Hi I know that there are similar questions already in there but I have ruled them out.
So I am trying to make a simple POST method with curl and keep getting error 500. Have I missed something ?
// Get cURL resource
$curl = curl_init();
//POST request body
$post_data = array(
'subscription_uuid' => $subscription_uuid,
'merchant' => $merchant_id
);
echo "JSON in POSTFIELDS:" . json_encode($post_data, JSON_PRETTY_PRINT) . "\n";
// Set Headers, endpoint and option to output response as string
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://subscriptions-jwt.fortumo.io/subscriptions/cancel',
CURLOPT_POST => 1,
CURLOPT_HTTPHEADER => array(
'Content Type: application/json' ,
'Authorization: Bearer' . " " . $jwt
),
CURLOPT_POSTFIELDS => json_encode($post_data)
));
// Send the request & save response
$unsubscribe_response = curl_exec($curl);
$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
//Request URL:
echo "Unsubscribe Request URL:\n" . curl_getinfo($curl, CURLINFO_EFFECTIVE_URL) . "\n";
echo "Error Code:" . $statusCode . "\n";
And here is the response I get from that code block(simplified this using echo-s):
JSON in POSTFIELDS:{
"subscription_uuid": "<<MY-TOKEN>>",
"merchant": "<<MY-TOKEN>>"
}
Unsubscribe Request URL:
https://subscriptions-jwt.fortumo.io/subscriptions/cancel
Error Code:500
Wierd thing is that using exactly same set of headers, JSON postfields and URL in a tool such as Advanced REST client everything works fine and I get 200 response with no problem.
Something is wrong with my code. Can anyone please spot the issue? Thanks in advance!

Related

Working with webhook using paystack payment gateway

I have created an online store with Paystack gateway implemented.
Up till now it's been successful, but I need a little help with creating a webhook event script, such that if user never redirects to the callback URL to be given value, I can get notified to give user value.
The functionality of my script should throw more light on this..
INITIALIZE.PHP SCRIPT
<?php
session_start();
if(isset($_POST["pay"])){
$curl = curl_init();
$email = $_SESSION["order_details"]["email"];
$amount = $_SESSION["order_details"]["total"]; //the amount in kobo. This value is actually NGN 300
// url to go to after payment
$callback_url = 'http://localhost:8080/phpmyadmin/online_store/order.php';
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.paystack.co/transaction/initialize",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode([
'amount'=>$amount,
'email'=>$email,
'callback_url' => $callback_url
]),
CURLOPT_HTTPHEADER => [
"authorization: Bearer sk_test_2563a843c7ddd24e92450fe2ce91f3f18a57ad27", //replace this with your own test key
"content-type: application/json",
"cache-control: no-cache"
],
));
$response = curl_exec($curl);
$err = curl_error($curl);
if($err){
// there was an error contacting the Paystack API
die('Curl returned error: ' . $err);
}
$tranx = json_decode($response, true);
if(!$tranx['status']){
// there was an error from the API
print_r('API returned error: ' . $tranx['message']);
}
// comment out this line if you want to redirect the user to the payment page print_r($tranx);
// redirect to page so User can pay
// uncomment this line to allow the user redirect to the payment page
header('Location: ' .
$tranx['data']['authorization_url']);
}
?>
CALLBACK SCRIPT
$curl = curl_init();
$reference = isset($_GET['reference']) ? $_GET['reference'] : '';
if(!$reference){
die('No reference supplied');
}
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.paystack.co/transaction/verify/" . rawurlencode($reference),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
"accept: application/json",
"authorization: Bearer sk_test_2563a843c7ddd24e92450fe2ce91f3f18a57ad27",
"cache-control: no-cache"
],
));
$response = curl_exec($curl);
$err = curl_error($curl);
if($err){
// there was an error contacting the Paystack API
die('Curl returned error: ' . $err);
}
$tranx = json_decode($response);
if(!$tranx->status){
// there was an error from the API
die('API returned error: ' . $tranx->message);
}
if('success' == $tranx->data->status){
// Rest part of the code that gives value to user, adds ordered items and payment info to database, sends email and delete the cart items or unset session (depending if a client or guest)
}
My script allows the user to make payments first by processing the payment through the initialize.php file before inserting Information into the Database through the call back script(order.php)
The problem is something can occur after successful payment and user might not be directed to the callback script to be given value to, so how do I use a webhook to give value to user if he/she wasn't directed to the callback script ?
Thanks in Advance
Go through this documentation. It has all your answer related to webhooks.
You can specify your webhook URL (SITEURL/path/to/webhook.php) on your dashboard where paystack would send POST requests to whenever an event occurs.
All you have to do to receive the event is to create an unauthenticated POST route on your application (SITEURL/path/to/webhook.php). The event object is sent as JSON in the request body.
You can use this type of code in webhook.php to receive webhook response
<?php
// Retrieve the request's body and parse it as JSON
$input = #file_get_contents("php://input");
$event = json_decode($input);
// Do something with $event
http_response_code(200); // PHP 5.4 or greater
?>
Between the web hook event and call back event, which one occurs first? If the callback happens first, then with the web hook, a check can be made in the database to know if transact exist.

Problem getting post data in API via php curl call

I am trying to send a file to a slim API via curl PHP.
Actually I have a PHP file that receive a from post data and is suppose to call a slim API with the received data and slim API is going to store the data in the database. It works fine when there is no file in the data but when I send a file to API along with other data using PHP curl and set the 'content-type: multipart/form-data' I miss all the posted data in API side. I couldn't figure out what's wrong with it!!!
By the way it works well when I test the API with postman. The API successfully gets the file and save it in the storage. The problem must be in the client side where I call the API using curl and PHP.
Could anybody please help me how to setup the curl call to to make the API work ?
Thanks a lot
route.php
$app->post('/softwareskills/insert', SoftwareSkillsController::class . ':insert')->setName('SoftwareSkills.insert');
SoftwareSkillsController.php
class SoftwareSkillsController {
public function insert(Request $request, Response $response, array $args)
{
$params= $request->getParsedBody();
$file = $request->getUploadedFiles();
var_dump($params); // return empty array!
var_dump($file); // return empty array!
}
}
upload.php
<?php
// $_POST and $_FILES to send them via php CURL
$tmpfile = $_FILES['attachment']['tmp_name'];
$filename = basename($_FILES['attachment']['name']);
$filemime = $_FILES['attachment']['type'];
$data = array(
"StNo" => $_POST['StNo'],
"SoftwareName" => $_POST['SoftwareName'],
"proficiency" => $_POST['proficiency'],
"attachment" => new CURLFile($tmpfile,$filemime,$filename)
);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "http://myapi.com/softwareskills/insert",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => http_build_query($data),
CURLOPT_HTTPHEADER => array(
"content-type: multipart/form-data"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}

Using curl to post request handle JSON data

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"];
}

Coinbase - php curl sendmoney - invalid signature error

I am trying coinbase api to send and get money and going to use in game,on running below code for sending money getting invalid signature error, not sure where I am wrong. I tried getting account detail, which is working fine and I am able to get account details.
<?php
$API_VERSION = '2016-02-01';
$curl = curl_init();
$timestamp = json_decode(file_get_contents("https://api.coinbase.com/v2/time"), true)["data"]["epoch"];
$req = "/v2/accounts/:account_id/transactions";
$url = "https://api.coinbase.com".$req;
$cle = "xxxxxxx";
$secret = "xxxxxxxx";
$params=['type'=>'send', 'to'=>'xxxxxxxxxx', 'amount'=>0.0001, 'currency'=>'BTC'];
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url,
CURLOPT_POST => true,
CURLOPT_USERAGENT, 'local server',
CURLOPT_POSTFIELDS => json_encode($params),
CURLOPT_HTTPHEADER => array(
"CB-VERSION:" . $API_VERSION,
"CB-ACCESS-SIGN:" . hash_hmac('sha256', $timestamp."GET".$req, $secret),
"CB-ACCESS-KEY:" . $cle,
"CB-ACCESS-TIMESTAMP:" . $timestamp,
'Content-Type: application/json'
),
CURLOPT_SSL_VERIFYPEER => false
));
$rep = curl_exec($curl);
curl_close($curl);
print_r($rep);
?>
In the $req URL, you need to replace :account_id with an actual account ID such as 3c04e35e-8e5a-5ff1-9155-00675db4ac02.
Most importantly, since this is a post request, the OAuth signature needs to include the payload (POST data) in the signature.
hash_hmac('sha256', $timestamp."POST".$req.json_encode($params), $secret),
When I encountered this error, it ended up being the account id, which is different for each of your currency accounts. Spent way too much time trying to figure out what was wrong with my signature... Anyways, I'd definitely try that out as GETs worked for me, but every other request type ended up with the invalid signature error.

Curl Get Request Removes spaces

Server data as viewed through a browser:
Ab91231 B923244 C9ds23911 D300231
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'http://www.test.com/stuff',
CURLOPT_USERAGENT => ''
));
$resp = curl_exec($curl);
// Send the request & save response to $resp
if(!curl_exec($curl)){
die('Error: "' . curl_error($curl) . '" - Code: ' . curl_errno($curl));
}
// Close request to clear up some resources
curl_close($curl);
print_r($resp);
printing the curl response I get :
Ab91231B923244C9ds23911D300231
any idea why this is happening?
This is because of one or both of these reasons:
The server-side code detects if a browser or curl ask for the resource and sends back the data differently depending on who asks.
The browser-side has something that changes the formatting of what you see, like javascript.

Categories