WxOpenController.php 24 KB

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