weixin.platform.class.php 12 KB

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