Wechat.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  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. # 为方便测试,这里可以直接用接口返回的token
  128. $result = array();
  129. if ($type == 'token' && isset($this->project['url']) && $this->project['url']) {
  130. $param = array('type' => $type, 'appid' => $this->project['appid']);
  131. $param = Dever::token($param, $this->project['secret']);
  132. $result = Dever::curl($this->project['url'], $param);
  133. $result = Dever::json_decode($result);
  134. if (isset($result['data'])) {
  135. $result = $result['data'];
  136. }
  137. }
  138. if (!$result) {
  139. if ($refresh) {
  140. $result = $this->curl(false, $value, false, $type);
  141. } else {
  142. $result = $this->curl(false, $value, true, $type);
  143. }
  144. }
  145. $key = $type;
  146. if ($result && isset($result[$key])) {
  147. $data = $result;
  148. $data['value'] = $result[$key];
  149. $data['expires'] = $result['expires_in'];
  150. }
  151. } else {
  152. $data['value'] = $value;
  153. $data['expires'] = $expires;
  154. }
  155. if ($data && isset($data['value']) && $data['value']) {
  156. $data['project_id'] = $this->project['id'];
  157. $expires = $data['expires'] - $interval;
  158. if ($expires <= 0) {
  159. $data['expires'] = $data['expires'] - 300;
  160. } else {
  161. $data['expires'] = $expires;
  162. }
  163. if ($update == true) {
  164. $data['where_id'] = $info['id'];
  165. $id = $info['id'];
  166. $db->update($data);
  167. } else {
  168. $id = $db->insert($data);
  169. }
  170. $data['id'] = $id;
  171. if ($id > 0 && isset($result['callback'])) {
  172. foreach ($result['callback'] as $v) {
  173. Dever::load($v[0], $id, $v[1], $this->project['id']);
  174. }
  175. }
  176. } elseif($info && $info['value']) {
  177. $data = $info;
  178. $data['value'] = $info['value'];
  179. }
  180. return $data;
  181. }
  182. /**
  183. * 获取最新的token
  184. *
  185. * @return mixed
  186. */
  187. public function token($value = false, $expires = false, $interval = 4000, $state = false)
  188. {
  189. $result = $this->save('token', $value, $expires, $interval, false, $state);
  190. return $result['value'];
  191. }
  192. /**
  193. * 获取最新的ticket
  194. *
  195. * @return mixed
  196. */
  197. public function ticket($value = false, $expires = false, $interval = 200, $state = false)
  198. {
  199. $result = $this->save('ticket', $value, $expires, $interval, false, $state);
  200. return $result['value'];
  201. }
  202. /**
  203. * 获取最新的oauth token
  204. *
  205. * @return mixed
  206. */
  207. public function oauth($param, $interval = 4000, $state = false)
  208. {
  209. if (is_array($param) && isset($param['auth_code'])) {
  210. $result = $this->curl('oauth.oauth', $param);
  211. if (isset($result['oauth.oauth'])) {
  212. return $this->save('oauth.oauth', $result['oauth.oauth'], $result['expires_in'], $interval, $result);
  213. } else {
  214. Dever::alert('oauth error');
  215. }
  216. } else {
  217. if (is_numeric($param)) {
  218. $id = $param;
  219. $param = array();
  220. $param['id'] = $id;
  221. }
  222. return $this->save('oauth.refresh', false, false, $interval, $param, $state);
  223. }
  224. }
  225. /**
  226. * 获取最新的code
  227. *
  228. * @return mixed
  229. */
  230. public function code($value = false, $expires = false, $interval = 200)
  231. {
  232. $result = $this->save('oauth.code', $value, $expires, $interval, false, true);
  233. return $result['value'];
  234. }
  235. /**
  236. * 获取最新的openid
  237. *
  238. * @return mixed
  239. */
  240. public function openid($id, $key = 'openid')
  241. {
  242. $info = Dever::db('token/oauth')->one($id);
  243. return $info[$key];
  244. }
  245. /**
  246. * 获取最新的oauth login地址
  247. *
  248. * @return mixed
  249. */
  250. public function login($callback = false, $code = false, $location = true)
  251. {
  252. if (!$code) {
  253. $code = $this->code();
  254. }
  255. $callback = Dever::url($callback);
  256. $config = $this->param('oauth.login', array('code' => $code, 'redirect' => $callback));
  257. $url = $config['url'] . http_build_query($config['param']);
  258. if ($location == true) {
  259. Dever::location($url);
  260. }
  261. return $url;
  262. }
  263. /**
  264. * 从wechat获取数据
  265. *
  266. * @return mixed
  267. */
  268. public function curl($method, $param = array(), $alert = true, $type = false)
  269. {
  270. if (!$this->alert) {
  271. if (!$alert) {
  272. $this->alert = 1;
  273. } else {
  274. $this->alert = 2;
  275. }
  276. }
  277. //return array();
  278. if (is_string($param)) {
  279. $result = json_decode(Dever::curl($param), true);
  280. } else {
  281. if ($method) {
  282. $param = $this->param($method, $param);
  283. }
  284. $result = Dever::curl($param['url'], $param['param'], $param['method'], $param['json']);
  285. if (isset($param['response']['img'])) {
  286. return $result;
  287. }
  288. $result = json_decode($result, true);
  289. $this->log($result, $param['name'], $param['url'], $param['param']);
  290. }
  291. if (isset($result['errcode']) && $result['errcode'] != 0) {
  292. if ($result['errcode'] == 40001) {
  293. $token = $this->token(false, false, 4000, true);
  294. return $this->curl($type, array(), $alert);
  295. }
  296. $result = $param + $result;
  297. Dever::log($result);
  298. if ($alert && $this->alert == 2) {
  299. Dever::alert(json_encode($result, JSON_UNESCAPED_UNICODE));
  300. }
  301. }
  302. if (isset($param['response'])) {
  303. foreach ($param['response'] as $k => $v) {
  304. if (strpos($k, '.')) {
  305. $temp = explode('.', $k);
  306. if (isset($result[$temp[0]][$temp[1]])) {
  307. $result[$v] = $result[$temp[0]][$temp[1]];
  308. }
  309. } elseif (isset($result[$k])) {
  310. $result[$v] = $result[$k];
  311. }
  312. if (strpos($v, 'callback.') !== false) {
  313. $temp = explode('callback.', $v);
  314. $result['callback'][] = array($temp[1], $result[$v]);
  315. }
  316. }
  317. }
  318. return $result;
  319. }
  320. public function log($result, $name, $url, $param)
  321. {
  322. $insert['name'] = $name;
  323. $insert['url'] = $url;
  324. $insert['result'] = json_encode($result, JSON_UNESCAPED_UNICODE);
  325. $insert['param'] = json_encode($param, JSON_UNESCAPED_UNICODE);
  326. Dever::db('token/log')->insert($insert);
  327. }
  328. /**
  329. * 拼装wechat需要的参数
  330. *
  331. * @return mixed
  332. */
  333. public function param($method, $param = array())
  334. {
  335. if (strpos($method, '.')) {
  336. $temp = explode('.', $method);
  337. $config = $this->config[$temp[0]][$temp[1]];
  338. } else {
  339. if (!isset($this->config[$method])) {
  340. return false;
  341. }
  342. $config = $this->config[$method];
  343. }
  344. if (!$param) {
  345. $param = array();
  346. }
  347. $param = $this->project + $param;
  348. //print_r($param);die;
  349. foreach ($config['param'] as $k => $v) {
  350. if ($v == 'token') {
  351. $config['url'] .= $k . '=' . $this->token();
  352. unset($config['param'][$k]);
  353. } elseif ($v == 'ticket') {
  354. $config['param'][$k] = $this->ticket();
  355. } elseif ($v == 'code') {
  356. $config['param'][$k] = $this->code();
  357. } elseif ($v == 'oauth') {
  358. if (!isset($param['oauth'])) {
  359. Dever::alert('oauth erorr');
  360. } elseif (is_numeric($param['oauth'])) {
  361. $oauth = $this->oauth($param['oauth']);
  362. $param['oauth'] = $oauth['value'];
  363. }
  364. $config['url'] .= $k . '=' . $param['oauth'];
  365. unset($config['param'][$k]);
  366. } elseif (!is_array($v) && isset($param[$v])) {
  367. $config['param'][$k] = $param[$v];
  368. } elseif($v) {
  369. $config['param'][$k] = $this->replace($v, $param);
  370. }
  371. }
  372. $config['json'] = isset($config['json']) && $config['json'] ? true : false;
  373. return $config;
  374. }
  375. /**
  376. * 替换{}
  377. *
  378. * @return mixed
  379. */
  380. public function replace($value, $param)
  381. {
  382. if (isset($param['domain']) && is_string($value) && strpos($value, '{domain}') !== false) {
  383. foreach ($param['domain'] as $k => $v) {
  384. $param['domain'][$k] = str_replace('{domain}', $v, $value);
  385. }
  386. return $param['domain'];
  387. }
  388. if (is_array($value)) {
  389. foreach ($value as $k => $v) {
  390. if (isset($param[$v])) {
  391. $value[$k] = $param[$v];
  392. } else {
  393. $value[$k] = $this->replace($v, $param);
  394. }
  395. }
  396. $value = Dever::json_encode($value);
  397. }
  398. return $value;
  399. }
  400. /**
  401. * 消息解密
  402. *
  403. * @return mixed
  404. */
  405. public function decode($sign, $timestamp, $nonce, $encrypt)
  406. {
  407. include(DEVER_PROJECT_PATH . 'example/wxBizMsgCrypt.php');
  408. $crypt = new \WXBizMsgCrypt($this->project['token'], $this->project['key'], $this->project['appid']);
  409. $format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%s]]></Encrypt></xml>";
  410. $xml = sprintf($format, $encrypt);
  411. $result = '';
  412. $code = $crypt->decryptMsg($sign, $timestamp, $nonce, $xml, $result);
  413. if ($code == 0) {
  414. libxml_disable_entity_loader(true);
  415. $result = (array) simplexml_load_string($result, 'SimpleXMLElement', LIBXML_NOCDATA);
  416. }
  417. return $result;
  418. }
  419. /**
  420. * 获取nonce
  421. *
  422. * @return mixed
  423. */
  424. public function nonce()
  425. {
  426. return substr(md5(microtime()), rand(10, 15));
  427. }
  428. /**
  429. * 获取signature
  430. *
  431. * @return mixed
  432. */
  433. public function signature($ticket, $url, $timestamp, $noncestr)
  434. {
  435. /*
  436. $info = array();
  437. $info['jsapi_ticket'] = $ticket;
  438. $info['url'] = $url;
  439. $info['timestamp'] = $timestamp;
  440. $info['noncestr'] = $noncestr;
  441. ksort($info);
  442. */
  443. $signature_string = "jsapi_ticket=$ticket&noncestr=$noncestr&timestamp=$timestamp&url=$url";
  444. //$signature_string = substr(http_build_query($info), 0, -1);
  445. return sha1($signature_string);
  446. }
  447. /**
  448. * 获取sign签名数据包
  449. *
  450. * @return mixed
  451. */
  452. public function sign($url)
  453. {
  454. $ticket = $this->ticket();
  455. if (!$url) {
  456. $url = Dever::url();
  457. } else {
  458. $url = urldecode($url);
  459. }
  460. $timestamp = time();
  461. $noncestr = $this->nonce();
  462. $signature = $this->signature($ticket, $url, $timestamp, $noncestr);
  463. $sign = array();
  464. $sign['appId'] = $this->project['appid'];
  465. $sign['nonceStr'] = $noncestr;
  466. $sign['timestamp'] = $timestamp;
  467. $sign['url'] = $url;
  468. $sign['signature'] = $signature;
  469. return $sign;
  470. }
  471. }