SendSms.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. include_once("../../../untils/conn.php"); // 引入数据库连接配置文件
  3. // 获取用户输入的手机号和IP地址
  4. $phoneNumber = $_POST["phoneNumber"];
  5. $ipAddress = $_SERVER['REMOTE_ADDR'];
  6. $sutime = time();
  7. $id = '1';
  8. $sql = "SELECT * FROM sms WHERE id =" . $id;
  9. $result = mysqli_query($con, $sql);
  10. if ($result->num_rows > 0) {
  11. // 输出数据
  12. while ($row = $result->fetch_assoc()) {
  13. // 获取每个字段的值
  14. $appId = $row["appid"];
  15. $appKey = $row["appkey"];
  16. $templateId = $row["te_ids"];
  17. $smsSign = $row["sign"];
  18. }
  19. // 生成6位随机数字作为验证码
  20. $verificationCode = mt_rand(100000, 999999);
  21. // 将验证码和IP地址存储起来
  22. $sql = "INSERT INTO vercodes (phone, code, ip , sutime) VALUES ('$phoneNumber', '$verificationCode', '$ipAddress' , '$sutime')";
  23. mysqli_query($con, $sql);
  24. // 发送短信验证码
  25. $params = array(
  26. '{1}' => $verificationCode,
  27. );
  28. $currentTimeStamp = time();
  29. $random = rand(1000000, 9999999);
  30. $requestParms = array(
  31. 'tel' => array(
  32. 'nationcode' => '86',
  33. 'mobile' => $phoneNumber,
  34. ),
  35. 'sig' => hash("sha256", "appkey=$appKey&random=$random&time=$currentTimeStamp&mobile=$phoneNumber", false),
  36. 'tpl_id' => $templateId,
  37. 'params' => array_values($params),
  38. 'sign' => $smsSign,
  39. 'time' => $currentTimeStamp,
  40. 'extend' => '',
  41. 'ext' => ''
  42. );
  43. $requestJson = json_encode($requestParms);
  44. $url = "https://yun.tim.qq.com/v5/tlssmssvr/sendsms?sdkappid=$appId&random=$random";
  45. $ch = curl_init();
  46. curl_setopt($ch, CURLOPT_URL, $url);
  47. curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8'));
  48. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  49. curl_setopt($ch, CURLOPT_POST, 1);
  50. curl_setopt($ch, CURLOPT_POSTFIELDS, $requestJson);
  51. $response = curl_exec($ch);
  52. curl_close($ch);
  53. $responseData = json_decode($response, true);
  54. if ($responseData["result"] == 0) {
  55. // 发送成功
  56. $jsonResponse = array("code" => 200, "msg" => "验证码发送成功");
  57. } else {
  58. // 发送失败
  59. $jsonResponse = array("code" => 400, "msg" => "验证码发送失败");
  60. // $jsonResponse = array("code" => 400, "msg" => "验证码发送失败!失败原因:" . $responseData["errmsg"]);
  61. }
  62. } else {
  63. // 未找到匹配的记录
  64. $jsonResponse = array("code" => 400, "msg" => "未找到匹配的记录");
  65. }
  66. // 返回JSON响应
  67. echo json_encode($jsonResponse);
  68. ?>