WxOpenController.php 23 KB

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