WxOpenController.php 23 KB

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