Wechat.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  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 = 4000, $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 = 4000, $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 = 4000, $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. if ($result['errcode'] == 40001) {
  280. $token = $this->token(false, false, 4000, true);
  281. return $this->curl($type, array(), $alert);
  282. }
  283. $result = $param + $result;
  284. Dever::log($result);
  285. if ($alert && $this->alert == 2) {
  286. Dever::alert(json_encode($result, JSON_UNESCAPED_UNICODE));
  287. }
  288. }
  289. if (isset($param['response'])) {
  290. foreach ($param['response'] as $k => $v) {
  291. if (strpos($k, '.')) {
  292. $temp = explode('.', $k);
  293. if (isset($result[$temp[0]][$temp[1]])) {
  294. $result[$v] = $result[$temp[0]][$temp[1]];
  295. }
  296. } elseif (isset($result[$k])) {
  297. $result[$v] = $result[$k];
  298. }
  299. if (strpos($v, 'callback.') !== false) {
  300. $temp = explode('callback.', $v);
  301. $result['callback'][] = array($temp[1], $result[$v]);
  302. }
  303. }
  304. }
  305. return $result;
  306. }
  307. public function log($result, $name, $url, $param)
  308. {
  309. $insert['name'] = $name;
  310. $insert['url'] = $url;
  311. $insert['result'] = json_encode($result, JSON_UNESCAPED_UNICODE);
  312. $insert['param'] = json_encode($param, JSON_UNESCAPED_UNICODE);
  313. Dever::db('token/log')->insert($insert);
  314. }
  315. /**
  316. * 拼装wechat需要的参数
  317. *
  318. * @return mixed
  319. */
  320. public function param($method, $param = array())
  321. {
  322. if (strpos($method, '.')) {
  323. $temp = explode('.', $method);
  324. $config = $this->config[$temp[0]][$temp[1]];
  325. } else {
  326. if (!isset($this->config[$method])) {
  327. return false;
  328. }
  329. $config = $this->config[$method];
  330. }
  331. if (!$param) {
  332. $param = array();
  333. }
  334. $param = $this->project + $param;
  335. //print_r($param);die;
  336. foreach ($config['param'] as $k => $v) {
  337. if ($v == 'token') {
  338. $config['url'] .= $k . '=' . $this->token();
  339. unset($config['param'][$k]);
  340. } elseif ($v == 'ticket') {
  341. $config['param'][$k] = $this->ticket();
  342. } elseif ($v == 'code') {
  343. $config['param'][$k] = $this->code();
  344. } elseif ($v == 'oauth') {
  345. if (!isset($param['oauth'])) {
  346. Dever::alert('oauth erorr');
  347. } elseif (is_numeric($param['oauth'])) {
  348. $oauth = $this->oauth($param['oauth']);
  349. $param['oauth'] = $oauth['value'];
  350. }
  351. $config['url'] .= $k . '=' . $param['oauth'];
  352. unset($config['param'][$k]);
  353. } elseif (!is_array($v) && isset($param[$v])) {
  354. $config['param'][$k] = $param[$v];
  355. } elseif($v) {
  356. $config['param'][$k] = $this->replace($v, $param);
  357. }
  358. }
  359. $config['json'] = isset($config['json']) && $config['json'] ? true : false;
  360. return $config;
  361. }
  362. /**
  363. * 替换{}
  364. *
  365. * @return mixed
  366. */
  367. public function replace($value, $param)
  368. {
  369. if (isset($param['domain']) && is_string($value) && strpos($value, '{domain}') !== false) {
  370. foreach ($param['domain'] as $k => $v) {
  371. $param['domain'][$k] = str_replace('{domain}', $v, $value);
  372. }
  373. return $param['domain'];
  374. }
  375. if (is_array($value)) {
  376. foreach ($value as $k => $v) {
  377. if (isset($param[$v])) {
  378. $value[$k] = $param[$v];
  379. } else {
  380. $value[$k] = $this->replace($v, $param);
  381. }
  382. }
  383. $value = Dever::json_encode($value);
  384. }
  385. return $value;
  386. }
  387. /**
  388. * 消息解密
  389. *
  390. * @return mixed
  391. */
  392. public function decode($sign, $timestamp, $nonce, $encrypt)
  393. {
  394. include(DEVER_PROJECT_PATH . 'example/wxBizMsgCrypt.php');
  395. $crypt = new \WXBizMsgCrypt($this->project['token'], $this->project['key'], $this->project['appid']);
  396. $format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%s]]></Encrypt></xml>";
  397. $xml = sprintf($format, $encrypt);
  398. $result = '';
  399. $code = $crypt->decryptMsg($sign, $timestamp, $nonce, $xml, $result);
  400. if ($code == 0) {
  401. libxml_disable_entity_loader(true);
  402. $result = (array) simplexml_load_string($result, 'SimpleXMLElement', LIBXML_NOCDATA);
  403. }
  404. return $result;
  405. }
  406. /**
  407. * 获取nonce
  408. *
  409. * @return mixed
  410. */
  411. public function nonce()
  412. {
  413. return substr(md5(microtime()), rand(10, 15));
  414. }
  415. /**
  416. * 获取signature
  417. *
  418. * @return mixed
  419. */
  420. public function signature($ticket, $url, $timestamp, $noncestr)
  421. {
  422. /*
  423. $info = array();
  424. $info['jsapi_ticket'] = $ticket;
  425. $info['url'] = $url;
  426. $info['timestamp'] = $timestamp;
  427. $info['noncestr'] = $noncestr;
  428. ksort($info);
  429. */
  430. $signature_string = "jsapi_ticket=$ticket&noncestr=$noncestr&timestamp=$timestamp&url=$url";
  431. //$signature_string = substr(http_build_query($info), 0, -1);
  432. return sha1($signature_string);
  433. }
  434. /**
  435. * 获取sign签名数据包
  436. *
  437. * @return mixed
  438. */
  439. public function sign($url)
  440. {
  441. $ticket = $this->ticket();
  442. if (!$url) {
  443. $url = Dever::url();
  444. } else {
  445. $url = htmlspecialchars_decode($url);
  446. }
  447. $timestamp = time();
  448. $noncestr = $this->nonce();
  449. $signature = $this->signature($ticket, $url, $timestamp, $noncestr);
  450. $sign = array();
  451. $sign['appId'] = $this->project['appid'];
  452. $sign['nonceStr'] = $noncestr;
  453. $sign['timestamp'] = $timestamp;
  454. $sign['url'] = $url;
  455. $sign['signature'] = $signature;
  456. return $sign;
  457. }
  458. }