Wechat.php 12 KB

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