WxOpenController.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. <?php
  2. namespace www\controllers;
  3. use common\services\xhMerchantExtendService;
  4. use Yii;
  5. use common\services\xhApplyOrderService;
  6. use common\services\xhWxMenuService;
  7. use common\services\xhMerchantService;
  8. use common\services\xhInviteService;
  9. use common\components\util;
  10. use common\components\configDict;
  11. use common\services\xhWxOpenService;
  12. use common\components\stringUtil;
  13. use common\components\wxUtil;
  14. use common\services\xhSetMealService;
  15. use yii\helpers\Json;
  16. use common\models\xhWxOpen;
  17. use linslin\yii2\curl;
  18. /**
  19. * 微信开放平台相关
  20. */
  21. class WxOpenController extends PublicController
  22. {
  23. public $withoutLogin = ['callback-create-first-merchant'];
  24. //开放平台开始授权 shish 2020.1.16
  25. public function actionBeginAuth()
  26. {
  27. $id = 1;
  28. $open = xhWxOpenService::getById($id);
  29. $pre = wxUtil::getPreAuthCode($open);
  30. $appId = $open['appId'];
  31. $oData = [];
  32. $oData['preAuthCodeTime'] = date("Y-m-d H:i:s");
  33. //设置预授码过期,让下个用户可以获取新的预授码
  34. xhWxOpenService::updateById($id, $oData);
  35. $url = Yii::$app->params['wHost'] . '/wx-open/callback';
  36. $merchantId = $open['merchantId'];
  37. //如果平台没有对应的商家,先去创建第一个商家并做关联
  38. if (empty($merchantId)) {
  39. $url = Yii::$app->params['wHost'] . '/wx-open/callback-create-first-merchant';
  40. }
  41. echo "<a href='https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid={$appId}&pre_auth_code={$pre}&redirect_uri={$url}'>授权</a>";
  42. }
  43. public function actionCheckMerchantName()
  44. {
  45. $get = Yii::$app->request->get();
  46. $merchantName = isset($get['merchantName']) ? $get['merchantName'] : '';
  47. $m = xhMerchantService::getByMerchantName($merchantName);
  48. if (!empty($m)) {
  49. util::fail('公众号名称已经使用');
  50. }
  51. util::ok();
  52. }
  53. /**
  54. * 下载微信里的图片到服务器
  55. */
  56. public function actionDownloadWxImg()
  57. {
  58. $get = Yii::$app->request->get();
  59. $mediaId = isset($get['mediaId']) ? $get['mediaId'] : '';
  60. $imgList = wxUtil::downloadmediaIdImg($this->merchant, $mediaId);
  61. if (!empty($imgList)) {
  62. util::success($imgList);
  63. }
  64. util::fail();
  65. }
  66. /**
  67. * 创建第一个商家
  68. */
  69. public function actionCallbackCreateFirstMerchant()
  70. {
  71. $get = Yii::$app->request->get();
  72. if (isset($get['auth_code']) == false) {
  73. util::stop('公众号授权回调未成功');
  74. }
  75. $code = $get['auth_code'];
  76. //使用授权码换取公众号的接口调用凭据和授权信息
  77. $authorize = wxUtil::getAuthorizer($code);
  78. if (isset($authorize['authorization_info']) == false) {
  79. util::stop('未换取公众号的接口调用凭据和授权信息');
  80. }
  81. $info = $authorize['authorization_info'];
  82. $authorizeAppId = $info['authorizer_appid'];
  83. $authorize_access_token = $info['authorizer_access_token'];
  84. $expires_in = $info['expires_in'];//7200
  85. $authorize_refresh_token = $info['authorizer_refresh_token'];
  86. //获取授权方的公众号帐号基本信息
  87. $authorizeDetailInfo = wxUtil::getAuthorizerInfo($authorizeAppId);
  88. if (isset($authorizeDetailInfo['authorizer_info']) == false) {
  89. util::stop('没有获取到公众号帐号基本信息');
  90. }
  91. $authorize_info = $authorizeDetailInfo['authorizer_info'];
  92. $nick_name = $authorize_info['nick_name'];
  93. $head_img = $authorize_info['head_img'];
  94. $service_type_info = $authorize_info['service_type_info'];
  95. if ($service_type_info['id'] != 2) {
  96. util::stop('公众号不是服务号');
  97. }
  98. $verify_type_info = $authorize_info['verify_type_info'];
  99. if ($verify_type_info['id'] != 0) {
  100. util::stop('公众号还没有认证哦');
  101. }
  102. $user_name = $authorize_info['user_name'];
  103. $alias = $authorize_info['alias'];
  104. $qrCodeUrl = $authorize_info['qrcode_url'];
  105. $business_info = $authorize_info['business_info'];
  106. $open_pay = $business_info['open_pay'];
  107. $merchant = xhMerchantService::getByAppId($authorizeAppId);
  108. $wxAccessTokenTime = date("Y-m-d H:i:s", (time() + $expires_in - 100));//安全起见,将过期时间设置得比微信里还短100秒
  109. if (!empty($merchant)) {
  110. util::stop('此公众号已经授权过了');
  111. }
  112. //引导生成商家
  113. $date = date("Y-m-d H:i:s");
  114. $trainDemo = configDict::getConfig('trainDemo');
  115. //$logo = xhMerchantService::logoSave($head_img, $authorizeAppId);
  116. $logo = '';
  117. $appData['logo'] = $logo;
  118. //保存公众号二维码
  119. //$wxQrCodeUrl = xhMerchantService::qrCodeSave($qrCodeUrl, $authorizeAppId);
  120. $wxQrCodeUrl = '';
  121. $appData['wxQrcodeUrl'] = $wxQrCodeUrl;
  122. $appData['wxAppId'] = $authorizeAppId;
  123. $appData['wxUserName'] = $user_name;
  124. $appData['wxAliasName'] = $alias;
  125. $appData['wxAccessToken'] = $authorize_access_token;
  126. $appData['wxAccessTokenTime'] = $wxAccessTokenTime;
  127. $appData['wxRefreshToken'] = $authorize_refresh_token;
  128. $appData['accountStyle'] = 0;//认证服务号
  129. $appData['status'] = 0;//待审核
  130. $appData['createTime'] = $date;
  131. $appData['updateTime'] = $date;
  132. $appData['shopLat'] = (string)0;
  133. $appData['shopLong'] = (string)0;
  134. $appData['shopPrecision'] = (string)0;
  135. $appData['account'] = $trainDemo['platform']['account'];
  136. $appData['adminId'] = 0;
  137. $appData['wxToken'] = stringUtil::buildWxToken(0);
  138. $appData['shopPhotoList'] = '';
  139. $appData['merchantName'] = $nick_name;
  140. $appData['shopProvince'] = '福建';
  141. $appData['shopCity'] = '厦门';
  142. $appData['shopDist'] = '思明区';
  143. $appData['alipayAccount'] = 'shishaohua8879@sina.com';
  144. $appData['alipayAccountName'] = '石少华';
  145. $appData['agentLevel'] = 1;//默认设置为代理商
  146. $merchant = xhMerchantService::applyCreateMerchant($appData);
  147. $wxOpenId = configDict::getConfig('openId');
  148. $merchantId = $merchant['id'];
  149. xhWxOpenService::updateById($wxOpenId, ['merchantId' => $merchantId]);
  150. xhWxMenuService::applyInit($merchant);//初始化微信菜单
  151. echo 'ok';
  152. }
  153. public function actionCallback()
  154. {
  155. $get = Yii::$app->request->get();
  156. if (isset($get['auth_code']) == false) {
  157. util::stop('公众号授权回调未成功');
  158. }
  159. $code = $get['auth_code'];
  160. //使用授权码换取公众号的接口调用凭据和授权信息
  161. $authorize = wxUtil::getAuthorizer($code);
  162. if (isset($authorize['authorization_info']) == false) {
  163. util::stop('未换取公众号的接口调用凭据和授权信息');
  164. }
  165. $info = $authorize['authorization_info'];
  166. $authorizeAppId = $info['authorizer_appid'];
  167. $authorize_access_token = $info['authorizer_access_token'];
  168. $expires_in = $info['expires_in'];//7200
  169. $authorize_refresh_token = $info['authorizer_refresh_token'];
  170. //获取授权方的基本信息
  171. $authorizeDetailInfo = wxUtil::getAuthorizerInfo($authorizeAppId);
  172. if (isset($authorizeDetailInfo['authorizer_info']) == false) {
  173. util::stop('没有获取到公众号帐号基本信息');
  174. }
  175. $authorize_info = $authorizeDetailInfo['authorizer_info'];
  176. $nick_name = $authorize_info['nick_name'];
  177. $head_img = $authorize_info['head_img'];
  178. $service_type_info = $authorize_info['service_type_info'];
  179. if (isset($authorize_info['MiniProgramInfo']) == false || empty($authorize_info['MiniProgramInfo'])) {
  180. if ($service_type_info['id'] != 2) {
  181. util::stop('公众号不是服务号,appId:' . $authorizeAppId . ' refresh:' . $authorize_refresh_token);
  182. }
  183. }
  184. $verify_type_info = $authorize_info['verify_type_info'];
  185. if ($verify_type_info['id'] != 0) {
  186. util::stop('公众号还没有认证哦');
  187. }
  188. $user_name = $authorize_info['user_name'];
  189. $alias = $authorize_info['alias'];
  190. $qrCodeUrl = $authorize_info['qrcode_url'];
  191. $business_info = $authorize_info['business_info'];
  192. $open_pay = $business_info['open_pay'];
  193. $accessTokenTime = date("Y-m-d H:i:s", (time() + $expires_in - 100));//安全起见,将过期时间设置得比微信里还短100秒
  194. //小程序
  195. if (isset($authorize_info['MiniProgramInfo']) && !empty($authorize_info['MiniProgramInfo'])) {
  196. $merchant = xhMerchantService::getByCondition(['miniAppId' => $authorizeAppId]);
  197. if (empty($merchant)) {
  198. Yii::info('没有小程序信息 appId:' . $authorizeAppId);
  199. util::stop('没有小程序信息 appId:' . $authorizeAppId);
  200. }
  201. $merchantId = $merchant['id'];
  202. xhMerchantExtendService::updateByMerchantId($merchantId, ['miniAccessToken' => $authorize_access_token, 'miniAccessTokenTime' => $accessTokenTime, 'miniRefreshToken' => $authorize_refresh_token]);
  203. Yii::info('小程序信息更新成功:' . json_encode($authorize_info));
  204. util::stop("小程序信息更新成功");
  205. } else {
  206. $merchant = xhMerchantService::getByAppId($authorizeAppId);
  207. Yii::info('appId:' . $authorizeAppId);
  208. $set = xhSetMealService::getRandOne();
  209. if (empty($set)) {
  210. util::stop('没有套餐信息');
  211. }
  212. if (empty($merchant)) {
  213. util::stop('这个商家没有生成过基本信息。appid:' . $authorizeAppId);
  214. }
  215. if (empty($merchant)) {
  216. echo '新建商家能力暂时关闭';
  217. Yii::$app->end();
  218. //没有生成商家,引导进去设置
  219. $session = Yii::$app->session;
  220. $session['wxAppId'] = $authorizeAppId;
  221. $session['wxUserName'] = $user_name;
  222. $session['wxAliasName'] = $alias;
  223. $session['wxAccessToken'] = $authorize_access_token;
  224. $session['wxAccessTokenTime'] = $accessTokenTime;
  225. $session['wxRefreshToken'] = $authorize_refresh_token;
  226. $session['logo'] = $head_img;
  227. $session['wxQrcodeUrl'] = $qrCodeUrl;
  228. $session['allowGenerateMerchant'] = 'ok';//经过授权流程,允许允许生成商家
  229. $trainDemo = configDict::getConfig('trainDemo');
  230. $demoName = $trainDemo['merchant']['name'];//培训演示的公众号
  231. return $this->renderPartial('callback', ['merchantName' => $nick_name, 'set' => $set, 'demoName' => $demoName]);
  232. }
  233. $cData = [];
  234. $cData['wxAccessToken'] = $authorize_access_token;
  235. $cData['wxAccessTokenTime'] = $accessTokenTime;
  236. $cData['wxRefreshToken'] = $authorize_refresh_token;
  237. //审核通过
  238. $cData['status'] = 1;
  239. $merchantId = $merchant['id'];
  240. xhMerchantService::updateById($merchantId, $cData);
  241. }
  242. echo $authorizeAppId . ' ';
  243. exit('ok');
  244. $price = $set['price'];
  245. $now = time();
  246. $apply = xhApplyOrderService::getByMerchantId($merchantId);
  247. if (empty($apply)) {
  248. return $this->renderPartial('hint', ['msg' => '没有申请记录']);
  249. }
  250. $orderId = $apply['id'];
  251. $price = $apply['actPrice'];
  252. $openMerchant = xhWxOpenService::getMerchant();
  253. $openMerchantAccount = $openMerchant['id'];
  254. $account = $merchant['id'];
  255. //将新生成的商家account加密传到后台绑定管理员,密钥有效期5分钟
  256. $newAccount = urlencode(stringUtil::authcode($account, 'ENCODE', 300));
  257. if ($apply['payStatus'] == 1) {
  258. if (empty($merchant['adminId'])) {
  259. $this->redirect(Yii::$app->params['adminUrl'] . '/admin/generate?account=' . $openMerchantAccount . '&newAccount=' . $newAccount);
  260. util::end();
  261. }
  262. return $this->renderPartial('hint', ['msg' => '恭喜!您已申请成功。']);
  263. }
  264. if ($price > 0) {
  265. $this->redirect(Yii::$app->params['openUrl'] . '/pay/apply?orderId=' . $apply['id']);
  266. util::end();
  267. } else {
  268. $inviteCode = $order['inviteCode'];
  269. $now = time();
  270. if (!empty($inviteCode)) {
  271. $invite = xhInviteService::getByCode($inviteCode);
  272. if (empty($invite)) {
  273. return $this->renderPartial('hint', ['msg' => '邀请码不存在']);
  274. }
  275. if ($invite['takeStatus'] == 1) {//邀请码未使用,并且没有过期
  276. return $this->renderPartial('hint', ['msg' => '邀请码已经使用,请联系客服']);
  277. }
  278. $inviteDeadline = $invite['deadline'];
  279. if ($now > $inviteDeadline) {
  280. return $this->renderPartial('hint', ['msg' => '邀请码已经过期,请联系客服']);
  281. }
  282. xhInviteService::updateByCode($inviteCode, ['takeStatus' => 1, 'inviteUseTo' => 0, 'targetId' => $orderId, 'invitedMerchantId' => $merchantId]);
  283. }
  284. $updateData = ['inviteCodeStatus' => 1, 'payStatus' => 1, 'payWay' => 0, 'invitedMerchantId' => $merchantId];
  285. xhApplyOrderService::updateById($orderId, $updateData);
  286. $this->redirect(Yii::$app->params['adminUrl'] . '/admin/generate?account=' . $openMerchantAccount . '&newAccount=' . $newAccount);
  287. util::end();
  288. }
  289. }
  290. public function actionResult()
  291. {
  292. $get = Yii::$app->request->get();
  293. $id = isset($get['id']) ? $get['id'] : 0;
  294. $merchant = xhMerchantService::getById($id);
  295. $status = configDict::getConfig('merchantStatusName');
  296. $orMechantId = configDict::getConfig('merchantId');
  297. $originalMerchant = xhMerchantService::getById($orMechantId);
  298. return $this->renderPartial('result', ['originalMerchant' => $originalMerchant, 'merchant' => $merchant, 'status' => $status]);
  299. }
  300. /**
  301. * 商家申请入驻
  302. */
  303. public function actionAddMerchant()
  304. {
  305. $post = Yii::$app->request->post();
  306. $session = Yii::$app->session;
  307. if (isset($session['allowGenerateMerchant']) == false) {
  308. //util::fail('没有经过授权的操作');
  309. }
  310. unset($post['_csrf']);
  311. if (isset($session['wxAppId']) == false || empty($session['wxAppId'])) {
  312. util::fail('公众号appId不存在');
  313. }
  314. $wxAppId = $session['wxAppId'];
  315. if (isset($session['logo'])) {
  316. $logo = xhMerchantService::logoSave($session['logo'], $wxAppId);
  317. $post['logo'] = $logo;
  318. }
  319. if (isset($session['wxQrcodeUrl'])) {
  320. $wxQrCodeUrl = xhMerchantService::qrCodeSave($session['wxQrcodeUrl'], $wxAppId);
  321. $post['wxQrcodeUrl'] = $wxQrCodeUrl;
  322. }
  323. $date = date("Y-m-d H:i:s");
  324. $inviteCode = isset($post['inviteCode']) ? $post['inviteCode'] : '';
  325. $accountStyle = configDict::getConfig('accountStyle');
  326. $merchantStatus = configDict::getConfig('merchantStatus');
  327. $serviceAccount = $accountStyle['serviceAccount'];//认证服务号
  328. $checking = $merchantStatus['checking'];//审核中
  329. $merchantName = !empty($post['merchantName']) ? $post['merchantName'] : '';
  330. $exists = xhMerchantService::getByMerchantName($merchantName);
  331. if (!empty($exists)) {
  332. util::fail('花店名称已经存在了');
  333. }
  334. $post['wxAppId'] = $wxAppId;
  335. $post['wxUserName'] = $session['wxUserName'];
  336. $post['wxAliasName'] = $session['wxAliasName'];
  337. $post['wxAccessToken'] = $session['wxAccessToken'];
  338. $post['wxAccessTokenTime'] = $session['wxAccessTokenTime'];
  339. $post['wxRefreshToken'] = $session['wxRefreshToken'];
  340. $post['accountStyle'] = $serviceAccount;//认证服务号
  341. $post['status'] = $checking;//待审
  342. $post['createTime'] = $date;
  343. $post['updateTime'] = $date;
  344. $post['shopLat'] = isset($post['shopLat']) ? (string)$post['shopLat'] : (string)0;
  345. $post['shopLong'] = isset($post['shopLong']) ? (string)$post['shopLong'] : (string)0;
  346. $post['shopPrecision'] = isset($post['shopPrecision']) ? (string)$post['shopPrecision'] : (string)0;
  347. $account = stringUtil::buildOrderNo(0);
  348. $trainDemo = configDict::getConfig('trainDemo');
  349. $demoName = $trainDemo['merchant']['name'];//培训演示的公众号
  350. if (isset($post['merchantName']) && $post['merchantName'] == $demoName) {
  351. $account = $trainDemo['merchant']['account'];
  352. }
  353. $post['account'] = $account;
  354. $post['adminId'] = 0;
  355. $post['wxToken'] = stringUtil::buildWxToken(0);
  356. $shopPhotoListString = json_encode(["outdoor" => $post['shopImg'], 'indoor' => $post['shopImg2']]);//将门店照片组合成json
  357. $post['shopPhotoList'] = $shopPhotoListString;
  358. $merchant = xhMerchantService::applyCreateMerchant($post);
  359. $id = $merchant['id'];
  360. $account = $merchant['id'];
  361. unset($session['allowGenerateMerchant']);
  362. xhWxMenuService::applyInit($merchant);
  363. $set = xhSetMealService::getRandOne();
  364. $price = $set['price'];
  365. $actPrice = $price;
  366. $mainMerchantId = 0;
  367. $now = time();
  368. $orderDeadline = 0;
  369. if (!empty($inviteCode)) {
  370. $invite = xhInviteService::getByCode($inviteCode);
  371. if (empty($invite)) {
  372. util::fail('邀请码不存在');
  373. }
  374. if ($invite['takeStatus'] == 1) {//邀请码未使用,并且没有过期
  375. util::fail('邀请码已经使用');
  376. }
  377. $inviteDeadline = $invite['deadline'];
  378. if ($now > $inviteDeadline) {
  379. util::fail('邀请码已经过期');
  380. }
  381. $mainMerchantId = isset($invite['merchantId']) ? $invite['merchantId'] : 0;
  382. $actPrice = stringUtil::calcSub($set['price'], $invite['save']);//扣除邀请码里的钱
  383. }
  384. $toPay = $actPrice <= 0 ? 'no' : 'yes';//是否需要付款
  385. $inviteCodeStatus = $actPrice <= 0 ? 1 : 0;//邀请码是否已使用
  386. $payStatus = $actPrice <= 0 ? 1 : 0;//付款是否成功
  387. $createTime = date("Y-m-d H:i:s");
  388. $orderId = 'A' . stringUtil::buildOrderNo($id);
  389. $orderData = ['id' => $orderId, 'userId' => $this->userId, 'applyName' => $merchantName, 'email' => '',
  390. 'createTime' => $createTime, 'accountId' => 0, 'inviteCode' => $inviteCode, 'merchantId' => $mainMerchantId, 'invitedMerchantId' => $id,
  391. 'prePrice' => $price, 'actPrice' => $actPrice, 'deadline' => $orderDeadline, 'inviteCodeStatus' => (int)$inviteCodeStatus, 'payStatus' => $payStatus,
  392. ];
  393. xhApplyOrderService::add($orderData);//保存订单信息
  394. if ($actPrice <= 0 && !empty($inviteCode)) {
  395. xhInviteService::updateByCode($inviteCode, ['targetId' => $orderId, 'takeStatus' => 1, 'invitedMerchantId' => $id, 'inviteUseTo' => 0]);
  396. }
  397. $openMerchant = xhWxOpenService::getMerchant();
  398. $openMerchantAccount = $openMerchant['id'];
  399. $newAccount = urlencode(stringUtil::authcode($account, 'ENCODE', 300));
  400. util::success(['account' => $openMerchantAccount, 'newAccount' => $newAccount, 'toPay' => $toPay, 'orderId' => $orderId, 'actPrice' => $actPrice]);
  401. }
  402. public function actionCheckInviteCode()
  403. {
  404. $get = Yii::$app->request->get();
  405. $code = isset($get['code']) ? $get['code'] : '';
  406. $invite = xhInviteService::getByCode($code);
  407. if (empty($invite)) {
  408. util::fail('邀请码错误');
  409. }
  410. $now = time();
  411. if ($now > $invite['deadline']) {
  412. util::fail('邀请码已经失效');
  413. }
  414. if (!empty($invite['takeStatus'])) {
  415. util::fail('邀请码已经使用');
  416. }
  417. util::success($invite);
  418. }
  419. public function actionSelect()
  420. {
  421. $isWx = util::isWx();
  422. if ($isWx == false) {
  423. return $this->renderPartial('notWeixin');
  424. }
  425. return $this->renderPartial('select');
  426. }
  427. public function actionApi()
  428. {
  429. $openData = file_get_contents('php://input');
  430. if (isset ($openData) == false || empty($openData)) {
  431. util::stop('has no post data');
  432. }
  433. $weixinSecret = Yii::getAlias("@vendor/weixinSecret");
  434. require_once($weixinSecret . '/wxBizMsgCrypt.php');
  435. $get = Yii::$app->request->get();
  436. $encryptMsg = $openData;
  437. $openId = configDict::getConfig('openId');
  438. $open = xhWxOpenService::getById($openId);
  439. $encodingAesKey = $open['aesKey'];
  440. $token = $open['token'];
  441. $appId = $open['appId'];
  442. $signature = isset($get['signature']) ? $get['signature'] : '';
  443. $timestamp = isset($get['timestamp']) ? $get['timestamp'] : '';
  444. $nonce = isset($get['nonce']) ? $get['nonce'] : '';
  445. $encrypt_type = isset($get['encrypt_type']) ? $get['encrypt_type'] : '';
  446. $msg_signature = isset($get['msg_signature']) ? $get['msg_signature'] : '';
  447. $xml_tree = new \DOMDocument();
  448. $xml_tree->loadXML($encryptMsg);
  449. $array_e = $xml_tree->getElementsByTagName('Encrypt');
  450. $encrypt = $array_e->item(0)->nodeValue;
  451. $format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%s]]></Encrypt></xml>";
  452. $from_xml = sprintf($format, $encrypt);
  453. $formString = '1:' . $token . ' 2:' . $encodingAesKey . ' 3:' . $appId . ' 4:' . $msg_signature . ' 5:' . $timestamp . ' 6:' . $nonce . ' 7:' . $from_xml;
  454. Yii::warning("formString:" . $formString);
  455. //第三方收到公众号平台发送的消息
  456. $pc = new \WXBizMsgCrypt($token, $encodingAesKey, $appId);
  457. $msg = '';//解密后的消息
  458. $errCode = $pc->decryptMsg($msg_signature, $timestamp, $nonce, $from_xml, $msg);
  459. if ($errCode != 0) {
  460. Yii::warning("解密未成功,错误代码:" . $errCode);
  461. Yii::$app->end();
  462. }
  463. $postObj = simplexml_load_string($msg, 'SimpleXMLElement', LIBXML_NOCDATA);
  464. $infoType = $postObj->InfoType;
  465. switch ($infoType) {
  466. //推送 componentVerifyTicket
  467. case 'component_verify_ticket':
  468. $componentVerifyTicket = $postObj->ComponentVerifyTicket;
  469. if (!empty($componentVerifyTicket)) {
  470. $oData = [];
  471. $oData['verifyTicket'] = (string)$componentVerifyTicket;
  472. $oData['verifyTicketTime'] = date("Y-m-d H:i:s", $timestamp + 600);//每10分钟(600秒)推一次
  473. xhWxOpenService::updateById($openId, $oData);
  474. Yii::warning("component_verify_ticket:" . (string)$componentVerifyTicket);
  475. util::stop('success');
  476. }
  477. break;
  478. //取消授权通知
  479. case 'unauthorized':
  480. $AppId = $postObj->AppId;
  481. $authorizeAppid = $postObj->AuthorizerAppid;
  482. $merchant = xhMerchantService::getByAppId($authorizeAppid);
  483. if (!empty($merchant)) {
  484. $merchantId = $merchant['id'];
  485. xhMerchantService::updateById($merchantId, ['status' => 5]);//自主冻结
  486. }
  487. break;
  488. //授权成功通知
  489. case 'authorized':
  490. $AppId = $postObj->AppId;//第三方平台appid
  491. $CreateTime = $postObj->CreateTime;//公众号
  492. $authorizeAppid = $postObj->AuthorizerAppid;//授权码,可用于换取公众号的接口调用凭据,详细见上面的说明
  493. $AuthorizationCode = $postObj->AuthorizationCode;
  494. $AuthorizationCodeExpiredTime = $postObj->AuthorizationCodeExpiredTime;//授权码过期时间
  495. break;
  496. //授权更新通知
  497. case 'updateauthorized':
  498. $AppId = $postObj->AppId;
  499. $CreateTime = $postObj->CreateTime;
  500. $authorizeAppid = $postObj->AuthorizerAppid;
  501. $AuthorizationCode = $postObj->AuthorizationCode;
  502. $AuthorizationCodeExpiredTime = $postObj->AuthorizationCodeExpiredTime;
  503. $authorize = wxUtil::getAuthorizer($AuthorizationCode);
  504. if (isset($authorize['authorization_info']) == false) {
  505. $msg = '授权回调获取到auth_code,但未换取公众号的接口调用凭据和授权信息!!';
  506. Yii::warning($msg, __METHOD__);
  507. Yii::$app->end();
  508. }
  509. $info = $authorize['authorization_info'];
  510. $authorizeAppId = $info['authorizer_appid'];
  511. $authorize_access_token = $info['authorizer_access_token'];
  512. $expires_in = $info['expires_in'];//7200
  513. $authorize_refresh_token = $info['authorizer_refresh_token'];
  514. $merchant = xhMerchantService::getByAppId($authorizeAppId);
  515. if (empty($merchant)) {
  516. return false;
  517. }
  518. $merchantId = $merchant['id'];
  519. $wxData = [];
  520. $wxData['wxAccessToken'] = $authorize_access_token;
  521. $wxData['wxRefreshToken'] = $authorize_refresh_token;
  522. $wxData['wxAccessTokenTime'] = date("Y-m-d H:i:s", (time() + $expires_in - 100));
  523. $wxData['status'] = 1;
  524. xhMerchantService::updateById($merchantId, $wxData);
  525. break;
  526. default:
  527. }
  528. Yii::warning("---wx open data end--- \n");
  529. }
  530. }