UnicomHelper.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. namespace app\service\mobile_get;
  3. trait UnicomHelper {
  4. protected static $ZOP_KEY = [
  5. 'appCode' => 'appCode',
  6. 'HMACMD5' => 'HMACMD5',
  7. 'AES' => 'AES'
  8. ];
  9. /**
  10. * uuid 唯一序列码
  11. * @param string $prefix
  12. * @return string
  13. */
  14. function uuid($prefix = '')
  15. {
  16. $chars = md5(uniqid(mt_rand(), true));
  17. $uuid = substr($chars, 0, 8) . '-';
  18. $uuid .= substr($chars, 8, 4) . '-';
  19. $uuid .= substr($chars, 12, 4) . '-';
  20. $uuid .= substr($chars, 16, 4) . '-';
  21. $uuid .= substr($chars, 20, 12);
  22. return $prefix . $uuid;
  23. }
  24. //获取当前时间毫秒
  25. function msectime()
  26. {
  27. list($msec, $sec) = explode(' ', microtime());
  28. $msectime = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
  29. return $msectime;
  30. }
  31. // 时间戳
  32. function getTimestamp()
  33. {
  34. $time = $this->msectime();
  35. return date('Y-m-d H:i:s.') . substr($time, -3);
  36. }
  37. // 生成签名
  38. function genSign($uuid, $timestamp)
  39. {
  40. $dataStr = 'appCode' .self::$ZOP_KEY['appCode'] . 'timestamp' . $timestamp . 'uuid' . $uuid . self::$ZOP_KEY['HMACMD5'];
  41. return $this->sign(self::$ZOP_KEY['HMACMD5'], $dataStr);
  42. }
  43. /**
  44. * 签名
  45. * @param string 密钥 联通侧提供的HmacMD5
  46. * @param string appCode+appCode值+timestamp+timestamp值*+uuid+uuid值+HmacMD5密钥值
  47. */
  48. function sign($key, $dataStr)
  49. {
  50. return base64_encode(hash_hmac("md5", $dataStr, base64_decode($key), true));
  51. }
  52. /**
  53. *AES加密
  54. */
  55. function encrypt($data, $key)
  56. {
  57. $data = openssl_encrypt($data, 'aes-128-ecb', base64_decode($key), OPENSSL_RAW_DATA);
  58. return base64_encode($data);
  59. }
  60. function body($data=[]){
  61. // uuid
  62. $uuid = $this->uuid();
  63. // 生成时间戳
  64. $timestamp = $this->getTimestamp();
  65. $reqObj = [
  66. 'head' => [
  67. 'sign' => $this->genSign($uuid, $timestamp),
  68. 'timestamp' => $timestamp,
  69. 'uuid' => $uuid
  70. ],
  71. 'body' => $data
  72. ];
  73. return $reqObj;
  74. }
  75. }