Wechat.php 12 KB

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