WxOpenController.php 23 KB

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