Wechat.php 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. <?php
  2. /**
  3. * 易优CMS
  4. * ============================================================================
  5. * 版权所有 2016-2028 海南赞赞网络科技有限公司,并保留所有权利。
  6. * 网站地址: http://www.eyoucms.com
  7. * ----------------------------------------------------------------------------
  8. * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
  9. * ============================================================================
  10. * Author: 小虎哥 <1105415366@qq.com>
  11. * Date: 2018-4-3
  12. */
  13. namespace app\plugins\controller;
  14. class Wechat extends Base
  15. {
  16. /**
  17. * 公众号配置
  18. */
  19. public $config;
  20. /**
  21. * 逻辑对象
  22. */
  23. public $logic_obj;
  24. /**
  25. * 是否来自于微信的服务器配置验证
  26. */
  27. public $is_check_signature = false;
  28. /**
  29. * 构造方法
  30. */
  31. public function __construct($appid = '', $ctl = ''){
  32. parent::__construct();
  33. //获取配置
  34. $map = array(
  35. 'appid' => $appid,
  36. );
  37. $this->config = M('weapp_wx_config')->where($map)->find();
  38. if ($this->config['wait_access'] == 0) {
  39. exit($_GET["echostr"]);
  40. }
  41. $echostr = isset($_GET['echostr']) ? $_GET['echostr'] : ''; // 是否来自于微信的服务器配置验证
  42. if ($echostr) {
  43. $this->is_check_signature = true;
  44. }else{
  45. $this->is_check_signature = false;
  46. $this->logic_obj = $this->getctl($ctl, $this->config);
  47. }
  48. }
  49. public function getctl($ctl = '', $config = array())
  50. {
  51. $class = '\\app\\plugins\\logic\\Wechat'.$ctl.'Logic'; //
  52. return new $class($config);
  53. }
  54. /**
  55. * 服务器地址(用户消息和开发者需要的事件推送,会被转发到该URL中)
  56. */
  57. public function valid()
  58. {
  59. if ($this->is_check_signature) {
  60. $this->checkSignature();
  61. }else{
  62. $this->logic_obj->responseMsg();
  63. }
  64. }
  65. /**
  66. * 开发者对签名(即signature)的效验,来判断此条消息的真实性
  67. * @return [type] [description]
  68. */
  69. public function checkSignature()
  70. {
  71. //微信会发送4个参数到我们的服务器后台 签名 时间戳 随机字符串 随机数
  72. $signature = $_GET['signature']; // 签名
  73. $timestamp = $_GET['timestamp']; // 时间戳
  74. $echoStr = $_GET['echostr']; // 随机字符串
  75. $nonce = $_GET['nonce']; // 随机数
  76. if ($signature && $timestamp && $echoStr && $nonce) {
  77. // 微信公众号基本配置中的token
  78. $token = $this->config['w_token'];
  79. //将token、timestamp、nonce按字典序排序
  80. $tmpArr = array($token, $timestamp, $nonce);
  81. sort($tmpArr, SORT_STRING);
  82. // 将三个参数字符串拼接成一个字符串进行sha1加密
  83. $tmpStr = implode($tmpArr);
  84. $tmpStr = sha1($tmpStr);
  85. // 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信
  86. if($tmpStr == $signature){
  87. header('content-type:text');
  88. exit($echoStr);
  89. } else {
  90. exit('');
  91. }
  92. }
  93. }
  94. }