weixin.platform.class.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. <?php
  2. /**
  3. * [WeEngine System] Copyright (c) 2014 WE7.CC
  4. * WeEngine is NOT a free software, it under the license terms, visited http://www.we7.cc/ for more details.
  5. */
  6. defined('IN_IA') or exit('Access Denied');
  7. define('ACCOUNT_PLATFORM_API_ACCESSTOKEN', 'https://api.weixin.qq.com/cgi-bin/component/api_component_token');
  8. define('ACCOUNT_PLATFORM_API_PREAUTHCODE', 'https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token=');
  9. define('ACCOUNT_PLATFORM_API_LOGIN', 'https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=%s&pre_auth_code=%s&redirect_uri=%s&auth_type=%s');
  10. define('ACCOUNT_PLATFORM_API_QUERY_AUTH_INFO', 'https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token=');
  11. define('ACCOUNT_PLATFORM_API_ACCOUNT_INFO', 'https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_info?component_access_token=');
  12. define('ACCOUNT_PLATFORM_API_REFRESH_AUTH_ACCESSTOKEN', 'https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token=');
  13. define('ACCOUNT_PLATFORM_API_OAUTH_CODE', 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&component_appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_base&state=%s#wechat_redirect');
  14. define('ACCOUNT_PLATFORM_API_OAUTH_USERINFO', 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_userinfo&state=%s&component_appid=%s#wechat_redirect');
  15. define('ACCOUNT_PLATFORM_API_OAUTH_INFO', 'https://api.weixin.qq.com/sns/oauth2/component/access_token?appid=%s&component_appid=%s&code=%s&grant_type=authorization_code&component_access_token=');
  16. define('ACCOUNT_PLATFORM_API_LOGIN_ACCOUNT', 1);
  17. define('ACCOUNT_PLATFORM_API_LOGIN_WXAPP', 2);
  18. load()->classs('weixin.account');
  19. load()->func('communication');
  20. class WeixinPlatform extends WeixinAccount {
  21. public $appid;
  22. protected $appsecret;
  23. public $token;
  24. public $encodingaeskey;
  25. protected $refreshtoken;
  26. protected $tablename = 'account_wechats';
  27. protected $menuFrame = 'account';
  28. protected $type = ACCOUNT_TYPE_OFFCIAL_AUTH;
  29. protected $typeName = '公众号';
  30. protected $typeSign = ACCOUNT_TYPE_SIGN;
  31. public function __construct($uniaccount = array()) {
  32. $setting = setting_load('platform');
  33. $this->appid = !empty($setting['platform']['appid']) ? $setting['platform']['appid'] : '';
  34. $this->appsecret = !empty($setting['platform']['appsecret']) ? $setting['platform']['appsecret'] : '';
  35. $this->token = !empty($setting['platform']['token']) ? $setting['platform']['token'] : '';
  36. $this->encodingaeskey = !empty($setting['platform']['encodingaeskey']) ? $setting['platform']['encodingaeskey'] : '';
  37. parent::__construct($uniaccount);
  38. }
  39. protected function getAccountInfo($uniacid) {
  40. if ('wx570bc396a51b8ff8' == $this->account['key']) {
  41. $this->account['key'] = $this->appid;
  42. $this->openPlatformTestCase();
  43. }
  44. $account = table('account_wechats')->getAccount($uniacid);
  45. $account['encrypt_key'] = $this->appid;
  46. return $account;
  47. }
  48. public function fetchSameAccountByAppid($appid) {
  49. return pdo_get($this->tablename, array('key' => $appid));
  50. }
  51. public function getComponentAccesstoken() {
  52. $accesstoken = cache_load(cache_system_key('account_component_assesstoken'));
  53. if (empty($accesstoken) || empty($accesstoken['value'])) {
  54. $ticket = empty($GLOBALS['_W']['setting']['account_ticket']) ? '' : $GLOBALS['_W']['setting']['account_ticket'];
  55. if (empty($ticket)) {
  56. return error(1, '缺少接入平台关键数据,等待微信开放平台推送数据,请十分钟后再试或是检查“授权事件接收URL”是否写错(index.php?c=account&amp;a=auth&amp;do=ticket地址中的&amp;符号容易被替换成&amp;amp;)');
  57. }
  58. $data = array(
  59. 'component_appid' => $this->appid,
  60. 'component_appsecret' => $this->appsecret,
  61. 'component_verify_ticket' => $ticket,
  62. );
  63. $response = $this->request(ACCOUNT_PLATFORM_API_ACCESSTOKEN, $data);
  64. if (is_error($response)) {
  65. return $response;
  66. }
  67. $accesstoken = array(
  68. 'value' => $response['component_access_token'],
  69. );
  70. $record_expire = intval($response['expires_in']) - 200;
  71. cache_write(cache_system_key('account_component_assesstoken'), $accesstoken, $record_expire);
  72. }
  73. return $accesstoken['value'];
  74. }
  75. public function getPreauthCode() {
  76. $component_accesstoken = $this->getComponentAccesstoken();
  77. if (is_error($component_accesstoken)) {
  78. return $component_accesstoken;
  79. }
  80. $data = array(
  81. 'component_appid' => $this->appid,
  82. );
  83. $response = $this->request(ACCOUNT_PLATFORM_API_PREAUTHCODE . $component_accesstoken, $data);
  84. if (is_error($response)) {
  85. return $response;
  86. }
  87. return $response['pre_auth_code'];
  88. }
  89. public function getAuthInfo($code) {
  90. $component_accesstoken = $this->getComponentAccesstoken();
  91. if (is_error($component_accesstoken)) {
  92. return $component_accesstoken;
  93. }
  94. $post = array(
  95. 'component_appid' => $this->appid,
  96. 'authorization_code' => $code,
  97. );
  98. $response = $this->request(ACCOUNT_PLATFORM_API_QUERY_AUTH_INFO . $component_accesstoken, $post);
  99. if (is_error($response)) {
  100. return $response;
  101. }
  102. $this->setAuthRefreshToken($response['authorization_info']['authorizer_refresh_token']);
  103. return $response;
  104. }
  105. public function getAuthorizerInfo($appid = '') {
  106. $component_accesstoken = $this->getComponentAccesstoken();
  107. if (is_error($component_accesstoken)) {
  108. return $component_accesstoken;
  109. }
  110. $appid = !empty($appid) ? $appid : $this->account['key'];
  111. $post = array(
  112. 'component_appid' => $this->appid,
  113. 'authorizer_appid' => $appid,
  114. );
  115. return $this->request(ACCOUNT_PLATFORM_API_ACCOUNT_INFO . $component_accesstoken, $post);
  116. }
  117. public function getAuthorizerList() {
  118. $token = $this->getComponentAccesstoken();
  119. if (is_error($token)) {
  120. return $token;
  121. }
  122. $data = array(
  123. 'component_appid' => $this->appid,
  124. 'offset' => 0,
  125. 'count' => 500
  126. );
  127. $url = "https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_list?component_access_token={$token}";
  128. return $this->request($url, $data);
  129. }
  130. public function getAccessToken() {
  131. global $_W;
  132. $cachekey = cache_system_key('account_auth_accesstoken', array('key' => $this->account['key']));
  133. $auth_accesstoken = cache_load($cachekey);
  134. if (!empty($auth_accesstoken) && !empty($auth_accesstoken['value'])) {
  135. return $auth_accesstoken['value'];
  136. }
  137. if (!empty($this->account['link'])) {
  138. load()->library('sdk-module');
  139. $link_config = iunserializer($this->account['link_config']);
  140. try {
  141. $account_type = in_array($this->account['type'], array(ACCOUNT_TYPE_APP_NORMAL, ACCOUNT_TYPE_APP_AUTH)) ? 2 : 1;
  142. $api = new \W7\Sdk\Module\Api($_W['setting']['site']['key'], $_W['setting']['site']['token'], $link_config['app_id'], $account_type, CLOUD_V3API_DOMAIN_PRE);
  143. $token = $api->app()->getAccessToken()->toArray();
  144. $token = array(
  145. 'authorizer_access_token' => $token['access_token'],
  146. 'expires_in' => $token['expires_in']
  147. );
  148. } catch (Exception $e) {
  149. return error('-1', $e->getMessage());
  150. }
  151. } else {
  152. $component_accesstoken = $this->getComponentAccesstoken();
  153. if (is_error($component_accesstoken)) {
  154. return $component_accesstoken;
  155. }
  156. $this->refreshtoken = $this->getAuthRefreshToken();
  157. $data = array(
  158. 'component_appid' => $this->appid,
  159. 'authorizer_appid' => $this->account['key'],
  160. 'authorizer_refresh_token' => $this->refreshtoken,
  161. );
  162. $token = $this->request(ACCOUNT_PLATFORM_API_REFRESH_AUTH_ACCESSTOKEN . $component_accesstoken, $data);
  163. if (is_error($token)) {
  164. return $token;
  165. }
  166. if ($token['authorizer_refresh_token'] != $this->refreshtoken) {
  167. $this->setAuthRefreshToken($token['authorizer_refresh_token']);
  168. }
  169. }
  170. $auth_accesstoken = array(
  171. 'value' => $token['authorizer_access_token'],
  172. );
  173. $record_expire = intval($token['expires_in']) - 200;
  174. cache_write($cachekey, $auth_accesstoken, $record_expire);
  175. return $auth_accesstoken['value'];
  176. }
  177. public function fetch_token() {
  178. return $this->getAccessToken();
  179. }
  180. public function getAuthLoginUrl($auth_type = ACCOUNT_PLATFORM_API_LOGIN_ACCOUNT, $if_console = false) {
  181. $allowed_type = array(ACCOUNT_PLATFORM_API_LOGIN_ACCOUNT, ACCOUNT_PLATFORM_API_LOGIN_WXAPP);
  182. $auth_type = in_array($auth_type, $allowed_type) ? $auth_type : ACCOUNT_PLATFORM_API_LOGIN_ACCOUNT;
  183. $preauthcode = $this->getPreauthCode();
  184. if (is_error($preauthcode)) {
  185. $authurl = "javascript:alert('{$preauthcode['message']}');";
  186. } else {
  187. $redirect = $GLOBALS['_W']['siteroot'] . 'web/index.php?c=account&a=auth&do=forward' . ($if_console ? '&if_console=1' : '');
  188. if (ACCOUNT_PLATFORM_API_LOGIN_WXAPP == $auth_type) {
  189. $redirect = $GLOBALS['_W']['siteroot'] . 'web/index.php?c=wxapp&a=auth&do=forward' . ($if_console ? '&if_console=1' : '');
  190. }
  191. $authurl = sprintf(
  192. ACCOUNT_PLATFORM_API_LOGIN,
  193. $this->appid,
  194. $preauthcode,
  195. urlencode($redirect),
  196. $auth_type
  197. );
  198. }
  199. return $authurl;
  200. }
  201. public function getOauthCodeUrl($callback, $state = '') {
  202. return sprintf(ACCOUNT_PLATFORM_API_OAUTH_CODE, $this->account['key'], $this->appid, $callback, $state);
  203. }
  204. public function getOauthUserInfoUrl($callback, $state = '', $extra = array()) {
  205. return sprintf(ACCOUNT_PLATFORM_API_OAUTH_USERINFO, $this->account['key'], $callback, $state, $this->appid);
  206. }
  207. public function getOauthInfo($code = '') {
  208. $component_accesstoken = $this->getComponentAccesstoken();
  209. if (is_error($component_accesstoken)) {
  210. return $component_accesstoken;
  211. }
  212. $apiurl = sprintf(ACCOUNT_PLATFORM_API_OAUTH_INFO . $component_accesstoken, $this->account['key'], $this->appid, $code);
  213. $response = $this->request($apiurl);
  214. if (is_error($response)) {
  215. return $response;
  216. }
  217. cache_write('account_oauth_refreshtoken' . $this->account['key'], $response['refresh_token']);
  218. return $response;
  219. }
  220. public function getJsApiTicket() {
  221. $cachekey = cache_system_key('jsticket', array('uniacid' => $this->account['uniacid']));
  222. $js_ticket = cache_load($cachekey);
  223. if (empty($js_ticket) || empty($js_ticket['value'])) {
  224. $access_token = $this->getAccessToken();
  225. if (is_error($access_token)) {
  226. return $access_token;
  227. }
  228. $apiurl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={$access_token}&type=jsapi";
  229. $response = $this->request($apiurl);
  230. if (is_error($response)) {
  231. return $response;
  232. }
  233. $js_ticket = array(
  234. 'value' => $response['ticket'],
  235. );
  236. $record_expire = $response['expires_in'] - 200;
  237. cache_write($cachekey, $js_ticket, $record_expire);
  238. }
  239. $this->account['jsapi_ticket'] = $js_ticket;
  240. return $js_ticket['value'];
  241. }
  242. public function getJssdkConfig($url = '') {
  243. global $_W, $urls;
  244. $jsapiTicket = $this->getJsApiTicket();
  245. if (is_error($jsapiTicket)) {
  246. $jsapiTicket = $jsapiTicket['message'];
  247. }
  248. $nonceStr = random(16);
  249. $timestamp = TIMESTAMP;
  250. $url = empty($url) ? ($urls['scheme'] . '://' . $urls['host'] . $_SERVER['REQUEST_URI']) : $url;
  251. $string1 = "jsapi_ticket={$jsapiTicket}&noncestr={$nonceStr}&timestamp={$timestamp}&url={$url}";
  252. $signature = sha1($string1);
  253. $config = array(
  254. 'appId' => $this->account['key'],
  255. 'nonceStr' => $nonceStr,
  256. 'timestamp' => "$timestamp",
  257. 'signature' => $signature,
  258. );
  259. if (DEVELOPMENT) {
  260. $config['url'] = $url;
  261. $config['string1'] = $string1;
  262. $config['name'] = $this->account['name'];
  263. }
  264. return $config;
  265. }
  266. public function openPlatformTestCase() {
  267. global $_GPC;
  268. $post = file_get_contents('php://input');
  269. WeUtility::logging('platform-test-message', $post);
  270. $encode_message = $this->xmlExtract($post);
  271. $message = aes_decode($encode_message['encrypt'], $this->encodingaeskey);
  272. $message = $this->parse($message);
  273. $response = array(
  274. 'ToUserName' => $message['from'],
  275. 'FromUserName' => $message['to'],
  276. 'CreateTime' => TIMESTAMP,
  277. 'MsgId' => TIMESTAMP,
  278. 'MsgType' => 'text',
  279. );
  280. if ('TESTCOMPONENT_MSG_TYPE_TEXT' == $message['content']) {
  281. $response['Content'] = 'TESTCOMPONENT_MSG_TYPE_TEXT_callback';
  282. }
  283. if ('event' == $message['msgtype']) {
  284. $response['Content'] = $message['event'] . 'from_callback';
  285. }
  286. if (strexists($message['content'], 'QUERY_AUTH_CODE')) {
  287. list($sufixx, $authcode) = explode(':', $message['content']);
  288. $auth_info = $this->getAuthInfo($authcode);
  289. WeUtility::logging('platform-test-send-message', var_export($auth_info, true));
  290. $url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=' . $auth_info['authorization_info']['authorizer_access_token'];
  291. $data = array(
  292. 'touser' => $message['from'],
  293. 'msgtype' => 'text',
  294. 'text' => array('content' => $authcode . '_from_api'),
  295. );
  296. $response = ihttp_request($url, urldecode(json_encode($data)));
  297. exit('');
  298. }
  299. $xml = array(
  300. 'Nonce' => safe_gpc_string($_GPC['nonce']),
  301. 'TimeStamp' => safe_gpc_string($_GPC['timestamp']),
  302. 'Encrypt' => aes_encode(array2xml($response), $this->encodingaeskey, $this->appid),
  303. );
  304. $signature = array($xml['Encrypt'], $this->token, safe_gpc_string($_GPC['timestamp']), safe_gpc_string($_GPC['nonce']));
  305. sort($signature, SORT_STRING);
  306. $signature = implode($signature);
  307. $xml['MsgSignature'] = sha1($signature);
  308. exit(array2xml($xml));
  309. }
  310. public function openGet($appid = '') {
  311. $token = $this->getAccessToken();
  312. if (is_error($token)) {
  313. return $token;
  314. }
  315. $data = array(
  316. 'appid' => !empty($appid) ? $appid : $this->account['key'],
  317. );
  318. $url = "https://api.weixin.qq.com/cgi-bin/open/get?access_token={$token}";
  319. return $this->request($url, $data);
  320. }
  321. public function openBind($appid = '') {
  322. $token = $this->getAccessToken();
  323. if (is_error($token)) {
  324. return $token;
  325. }
  326. $data = array(
  327. 'appid' => !empty($appid) ? $appid : $this->account['key'],
  328. 'open_appid' => $this->appid,
  329. );
  330. $url = "https://api.weixin.qq.com/cgi-bin/open/bind?access_token={$token}";
  331. return $this->request($url, $data);
  332. }
  333. protected function request($url, $post = array()) {
  334. if (!empty($post)) {
  335. $response = ihttp_request($url, json_encode($post, JSON_UNESCAPED_UNICODE));
  336. } else {
  337. $response = ihttp_request($url);
  338. }
  339. $response = json_decode($response['content'], true);
  340. if (empty($response) || !empty($response['errcode'])) {
  341. return error($response['errcode'], $this->errorCode($response['errcode'], $response['errmsg']));
  342. }
  343. return $response;
  344. }
  345. protected function getAuthRefreshToken() {
  346. $auth_refresh_token = cache_load(cache_system_key('account_auth_refreshtoken', array('uniacid' => $this->account['uniacid'])));
  347. if (empty($auth_refresh_token)) {
  348. $auth_refresh_token = $this->account['auth_refresh_token'];
  349. cache_write(cache_system_key('account_auth_refreshtoken', array('uniacid' => $this->account['uniacid'])), $auth_refresh_token);
  350. }
  351. return $auth_refresh_token;
  352. }
  353. protected function setAuthRefreshToken($token) {
  354. $tablename = 'account_wechats';
  355. pdo_update($tablename, array('auth_refresh_token' => $token), array('uniacid' => $this->account['uniacid']));
  356. cache_write(cache_system_key('account_auth_refreshtoken', array('uniacid' => $this->account['uniacid'])), $token);
  357. }
  358. public function result($errno, $message = '', $data = '') {
  359. exit(json_encode(array(
  360. 'errno' => $errno,
  361. 'message' => $message,
  362. 'data' => $data,
  363. )));
  364. }
  365. }