helpers.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. /*
  3. * This file is part of the overtrue/wechat.
  4. *
  5. * (c) overtrue <i@overtrue.me>
  6. *
  7. * This source file is subject to the MIT license that is bundled
  8. * with this source code in the file LICENSE.
  9. */
  10. /**
  11. * helpers.php.
  12. *
  13. * @author overtrue <i@overtrue.me>
  14. * @copyright 2015 overtrue <i@overtrue.me>
  15. *
  16. * @see https://github.com/overtrue
  17. * @see http://overtrue.me
  18. */
  19. namespace EasyWeChat\Payment;
  20. /**
  21. * Generate a signature.
  22. *
  23. * @param array $attributes
  24. * @param string $key
  25. * @param string $encryptMethod
  26. *
  27. * @return string
  28. */
  29. function generate_sign(array $attributes, $key, $encryptMethod = 'md5')
  30. {
  31. ksort($attributes);
  32. $attributes['key'] = $key;
  33. return strtoupper(call_user_func_array($encryptMethod, $encryptMethod == "md5" ? [urldecode(http_build_query($attributes))] : ['sha256', urldecode(http_build_query($attributes)), $key]));
  34. }
  35. /**
  36. * Get client ip.
  37. *
  38. * @return string
  39. */
  40. function get_client_ip()
  41. {
  42. if (!empty($_SERVER['REMOTE_ADDR'])) {
  43. $ip = $_SERVER['REMOTE_ADDR'];
  44. } else {
  45. // for php-cli(phpunit etc.)
  46. $ip = defined('PHPUNIT_RUNNING') ? '127.0.0.1' : gethostbyname(gethostname());
  47. }
  48. return filter_var($ip, FILTER_VALIDATE_IP) ?: '127.0.0.1';
  49. }
  50. /**
  51. * Get current server ip.
  52. *
  53. * @return string
  54. */
  55. function get_server_ip()
  56. {
  57. if (!empty($_SERVER['SERVER_ADDR'])) {
  58. $ip = $_SERVER['SERVER_ADDR'];
  59. } elseif (!empty($_SERVER['SERVER_NAME'])) {
  60. $ip = gethostbyname($_SERVER['SERVER_NAME']);
  61. } else {
  62. // for php-cli(phpunit etc.)
  63. $ip = defined('PHPUNIT_RUNNING') ? '127.0.0.1' : gethostbyname(gethostname());
  64. }
  65. return filter_var($ip, FILTER_VALIDATE_IP) ?: '127.0.0.1';
  66. }