How to POST JSON Data With PHP cURL?
You are POSTing the json incorrectly -- but even if it were correct, you would not be able to test using print_r($_POST)
(read why here). Instead, on your second page, you can nab the incoming request using file_get_contents("php://input")
, which will contain the POSTed json. To view the received data in a more readable format, try this:
echo '<pre>'.print_r(json_decode(file_get_contents("php://input")),1).'</pre>';
In your code, you are indicating Content-Type:application/json
, but you are not json-encoding all of the POST data -- only the value of the "customer" POST field. Instead, do something like this:
$ch = curl_init( $url );# Setup request to send json via POST.$payload = json_encode( array( "customer"=> $data ) );curl_setopt( $ch, CURLOPT_POSTFIELDS, $payload );curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));# Return response instead of printing.curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );# Send request.$result = curl_exec($ch);curl_close($ch);# Print response.echo "<pre>$result</pre>";
Sidenote: You might benefit from using a third-party library instead of interfacing with the Shopify API directly yourself.
$url = 'url_to_post';$data = array("first_name" => "First name","last_name" => "last name","email"=>"email@gmail.com","addresses" => array ("address1" => "some address" ,"city" => "city","country" => "CA", "first_name" => "Mother","last_name" => "Lastnameson","phone" => "555-1212", "province" => "ON", "zip" => "123 ABC" ) );$postdata = json_encode($data);$ch = curl_init($url); curl_setopt($ch, CURLOPT_POST, 1);curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));$result = curl_exec($ch);curl_close($ch);print_r ($result);
This code worked for me. You can try...
Replace
curl_setopt($ch, CURLOPT_POSTFIELDS, array("customer"=>$data_string));
with:
$data_string = json_encode(array("customer"=>$data));//Send blindly the json-encoded string.//The server, IMO, expects the body of the HTTP request to be in JSONcurl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
I dont get what you meant by "other page", I hope it is the page at: 'url_to_post'. If that page is written in PHP, the JSON you just posted above will be read in the below way:
$jsonStr = file_get_contents("php://input"); //read the HTTP body.$json = json_decode($jsonStr);