WeixinServer.php 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. <?php
  2. namespace App\Servers\WeChat;
  3. use App\Servers\Common\RedisDataServer;
  4. class WeixinServer
  5. {
  6. /**
  7. * 单列对象
  8. * @var
  9. */
  10. private static $server = '';
  11. public $appid = '';
  12. public $appsecret = '';
  13. private function __construct(){
  14. $this->appid=env('WX_APPID','');
  15. $this->appsecret=env('WX_APPSECRET','');
  16. }
  17. /**
  18. * 创建对象
  19. * @return WeixinServer
  20. */
  21. static function creatServer()
  22. {
  23. if(empty(self::$server)){
  24. self::$server = new WeixinServer();
  25. }
  26. return self::$server;
  27. }
  28. /**
  29. * 网页授权
  30. * @return mixed
  31. */
  32. function authorize()
  33. {
  34. $code = request()->input('code', '');
  35. if (empty($code)) {
  36. $redirect_url = $this->getServerUrl();
  37. $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->appid}&redirect_uri={$redirect_url}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
  38. $this->redirect($url);
  39. return false;
  40. } else {
  41. $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$this->appid}&secret={$this->appsecret}&code={$code}&grant_type=authorization_code";
  42. $result = $this->sendRequest($url);
  43. $result = json_decode($result, true);
  44. if (isset($result['errcode'])) {
  45. return false;
  46. } else {
  47. // $openid = $result['openid'];
  48. // $access_token = $result['access_token'];
  49. // $url = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid={$this->appid}&grant_type=refresh_token&refresh_token={$result['refresh_token']} ";
  50. // $result = $this->sendRequest($url);
  51. // $result = json_decode($result, true);
  52. // if (isset($result['access_token'])) {
  53. // $access_token = $result['access_token'];
  54. // $openid = $result['openid'];
  55. // }
  56. // $url = "https://api.weixin.qq.com/sns/userinfo?access_token={$access_token}&openid={$openid}&lang=zh_CN";
  57. // $result = $this->sendRequest($url);
  58. // $result = json_decode($result, true);
  59. // if (isset($result['errcode'])) {
  60. // return false;
  61. // }
  62. return $result;
  63. }
  64. }
  65. }
  66. /**
  67. * 获取当前连接
  68. * @return string
  69. */
  70. function getServerUrl()
  71. {
  72. return urlencode('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
  73. }
  74. function redirect($uri = '', $method = 'location', $http_response_code = 302)
  75. {
  76. if (!preg_match('#^https?://#i', $uri)) {
  77. $uri = site_url($uri);
  78. }
  79. switch ($method) {
  80. case 'refresh' :
  81. header("Refresh:0;url=" . $uri);
  82. break;
  83. default :
  84. header("Location: " . $uri, TRUE, $http_response_code);
  85. break;
  86. }
  87. exit();
  88. }
  89. /**
  90. * @param $url
  91. * @param string $type 请求方式
  92. * @param string $data 数据 数组格式
  93. * @return mixed
  94. */
  95. protected function sendRequest($url, $type = 'get', $data = '')
  96. {
  97. $ch = curl_init();
  98. if ($type == 'get' && $data) {
  99. $url = $url . '?' . http_build_query($data);
  100. }
  101. curl_setopt($ch, CURLOPT_URL, $url); //设置访问路径
  102. curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); //设置可以返回字符串
  103. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  104. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  105. $head = array('User-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36');
  106. curl_setopt($ch, CURLOPT_HTTPHEADER, $head);
  107. if ($type == 'post') {
  108. curl_setopt($ch, CURLOPT_POST, TRUE);//post请求
  109. $data = json_encode($data, JSON_UNESCAPED_UNICODE);
  110. curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//设置传递的参数
  111. }
  112. $request = curl_exec($ch);
  113. curl_close($ch);
  114. return $request;
  115. }
  116. /**
  117. * 获取js授权信息
  118. * @return mixed
  119. */
  120. function getJsConfig($url = '')
  121. {
  122. $hash = '';
  123. $chars = 'ABCDEFGHIJKMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz';
  124. $max = strlen($chars) - 1;
  125. for ($i = 0; $i < 16; $i++) {
  126. $hash .= $chars[mt_rand(0, $max)];
  127. }
  128. $data['noncestr'] = $hash;
  129. $data['jsapi_ticket'] = $this->getJsTicket();
  130. $data['timestamp'] = time();
  131. if (empty($url)) {
  132. $data['url'] = $this->getServerUrl();
  133. } else {
  134. $data['url'] = $url;
  135. }
  136. ksort($data);
  137. $str = '';
  138. foreach ($data as $key => $val) {
  139. $str .= '&';
  140. $str .= $key . '=' . $val;
  141. }
  142. $str = mb_substr($str, 1);
  143. $data['appid'] = $this->appid;
  144. $data['signature'] = sha1($str);
  145. unset($data['jsapi_ticket']);
  146. return $data;
  147. }
  148. /**
  149. * 获取 access_token
  150. * @return bool
  151. */
  152. protected function getAccessToken($type = 1)
  153. {
  154. $key = 'vouchername';
  155. $appId = $this->appid;
  156. $appsecret = $this->appsecret;
  157. $data = RedisDataServer::creatServer()->getData($key, 'json');
  158. if (empty($data) || $data['endtime'] < time() || true) {
  159. $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appId}&secret={$appsecret}";
  160. $result = $this->sendRequest($url);
  161. $result = json_decode($result, true);
  162. // $bey = Cache::set('vouchername', array('access_token' => $result['access_token'], 'endtime' => time() + 7000), 7000);
  163. if ( isset($result['access_token'])) {
  164. RedisDataServer::creatServer()->setData($key, array('access_token' => $result['access_token'], 'endtime' => time() + 1800), 'json',1800);
  165. return $result['access_token'];
  166. } else {
  167. return false;
  168. }
  169. } else {
  170. return $data['access_token'];
  171. }
  172. }
  173. /**
  174. * 获取Js调用凭证
  175. * @return bool
  176. */
  177. function getJsTicket()
  178. {
  179. // $data = Cache::get('js_ticket');
  180. $data = RedisDataServer::creatServer()->getData('js_ticket', 'json');
  181. if (empty($data) || $data['endtime'] < time()) {
  182. $access_token = $this->getAccessToken();
  183. $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={$access_token}&type=jsapi";
  184. $result = $this->sendRequest($url);
  185. $result = json_decode($result, true);
  186. if ($result['errcode'] == 0) {
  187. //file_put_contents($this->js_ticket,serialize(array('access_token'=>$result['access_token'],'endtime'=>time()+7000)));
  188. // Cache::set('js_ticket', array('access_token' => $result['ticket'], 'endtime' => time() + 7000), 7000);
  189. RedisDataServer::creatServer()->setData('js_ticket', array('access_token' => $result['ticket'], 'endtime' => time() + 7000), 'json',7000);
  190. return $result['ticket'];
  191. }
  192. return false;
  193. } else {
  194. return $data['access_token'];
  195. }
  196. }
  197. }