Request Payload как принять
В примере нужна реализация api для формы, отправляемой с помощью Angular JS. Данные отправляются в Request Payload (название из консоли Google Chrome) при этом массив $_POST — пуст.
Чтобы получить эти данные
В виде json:
echo file_get_contents('php://input');
В результате получим:
{"jsonrpc":"2.0","method":"Widget.ContactForm.sendMessage","id":"0","params":{"message":{"name":"Krylov","email":"[email protected]","address":"+78120000000","message":"test"},"placeholder":{"name":"Name *","email":"E-mail *","address":"Cell ","message":"Comment *"},"hash":"1@KfwalNFOU1rJqW8s4ffYsHg/zlhRhCTLd0XubaAkcVIxhpL227jVj+ZAWVdgge1+eCLe7c1ww+VOT4b26gDXlUvAl39DeMXMzCbqxgK9/e0O1VIIpXX8YYdD0za2rC0nsBHkw0/Ing7u+pYK5KoIpqk4L47Q7DtNRVbLglD6Fm0="}}
В виде массива:
print_r(json_decode(trim(file_get_contents('php://input')),true));
В результате получим:
Array ( [jsonrpc] => 2.0 [method] => Widget.ContactForm.sendMessage [id] => 0 [params] => Array ( [message] => Array ( [name] => Krylov [email] => krylov@krylov.org.ua [address] => +78120000000 [message] => test ) [placeholder] => Array ( [name] => Name * [email] => E-mail * [address] => Cell [message] => Comment * ) [hash] => 1@KfwalNFOU1rJqW8s4ffYsHg/zlhRhCTLd0XubaAkcVIxhpL227jVj+ZAWVdgge1+eCLe7c1ww+VOT4b26gDXlUvAl39DeMXMzCbqxgK9/e0O1VIIpXX8YYdD0za2rC0nsBHkw0/Ing7u+pYK5KoIpqk4L47Q7DtNRVbLglD6Fm0= ) )
Пример простейшей обработки:
header('Content-Type: application/json'); $data=json_decode(trim(file_get_contents('php://input')),true); if(count($data['params']['placeholder'])>0){ $message=''; foreach($data['params']['placeholder'] as $k=>$v){ $message.='<b>'.$v.':</b> '.$data['params']['message'][$k].'<br/>'; } $from='=?utf-8?B?'.base64_encode('Site Name').'?='; $subject='=?utf-8?B?'.base64_encode('Contact Form').'?='; $headers="Content-Type: text/html; charset=utf-8\r\n"; $headers.="From: \"".$from."\"<noreply@".$_SERVER['HTTP_HOST'].">\r\n"; if(mail('[email protected]',$subject,$message,$headers)){ exit('{"result":true,"id":"'.$data['id'].'","jsonrpc":"2.0"}'); } } exit('{"error":{"code":-32600,"message":"Invalid Request","data":null},"id":null}');