Wechat.php 11 KB

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