Wechat.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  1. <?php
  2. /*
  3. |--------------------------------------------------------------------------
  4. | core.php 微信平台核心类
  5. |--------------------------------------------------------------------------
  6. */
  7. namespace Token\Lib;
  8. use Dever;
  9. class Wechat
  10. {
  11. /**
  12. * config
  13. *
  14. * @var array
  15. */
  16. private $config;
  17. /**
  18. * project
  19. *
  20. * @var string
  21. */
  22. private $project;
  23. /**
  24. * alert
  25. *
  26. * @var int
  27. */
  28. private $alert;
  29. /**
  30. * 构造函数 初始化
  31. *
  32. * @return mixed
  33. */
  34. public function __construct($project = false, $type = '')
  35. {
  36. $this->config = Dever::config('wechat', $type)->cAll;
  37. $type = $this->config['type'];
  38. if (!$project) {
  39. $appid = Dever::input('appid');
  40. if ($appid) {
  41. $project = Dever::db('token/project')->one(array('option_type' => $type, 'option_appid' => $appid));
  42. }
  43. /*
  44. if (!$project) {
  45. $project = Dever::db('token/project')->one(array('option_type' => $type));
  46. }
  47. */
  48. if (!$project) {
  49. $project = Dever::input('project', 1);
  50. }
  51. }
  52. if (is_numeric($project)) {
  53. $project = Dever::db('token/project')->one(array('option_type' => $type, 'option_id' => $project));
  54. }
  55. if (!$project) {
  56. Dever::alert('project is not exits!');
  57. }
  58. $this->project = $project;
  59. }
  60. /**
  61. * 获取当前站点的配置
  62. *
  63. * @return mixed
  64. */
  65. public function project()
  66. {
  67. return $this->project;
  68. }
  69. /**
  70. * 获取当前基本的配置
  71. *
  72. * @return mixed
  73. */
  74. public function config()
  75. {
  76. return $this->config;
  77. }
  78. /**
  79. * 更新数据库
  80. * state true为强制更新数据库中的token数据
  81. *
  82. * @return mixed
  83. */
  84. private function save($type = 'ticket', $value, $expires = false, $interval = 2000, $data = false, $state = false)
  85. {
  86. $refresh = false;
  87. if (strpos($type, '.')) {
  88. $temp = explode('.', $type);
  89. if ($temp[1] == 'refresh') {
  90. $refresh = true;
  91. $temp[1] = 'oauth';
  92. }
  93. $table = 'token/' . $temp[1];
  94. } else {
  95. $table = 'token/' . $type;
  96. }
  97. $db = Dever::db($table);
  98. if ($data) {
  99. if (isset($data['id'])) {
  100. $where['option_id'] = $data['id'];
  101. unset($data['id']);
  102. }
  103. if (isset($data['openid'])) {
  104. $where['option_openid'] = $data['openid'];
  105. }
  106. if (isset($data['unionid'])) {
  107. $where['option_unionid'] = $data['unionid'];
  108. }
  109. }
  110. $where['option_project_id'] = $this->project['id'];
  111. $info = $db->one($where);
  112. $update = false;
  113. if ($state == true) {
  114. $update = true;
  115. } elseif ($info && time() - $info['mdate'] >= $info['expires']) {
  116. $update = true;
  117. } elseif($info) {
  118. return $info;
  119. }
  120. if (!$info) {
  121. $update = false;
  122. }
  123. if (!$value) {
  124. $value = $this->param($type, $info);
  125. }
  126. if (is_array($value) || (is_string($value) && strstr($value, 'http://'))) {
  127. if ($refresh) {
  128. $result = $this->curl(false, $value, false, $type);
  129. } else {
  130. $result = $this->curl(false, $value, true, $type);
  131. }
  132. $key = $type;
  133. if ($result && isset($result[$key])) {
  134. $data = $result;
  135. $data['value'] = $result[$key];
  136. $data['expires'] = $result['expires_in'];
  137. }
  138. } else {
  139. $data['value'] = $value;
  140. $data['expires'] = $expires;
  141. }
  142. if ($data && isset($data['value']) && $data['value']) {
  143. $data['project_id'] = $this->project['id'];
  144. $expires = $data['expires'] - $interval;
  145. if ($expires <= 0) {
  146. $data['expires'] = $data['expires'] - 300;
  147. } else {
  148. $data['expires'] = $expires;
  149. }
  150. if ($update == true) {
  151. $data['where_id'] = $info['id'];
  152. $id = $info['id'];
  153. $db->update($data);
  154. } else {
  155. $id = $db->insert($data);
  156. }
  157. $data['id'] = $id;
  158. if ($id > 0 && isset($result['callback'])) {
  159. foreach ($result['callback'] as $v) {
  160. Dever::load($v[0], $id, $v[1], $this->project['id']);
  161. }
  162. }
  163. } elseif($info && $info['value']) {
  164. $data = $info;
  165. $data['value'] = $info['value'];
  166. }
  167. return $data;
  168. }
  169. /**
  170. * 获取最新的token
  171. *
  172. * @return mixed
  173. */
  174. public function token($value = false, $expires = false, $interval = 2000, $state = false)
  175. {
  176. $result = $this->save('token', $value, $expires, $interval, false, $state);
  177. return $result['value'];
  178. }
  179. /**
  180. * 获取最新的ticket
  181. *
  182. * @return mixed
  183. */
  184. public function ticket($value = false, $expires = false, $interval = 200, $state = false)
  185. {
  186. $result = $this->save('ticket', $value, $expires, $interval, false, $state);
  187. return $result['value'];
  188. }
  189. /**
  190. * 获取最新的oauth token
  191. *
  192. * @return mixed
  193. */
  194. public function oauth($param, $interval = 2000, $state = false)
  195. {
  196. if (is_array($param) && isset($param['auth_code'])) {
  197. $result = $this->curl('oauth.oauth', $param);
  198. if (isset($result['oauth.oauth'])) {
  199. return $this->save('oauth.oauth', $result['oauth.oauth'], $result['expires_in'], $interval, $result);
  200. } else {
  201. Dever::alert('oauth error');
  202. }
  203. } else {
  204. if (is_numeric($param)) {
  205. $id = $param;
  206. $param = array();
  207. $param['id'] = $id;
  208. }
  209. return $this->save('oauth.refresh', false, false, $interval, $param, $state);
  210. }
  211. }
  212. /**
  213. * 获取最新的code
  214. *
  215. * @return mixed
  216. */
  217. public function code($value = false, $expires = false, $interval = 200)
  218. {
  219. $result = $this->save('oauth.code', $value, $expires, $interval, false, true);
  220. return $result['value'];
  221. }
  222. /**
  223. * 获取最新的openid
  224. *
  225. * @return mixed
  226. */
  227. public function openid($id, $key = 'openid')
  228. {
  229. $info = Dever::db('token/oauth')->one($id);
  230. return $info[$key];
  231. }
  232. /**
  233. * 获取最新的oauth login地址
  234. *
  235. * @return mixed
  236. */
  237. public function login($callback = false, $code = false, $location = true)
  238. {
  239. if (!$code) {
  240. $code = $this->code();
  241. }
  242. $callback = Dever::url($callback);
  243. $config = $this->param('oauth.login', array('code' => $code, 'redirect' => $callback));
  244. $url = $config['url'] . http_build_query($config['param']);
  245. if ($location == true) {
  246. Dever::location($url);
  247. }
  248. return $url;
  249. }
  250. /**
  251. * 从wechat获取数据
  252. *
  253. * @return mixed
  254. */
  255. public function curl($method, $param = array(), $alert = true, $type = false)
  256. {
  257. if (!$this->alert) {
  258. if (!$alert) {
  259. $this->alert = 1;
  260. } else {
  261. $this->alert = 2;
  262. }
  263. }
  264. //return array();
  265. if (is_string($param)) {
  266. $result = json_decode(Dever::curl($param), true);
  267. } else {
  268. if ($method) {
  269. $param = $this->param($method, $param);
  270. }
  271. $result = Dever::curl($param['url'], $param['param'], $param['method'], $param['json']);
  272. if (isset($param['response']['img'])) {
  273. return $result;
  274. }
  275. $result = json_decode($result, true);
  276. $this->log($result, $param['name'], $param['url'], $param['param']);
  277. }
  278. if (isset($result['errcode']) && $result['errcode'] != 0) {
  279. /*
  280. if ($result['errcode'] == 40001) {
  281. $token = $this->token(false, false, 2000, true);
  282. return $this->curl($type, array(), $alert);
  283. }
  284. */
  285. $result = $param + $result;
  286. Dever::log($result);
  287. if ($alert && $this->alert == 2) {
  288. Dever::alert(json_encode($result, JSON_UNESCAPED_UNICODE));
  289. }
  290. }
  291. if (isset($param['response'])) {
  292. foreach ($param['response'] as $k => $v) {
  293. if (strpos($k, '.')) {
  294. $temp = explode('.', $k);
  295. if (isset($result[$temp[0]][$temp[1]])) {
  296. $result[$v] = $result[$temp[0]][$temp[1]];
  297. }
  298. } elseif (isset($result[$k])) {
  299. $result[$v] = $result[$k];
  300. }
  301. if (strpos($v, 'callback.') !== false) {
  302. $temp = explode('callback.', $v);
  303. $result['callback'][] = array($temp[1], $result[$v]);
  304. }
  305. }
  306. }
  307. return $result;
  308. }
  309. public function log($result, $name, $url, $param)
  310. {
  311. $insert['name'] = $name;
  312. $insert['url'] = $url;
  313. $insert['result'] = json_encode($result, JSON_UNESCAPED_UNICODE);
  314. $insert['param'] = json_encode($param, JSON_UNESCAPED_UNICODE);
  315. Dever::db('token/log')->insert($insert);
  316. }
  317. /**
  318. * 拼装wechat需要的参数
  319. *
  320. * @return mixed
  321. */
  322. public function param($method, $param = array())
  323. {
  324. if (strpos($method, '.')) {
  325. $temp = explode('.', $method);
  326. $config = $this->config[$temp[0]][$temp[1]];
  327. } else {
  328. if (!isset($this->config[$method])) {
  329. return false;
  330. }
  331. $config = $this->config[$method];
  332. }
  333. if (!$param) {
  334. $param = array();
  335. }
  336. $param = $this->project + $param;
  337. //print_r($param);die;
  338. foreach ($config['param'] as $k => $v) {
  339. if ($v == 'token') {
  340. $config['url'] .= $k . '=' . $this->token();
  341. unset($config['param'][$k]);
  342. } elseif ($v == 'ticket') {
  343. $config['param'][$k] = $this->ticket();
  344. } elseif ($v == 'code') {
  345. $config['param'][$k] = $this->code();
  346. } elseif ($v == 'oauth') {
  347. if (!isset($param['oauth'])) {
  348. Dever::alert('oauth erorr');
  349. } elseif (is_numeric($param['oauth'])) {
  350. $oauth = $this->oauth($param['oauth']);
  351. $param['oauth'] = $oauth['value'];
  352. }
  353. $config['url'] .= $k . '=' . $param['oauth'];
  354. unset($config['param'][$k]);
  355. } elseif (!is_array($v) && isset($param[$v])) {
  356. $config['param'][$k] = $param[$v];
  357. } elseif($v) {
  358. $config['param'][$k] = $this->replace($v, $param);
  359. }
  360. }
  361. $config['json'] = isset($config['json']) && $config['json'] ? true : false;
  362. return $config;
  363. }
  364. /**
  365. * 替换{}
  366. *
  367. * @return mixed
  368. */
  369. public function replace($value, $param)
  370. {
  371. if (isset($param['domain']) && strpos($value, '{domain}') !== false) {
  372. foreach ($param['domain'] as $k => $v) {
  373. $param['domain'][$k] = str_replace('{domain}', $v, $value);
  374. }
  375. return $param['domain'];
  376. }
  377. return $value;
  378. }
  379. /**
  380. * 消息解密
  381. *
  382. * @return mixed
  383. */
  384. public function decode($sign, $timestamp, $nonce, $encrypt)
  385. {
  386. include(DEVER_PROJECT_PATH . 'example/wxBizMsgCrypt.php');
  387. $crypt = new \WXBizMsgCrypt($this->project['token'], $this->project['key'], $this->project['appid']);
  388. $format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%s]]></Encrypt></xml>";
  389. $xml = sprintf($format, $encrypt);
  390. $result = '';
  391. $code = $crypt->decryptMsg($sign, $timestamp, $nonce, $xml, $result);
  392. if ($code == 0) {
  393. libxml_disable_entity_loader(true);
  394. $result = (array) simplexml_load_string($result, 'SimpleXMLElement', LIBXML_NOCDATA);
  395. }
  396. return $result;
  397. }
  398. /**
  399. * 获取nonce
  400. *
  401. * @return mixed
  402. */
  403. public function nonce()
  404. {
  405. return substr(md5(microtime()), rand(10, 15));
  406. }
  407. /**
  408. * 获取signature
  409. *
  410. * @return mixed
  411. */
  412. public function signature($ticket, $url, $timestamp, $noncestr)
  413. {
  414. /*
  415. $info = array();
  416. $info['jsapi_ticket'] = $ticket;
  417. $info['url'] = $url;
  418. $info['timestamp'] = $timestamp;
  419. $info['noncestr'] = $noncestr;
  420. ksort($info);
  421. */
  422. $signature_string = "jsapi_ticket=$ticket&noncestr=$noncestr&timestamp=$timestamp&url=$url";
  423. //$signature_string = substr(http_build_query($info), 0, -1);
  424. return sha1($signature_string);
  425. }
  426. /**
  427. * 获取sign签名数据包
  428. *
  429. * @return mixed
  430. */
  431. public function sign($url)
  432. {
  433. $ticket = $this->ticket();
  434. if (!$url) {
  435. $url = Dever::url();
  436. } else {
  437. $url = htmlspecialchars_decode($url);
  438. }
  439. $timestamp = time();
  440. $noncestr = $this->nonce();
  441. $signature = $this->signature($ticket, $url, $timestamp, $noncestr);
  442. $sign = array();
  443. $sign['appId'] = $this->project['appid'];
  444. $sign['nonceStr'] = $noncestr;
  445. $sign['timestamp'] = $timestamp;
  446. $sign['url'] = $url;
  447. $sign['signature'] = $signature;
  448. return $sign;
  449. }
  450. }