在表单提交 PHP 上使用 CURL 发送 JSON Post 请求

Sending JSON Post Request using CURL on Form Submit PHP

我有这个功能,我可以注册一个令牌来进行交易,而无需输入凭据。

有些博客说 curl exec 执行 curl 的工作,但这个函数没有任何反应。我可以使用表单中的提交按钮以某种方式触发此 CURL 吗?还有,我怎么知道CURL的错误?

$curl = curl_init();

                curl_setopt_array($curl, array(
                  CURLOPT_URL => 'url here',
                  CURLOPT_RETURNTRANSFER => true,
                  CURLOPT_ENCODING => '',
                  CURLOPT_MAXREDIRS => 10,
                  CURLOPT_TIMEOUT => 0,
                  CURLOPT_FOLLOWLOCATION => true,
                  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                  CURLOPT_CUSTOMREQUEST => 'POST',
                  CURLOPT_POSTFIELDS =>'{
                    "clientIp": $_clientip,
                    "ipAddress": $_ipaddress,
                    "merchantId": $_mid,
                    "notificationUrl": $_noturl,
                    "requestId": $_requestid,
                    "responseUrl": $_resurl,
                    "signature": "1f4856d7868b1c352e015211e79df194d6fa1babc624084dd00027bf89538184d75f19991d008c1d99d2b5a28c2eea7f928e304611562eb838216e3664eac628",
                    "trxType": "createtoken",
                    "verify": "Y",
                     "address1": $_addr1,
                  "address2": $_addr2,
                  "city": $_city,
                  "country": $_country,
                  "email": $_email,
                  "fName": $_fname,
                  "lName": $_lname,
                  "mName": $_mname,
                  "mobile": $_mobile,
                  "phone": $_phone,
                  "state": $_state,
                  "postal": ""
                }',
                  CURLOPT_HTTPHEADER => array(
                    'Content-Type: application/json',
                    'Idempotency-Key: HMCENRO202001140009T',
                    'Authorization: Basic Og=='
                  ),
                ));

                $response = curl_exec($curl);

                curl_close($curl);
                echo $response;

你可以尝试将正文定义为结构化表示,然后将其转换为 JSON:

$recipient['dst']      = "+000000";
$message['recipients'] = array($recipient);
$message['text']       = "this is a test message";
$job['messages']       = array($message);

$json = json_encode($job);

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => 'url here',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'POST',
  CURLOPT_POSTFIELDS => $json,
  CURLOPT_HTTPHEADER => array(
    'Content-Type: application/json',
    'Idempotency-Key: HMCENRO202001140009T',
    'Authorization: Basic Og=='
  ),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;