weixin.platform.class.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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); define('ACCOUNT_PLATFORM_API_LOGIN_WXAPP', 2); load()->classs('weixin.account');
  17. load()->func('communication');
  18. class WeixinPlatform extends WeixinAccount {
  19. public $appid;
  20. protected $appsecret;
  21. public $token;
  22. public $encodingaeskey;
  23. protected $refreshtoken;
  24. protected $tablename = 'account_wechats';
  25. protected $menuFrame = 'account';
  26. protected $type = ACCOUNT_TYPE_OFFCIAL_AUTH;
  27. protected $typeName = '公众号';
  28. protected $typeSign = ACCOUNT_TYPE_SIGN;
  29. public function __construct($uniaccount = array()) {
  30. $setting = setting_load('platform');
  31. $this->appid = $setting['platform']['appid'];
  32. $this->appsecret = $setting['platform']['appsecret'];
  33. $this->token = $setting['platform']['token'];
  34. $this->encodingaeskey = $setting['platform']['encodingaeskey'];
  35. parent::__construct($uniaccount);
  36. }
  37. protected function getAccountInfo($acid) {
  38. if ($this->account['key'] == 'wx570bc396a51b8ff8') {
  39. $this->account['key'] = $this->appid;
  40. $this->openPlatformTestCase();
  41. }
  42. $account_table = table('account');
  43. $account = $account_table->getWechatappAccount($acid);
  44. $account['encrypt_key'] = $this->appid;
  45. return $account;
  46. }
  47. public function fetchSameAccountByAppid($appid) {
  48. return pdo_get($this->tablename, array('key' => $appid));
  49. }
  50. function getComponentAccesstoken() {
  51. $accesstoken = cache_load(cache_system_key('account_component_assesstoken'));
  52. if (empty($accesstoken) || empty($accesstoken['value']) || $accesstoken['expire'] < TIMESTAMP) {
  53. $ticket = $GLOBALS['_W']['setting']['account_ticket'];
  54. if (empty($ticket)) {
  55. return error(1, '缺少接入平台关键数据,等待微信开放平台推送数据,请十分钟后再试或是检查“授权事件接收URL”是否写错(index.php?c=account&amp;a=auth&amp;do=ticket地址中的&amp;符号容易被替换成&amp;amp;)');
  56. }
  57. $data = array(
  58. 'component_appid' => $this->appid,
  59. 'component_appsecret' => $this->appsecret,
  60. 'component_verify_ticket' => $ticket,
  61. );
  62. $response = $this->request(ACCOUNT_PLATFORM_API_ACCESSTOKEN, $data);
  63. if (is_error($response)) {
  64. $errormsg = $this->errorCode($response['errno'], $response['message']);
  65. return error($response['errno'], $errormsg);
  66. }
  67. $accesstoken = array(
  68. 'value' => $response['component_access_token'],
  69. 'expire' => TIMESTAMP + intval($response['expires_in']),
  70. );
  71. cache_write(cache_system_key('account_component_assesstoken'), $accesstoken);
  72. }
  73. return $accesstoken['value'];
  74. }
  75. function getPreauthCode() {
  76. $preauthcode = cache_load(cache_system_key('account_preauthcode'));
  77. if (true || empty($preauthcode) || empty($preauthcode['value']) || $preauthcode['expire'] < TIMESTAMP) {
  78. $component_accesstoken = $this->getComponentAccesstoken();
  79. if (is_error($component_accesstoken)) {
  80. return $component_accesstoken;
  81. }
  82. $data = array(
  83. 'component_appid' => $this->appid
  84. );
  85. $response = $this->request(ACCOUNT_PLATFORM_API_PREAUTHCODE . $component_accesstoken, $data);
  86. if (is_error($response)) {
  87. return $response;
  88. }
  89. $preauthcode = array(
  90. 'value' => $response['pre_auth_code'],
  91. 'expire' => TIMESTAMP + intval($response['expires_in']),
  92. );
  93. cache_write(cache_system_key('account_preauthcode'), $preauthcode);
  94. }
  95. return $preauthcode['value'];
  96. }
  97. public function getAuthInfo($code) {
  98. $component_accesstoken = $this->getComponentAccesstoken();
  99. if (is_error($component_accesstoken)) {
  100. return $component_accesstoken;
  101. }
  102. $post = array(
  103. 'component_appid' => $this->appid,
  104. 'authorization_code' => $code,
  105. );
  106. $response = $this->request(ACCOUNT_PLATFORM_API_QUERY_AUTH_INFO . $component_accesstoken, $post);
  107. if (is_error($response)) {
  108. return $response;
  109. }
  110. $this->setAuthRefreshToken($response['authorization_info']['authorizer_refresh_token']);
  111. return $response;
  112. }
  113. public function getAuthorizerInfo($appid = '') {
  114. $component_accesstoken = $this->getComponentAccesstoken();
  115. if (is_error($component_accesstoken)) {
  116. return $component_accesstoken;
  117. }
  118. $appid = !empty($appid) ? $appid : $this->account['key'];
  119. $post = array(
  120. 'component_appid' => $this->appid,
  121. 'authorizer_appid' => $appid,
  122. );
  123. $response = $this->request(ACCOUNT_PLATFORM_API_ACCOUNT_INFO . $component_accesstoken, $post);
  124. if (is_error($response)) {
  125. return $response;
  126. }
  127. return $response;
  128. }
  129. public function getAccessToken() {
  130. $cachekey = cache_system_key('account_auth_accesstoken', array('key' => $this->account['key']));
  131. $auth_accesstoken = cache_load($cachekey);
  132. if (empty($auth_accesstoken) || empty($auth_accesstoken['value']) || $auth_accesstoken['expire'] < TIMESTAMP) {
  133. $component_accesstoken = $this->getComponentAccesstoken();
  134. if (is_error($component_accesstoken)) {
  135. return $component_accesstoken;
  136. }
  137. $this->refreshtoken = $this->getAuthRefreshToken();
  138. $data = array(
  139. 'component_appid' => $this->appid,
  140. 'authorizer_appid' => $this->account['key'],
  141. 'authorizer_refresh_token' => $this->refreshtoken,
  142. );
  143. $response = $this->request(ACCOUNT_PLATFORM_API_REFRESH_AUTH_ACCESSTOKEN . $component_accesstoken, $data);
  144. if (is_error($response)) {
  145. return $response;
  146. }
  147. if ($response['authorizer_refresh_token'] != $this->refreshtoken) {
  148. $this->setAuthRefreshToken($response['authorizer_refresh_token']);
  149. }
  150. $auth_accesstoken = array(
  151. 'value' => $response['authorizer_access_token'],
  152. 'expire' => TIMESTAMP + intval($response['expires_in']),
  153. );
  154. cache_write($cachekey, $auth_accesstoken);
  155. }
  156. return $auth_accesstoken['value'];
  157. }
  158. public function fetch_token() {
  159. return $this->getAccessToken();
  160. }
  161. public function getAuthLoginUrl() {
  162. $preauthcode = $this->getPreauthCode();
  163. if (is_error($preauthcode)) {
  164. $authurl = "javascript:alert('{$preauthcode['message']}');";
  165. } else {
  166. $authurl = sprintf(ACCOUNT_PLATFORM_API_LOGIN, $this->appid,
  167. $preauthcode, urlencode($GLOBALS['_W']['siteroot'] . 'index.php?c=account&a=auth&do=forward'), ACCOUNT_PLATFORM_API_LOGIN_ACCOUNT);
  168. }
  169. return $authurl;
  170. }
  171. public function getOauthCodeUrl($callback, $state = '') {
  172. return sprintf(ACCOUNT_PLATFORM_API_OAUTH_CODE, $this->account['key'], $this->appid, $callback, $state);
  173. }
  174. public function getOauthUserInfoUrl($callback, $state = '') {
  175. return sprintf(ACCOUNT_PLATFORM_API_OAUTH_USERINFO, $this->account['key'], $callback, $state, $this->appid);
  176. }
  177. public function getOauthInfo($code = '') {
  178. $component_accesstoken = $this->getComponentAccesstoken();
  179. if (is_error($component_accesstoken)) {
  180. return $component_accesstoken;
  181. }
  182. $apiurl = sprintf(ACCOUNT_PLATFORM_API_OAUTH_INFO . $component_accesstoken, $this->account['key'], $this->appid, $code);
  183. $response = $this->request($apiurl);
  184. if (is_error($response)) {
  185. return $response;
  186. }
  187. cache_write('account_oauth_refreshtoken'.$this->account['key'], $response['refresh_token']);
  188. return $response;
  189. }
  190. public function getJsApiTicket(){
  191. $cachekey = cache_system_key('jsticket', array('acid' => $this->account['acid']));
  192. $js_ticket = cache_load($cachekey);
  193. if (empty($js_ticket) || empty($js_ticket['value']) || $js_ticket['expire'] < TIMESTAMP) {
  194. $access_token = $this->getAccessToken();
  195. if(is_error($access_token)){
  196. return $access_token;
  197. }
  198. $apiurl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={$access_token}&type=jsapi";
  199. $response = $this->request($apiurl);
  200. $js_ticket = array(
  201. 'value' => $response['ticket'],
  202. 'expire' => TIMESTAMP + $response['expires_in'] - 200,
  203. );
  204. cache_write($cachekey, $js_ticket);
  205. }
  206. $this->account['jsapi_ticket'] = $js_ticket;
  207. return $js_ticket['value'];
  208. }
  209. public function getJssdkConfig($url = ''){
  210. global $_W;
  211. $jsapiTicket = $this->getJsApiTicket();
  212. if(is_error($jsapiTicket)){
  213. $jsapiTicket = $jsapiTicket['message'];
  214. }
  215. $nonceStr = random(16);
  216. $timestamp = TIMESTAMP;
  217. $url = empty($url) ? $_W['siteurl'] : $url;
  218. $string1 = "jsapi_ticket={$jsapiTicket}&noncestr={$nonceStr}&timestamp={$timestamp}&url={$url}";
  219. $signature = sha1($string1);
  220. $config = array(
  221. "appId" => $this->account['key'],
  222. "nonceStr" => $nonceStr,
  223. "timestamp" => "$timestamp",
  224. "signature" => $signature,
  225. );
  226. if(DEVELOPMENT) {
  227. $config['url'] = $url;
  228. $config['string1'] = $string1;
  229. $config['name'] = $this->account['name'];
  230. }
  231. return $config;
  232. }
  233. public function openPlatformTestCase() {
  234. global $_GPC;
  235. $post = file_get_contents('php://input');
  236. WeUtility::logging('platform-test-message', $post);
  237. $encode_message = $this->xmlExtract($post);
  238. $message = aes_decode($encode_message['encrypt'], $this->encodingaeskey);
  239. $message = $this->parse($message);
  240. $response = array(
  241. 'ToUserName' => $message['from'],
  242. 'FromUserName' => $message['to'],
  243. 'CreateTime' => TIMESTAMP,
  244. 'MsgId' => TIMESTAMP,
  245. 'MsgType' => 'text',
  246. );
  247. if ($message['content'] == 'TESTCOMPONENT_MSG_TYPE_TEXT') {
  248. $response['Content'] = 'TESTCOMPONENT_MSG_TYPE_TEXT_callback';
  249. }
  250. if ($message['msgtype'] == 'event') {
  251. $response['Content'] = $message['event'] . 'from_callback';
  252. }
  253. if (strexists($message['content'], 'QUERY_AUTH_CODE')) {
  254. list($sufixx, $authcode) = explode(':', $message['content']);
  255. $auth_info = $this->getAuthInfo($authcode);
  256. WeUtility::logging('platform-test-send-message', var_export($auth_info, true));
  257. $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=". $auth_info['authorization_info']['authorizer_access_token'];
  258. $data = array(
  259. 'touser' => $message['from'],
  260. 'msgtype' => 'text',
  261. 'text' => array('content' => $authcode.'_from_api'),
  262. );
  263. $response = ihttp_request($url, urldecode(json_encode($data)));
  264. exit('');
  265. }
  266. $xml = array(
  267. 'Nonce' => $_GPC['nonce'],
  268. 'TimeStamp' => $_GPC['timestamp'],
  269. 'Encrypt' => aes_encode(array2xml($response), $this->encodingaeskey, $this->appid),
  270. );
  271. $signature = array($xml['Encrypt'], $this->token, $_GPC['timestamp'], $_GPC['nonce']);
  272. sort($signature, SORT_STRING);
  273. $signature = implode($signature);
  274. $xml['MsgSignature'] = sha1($signature);
  275. exit(array2xml($xml));
  276. }
  277. protected function request($url, $post = array()) {
  278. $response = ihttp_request($url, json_encode($post));
  279. $response = json_decode($response['content'], true);
  280. if (empty($response) || !empty($response['errcode'])) {
  281. return error($response['errcode'], $this->errorCode($response['errcode'], $response['errmsg']));
  282. }
  283. return $response;
  284. }
  285. protected function getAuthRefreshToken() {
  286. $auth_refresh_token = cache_load(cache_system_key('account_auth_refreshtoken', array('uniacid' => $this->account['uniacid'])));
  287. if (empty($auth_refresh_token)) {
  288. $auth_refresh_token = $this->account['auth_refresh_token'];
  289. cache_write(cache_system_key('account_auth_refreshtoken', array('uniacid' => $this->account['uniacid'])), $auth_refresh_token);
  290. }
  291. return $auth_refresh_token;
  292. }
  293. protected function setAuthRefreshToken($token) {
  294. $tablename = 'account_wechats';
  295. pdo_update($tablename, array('auth_refresh_token' => $token), array('uniacid' => $this->account['uniacid']));
  296. cache_write(cache_system_key('account_auth_refreshtoken', array('uniacid' => $this->account['uniacid'])), $token);
  297. }
  298. public function result($errno, $message = '', $data = '') {
  299. exit(json_encode(array(
  300. 'errno' => $errno,
  301. 'message' => $message,
  302. 'data' => $data,
  303. )));
  304. }
  305. }