不能使用fopen进行post请求


Cannot do a post request using fopen

我试图做一个post request使用fopen,但我不能改变请求的头,不能完成它。我需要帮助,请看到我的代码:

$data_array = array(
   'MerchantOrderId'=>'2014111703',
   'Customer'=>array(  
      'Name'=>'Comprador Teste'     
   ),
   'Payment'=>array(  
     'Type'=>'CreditCard',
     'Amount'=> '100',
     'Provider'=>'Simulado',
     'Installments'=>1,
     'CreditCard'=>array(  
         'CardNumber'=>'4461561220666711',
         'Holder'=>'Pablo Pablo',
         'ExpirationDate'=>'01/2019',
         'SecurityCode'=>'101',
         'Brand'=>'Master'
     )
   )
);
$data = json_encode($data_array);
$header = 'Content-Type : application/json'r'n'.
          'Content-Length :'. strlen($data).''r'n'.
          'MerchantId : 3a361c55-2feb-4c8d-a0e9-1cf24fb31242'r'n'.
          'MerchantKey : VXXIKMBOZHBZACKKJHHTYLECTACKIYQXAXYHOJNI'r'n'.
          'RequestId : 4e361c55-2feb-4c8d-a0e9-1cf24fb31244';
$context_opt = array(
    'https' => array (
        'method'  => "POST",
    'header'  => $header,
    'content' => $data
    )
);
$url = 'https://apisandbox.braspag.com.br/v2/sales';
$fp = fopen(
  $url, 
  'r', 
  false, 
  stream_context_create($context_opt)
);
if (!$fp)
{
    throw new Exception('Problem with $url, $php_errormsg');
}
$result = stream_get_contents($fp);
fclose($fp);
print_r($result);

我使用rest控制台chrome扩展测试了这个配置,工作得很好我哪里做错了?

在您的上下文选项数组中,您需要使用关键字http,而不是https。HTTPS不是它自己的包装器,它是HTTP包装器+ SSL包装器的组合。

$context_opt = array(
    'http' => array (
        'method'  => "POST",
        'header'  => $header,
        'content' => $data
    )
);

除此之外,您还需要修复头文件的定义。首先,您需要使用双引号字符串,以便'r'n转义创建新行。使用单引号,您将获得分隔头的文字''r'n'。其次,您需要删除标题名称和冒号之间的空格,标题名称中不允许有空格。

$header = "Content-Type: application/json'r'n".
          "Content-Length: ". strlen($data)."'r'n".
          "MerchantId: 3a361c55-2feb-4c8d-a0e9-1cf24fb31242'r'n".
          "MerchantKey: VXXIKMBOZHBZACKKJHHTYLECTACKIYQXAXYHOJNI'r'n".
          "RequestId: 4e361c55-2feb-4c8d-a0e9-1cf24fb31244";