onlogin.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. namespace onlogin;
  3. class Onlogin
  4. {
  5. private $secretid;
  6. private $secretkey;
  7. private $businessid;
  8. private $api_url = "https://ye.dun.163yun.com/v1/oneclick/check";
  9. private $version = "v1";
  10. private $api_timeout = 5;
  11. private $internal_string_charset = "auto";
  12. /**
  13. * 构造函数
  14. * @param $sessionKey string 用户在小程序登录后获取的会话密钥
  15. * @param $appid string 小程序的appid
  16. */
  17. public function __construct($secretid, $secretkey, $businessid)
  18. {
  19. $this->secretid = $secretid;
  20. $this->secretkey = $secretkey;
  21. $this->businessid = $businessid;
  22. $this->api_url = "https://ye.dun.163yun.com/v1/oneclick/check";
  23. $this->version = "v1";
  24. $this->api_timeout = 5;
  25. $this->internal_string_charset = "auto";
  26. }
  27. /**
  28. * 计算参数签名
  29. * $params 请求参数
  30. * $secretKey secretKey
  31. */
  32. function gen_signature($secretKey, $params)
  33. {
  34. ksort($params);
  35. $buff = "";
  36. foreach ($params as $key => $value) {
  37. if ($value !== null) {
  38. $buff .= $key;
  39. $buff .= $value;
  40. }
  41. }
  42. $buff .= $secretKey;
  43. return md5($buff);
  44. }
  45. /**
  46. * 将输入数据的编码统一转换成utf8
  47. * @params 输入的参数
  48. */
  49. function toUtf8($params)
  50. {
  51. $utf8s = array();
  52. foreach ($params as $key => $value) {
  53. $utf8s[$key] = is_string($value) ? mb_convert_encoding($value, "utf8", $this->internal_string_charset) : $value;
  54. }
  55. return $utf8s;
  56. }
  57. /**
  58. * 易盾本机验证在线检测请求接口简单封装
  59. * $params 请求参数
  60. */
  61. function check($params)
  62. {
  63. $params["secretId"] = $this->secretid;
  64. $params["businessId"] = $this->businessid;
  65. $params["version"] = $this->version;
  66. $params["timestamp"] = sprintf("%d", round(microtime(true) * 1000));
  67. // time in milliseconds
  68. $params["nonce"] = substr(md5(time()), 0, 32);
  69. // random int
  70. $params = $this->toUtf8($params);
  71. $params["signature"] = $this->gen_signature($this->secretkey, $params);
  72. $options = array('http' => array(
  73. 'header' => "Content-type: application/x-www-form-urlencoded\r\n",
  74. 'method' => 'POST',
  75. 'timeout' => $this->api_timeout,
  76. // read timeout in seconds
  77. 'content' => http_build_query($params)
  78. ));
  79. $context = stream_context_create($options);
  80. $result = file_get_contents($this->api_url, false, $context);
  81. if ($result === FALSE) {
  82. return array("code" => 500, "msg" => "file_get_contents failed.");
  83. } else {
  84. return json_decode($result, true);
  85. }
  86. }
  87. }