WxOpenController.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. <?php
  2. namespace www\controllers;
  3. use common\services\xhMerchantExtendService;
  4. use common\services\xhTMessageService;
  5. use Yii;
  6. use common\services\xhApplyOrderService;
  7. use common\services\xhWxMenuService;
  8. use common\services\xhMerchantService;
  9. use common\services\xhInviteService;
  10. use common\components\util;
  11. use common\components\configDict;
  12. use common\services\xhWxOpenService;
  13. use common\components\stringUtil;
  14. use common\components\wxUtil;
  15. use common\services\xhSetMealService;
  16. use yii\helpers\Json;
  17. use common\models\xhWxOpen;
  18. use linslin\yii2\curl;
  19. /**
  20. * 微信开放平台相关
  21. */
  22. class WxOpenController extends PublicController
  23. {
  24. public $withoutLogin = ['callback-create-first-merchant'];
  25. //开放平台开始授权 shish 2020.1.16
  26. public function actionBeginAuth()
  27. {
  28. $id = 1;
  29. $merchantId = Yii::$app->request->get('id', 0);
  30. $open = xhWxOpenService::getById($id);
  31. $pre = wxUtil::getPreAuthCode($open);
  32. $appId = $open['appId'];
  33. $oData = [];
  34. $oData['preAuthCodeTime'] = date("Y-m-d H:i:s");
  35. //设置预授码过期,让下个用户可以获取新的预授码
  36. xhWxOpenService::updateById($id, $oData);
  37. $url = Yii::$app->params['wHost'] . '/wx-open-callback/' . $merchantId;
  38. $authType = Yii::$app->request->get('authType', 1);
  39. echo "<a href='https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid={$appId}&pre_auth_code={$pre}&redirect_uri={$url}&auth_type={$authType}'>授权</a>";
  40. }
  41. public function actionCheckMerchantName()
  42. {
  43. $get = Yii::$app->request->get();
  44. $merchantName = isset($get['merchantName']) ? $get['merchantName'] : '';
  45. $m = xhMerchantService::getByMerchantName($merchantName);
  46. if (!empty($m)) {
  47. util::fail('公众号名称已经使用');
  48. }
  49. util::ok();
  50. }
  51. /**
  52. * 下载微信里的图片到服务器
  53. */
  54. public function actionDownloadWxImg()
  55. {
  56. $get = Yii::$app->request->get();
  57. $mediaId = isset($get['mediaId']) ? $get['mediaId'] : '';
  58. $imgList = wxUtil::downloadmediaIdImg($this->merchant, $mediaId);
  59. if (!empty($imgList)) {
  60. util::success($imgList);
  61. }
  62. util::fail();
  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 = wxUtil::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 = wxUtil::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. if (isset($authorize_info['MiniProgramInfo']) && !empty($authorize_info['MiniProgramInfo'])) {
  110. $merchant = xhMerchantService::getByCondition(['miniAppId' => $authorizeAppId]);
  111. if (empty($merchant)) {
  112. Yii::info('没有小程序信息 appId:' . $authorizeAppId);
  113. util::stop('没有小程序信息 appId:' . $authorizeAppId);
  114. }
  115. $merchantId = $merchant['id'];
  116. xhMerchantExtendService::updateByMerchantId($merchantId, ['miniAccessToken' => $authorize_access_token, 'miniAccessTokenTime' => $accessTokenTime, 'miniRefreshToken' => $authorize_refresh_token]);
  117. Yii::info('小程序信息更新成功:' . json_encode($authorize_info));
  118. util::stop("小程序信息更新成功");
  119. }
  120. $merchant = xhMerchantService::getByAppId($authorizeAppId);
  121. Yii::info('appId:' . $authorizeAppId);
  122. $set = xhSetMealService::getRandOne();
  123. if (empty($set)) {
  124. util::stop('没有套餐信息');
  125. }
  126. if (empty($merchant)) {
  127. util::stop('这个商家没有生成过基本信息。appid:' . $authorizeAppId);
  128. }
  129. if (empty($merchant)) {
  130. //引导生成商家
  131. $date = date("Y-m-d H:i:s");
  132. $trainDemo = configDict::getConfig('trainDemo');
  133. //$logo = xhMerchantService::logoSave($head_img, $authorizeAppId);
  134. $logo = '';
  135. $appData['logo'] = $logo;
  136. //保存公众号二维码
  137. //$wxQrCodeUrl = xhMerchantService::qrCodeSave($qrCodeUrl, $authorizeAppId);
  138. $wxQrCodeUrl = '';
  139. $appData['wxQrcodeUrl'] = $wxQrCodeUrl;
  140. $appData['wxAppId'] = $authorizeAppId;
  141. $appData['wxUserName'] = $user_name;
  142. $appData['wxAliasName'] = $alias;
  143. $appData['wxAccessToken'] = $authorize_access_token;
  144. $appData['wxAccessTokenTime'] = $wxAccessTokenTime;
  145. $appData['wxRefreshToken'] = $authorize_refresh_token;
  146. $appData['accountStyle'] = 0;//认证服务号
  147. $appData['status'] = 0;//待审核
  148. $appData['createTime'] = $date;
  149. $appData['updateTime'] = $date;
  150. $appData['shopLat'] = (string)0;
  151. $appData['shopLong'] = (string)0;
  152. $appData['shopPrecision'] = (string)0;
  153. $appData['account'] = $trainDemo['platform']['account'];
  154. $appData['adminId'] = 0;
  155. $appData['wxToken'] = stringUtil::buildWxToken(0);
  156. $appData['shopPhotoList'] = '';
  157. $appData['merchantName'] = $nick_name;
  158. $appData['shopProvince'] = '福建';
  159. $appData['shopCity'] = '厦门';
  160. $appData['shopDist'] = '思明区';
  161. $appData['alipayAccount'] = 'shish@zhhinc.com';
  162. $appData['alipayAccountName'] = '石少华';
  163. $appData['agentLevel'] = 1;//默认设置为代理商
  164. $merchant = xhMerchantService::applyCreateMerchant($appData);
  165. $merchantId = $merchant['id'];
  166. $wxOpenId = configDict::getConfig('openId');
  167. $open = xhWxOpenService::getById($wxOpenId);
  168. if (isset($open['merchantId']) && !empty($open['merchantId'])) {
  169. xhWxOpenService::updateById($wxOpenId, ['merchantId' => $merchantId]);
  170. }
  171. $data = ['merchantId' => $merchantId, 'platform' => 1];
  172. $producer = Yii::$app->rabbitmq->getProducer('openShopInitProducer');
  173. $msg = serialize($data);
  174. $producer->publish($msg, 'openShopInitExchange', 'openShopInitRoute');
  175. } else {
  176. $cData = [];
  177. $cData['wxAccessToken'] = $authorize_access_token;
  178. $cData['wxAccessTokenTime'] = $accessTokenTime;
  179. $cData['wxRefreshToken'] = $authorize_refresh_token;
  180. //审核通过
  181. $cData['status'] = 1;
  182. $merchantId = $merchant['id'];
  183. xhMerchantService::updateById($merchantId, $cData);
  184. }
  185. echo 'ok';
  186. }
  187. public function actionCallback()
  188. {
  189. }
  190. public function actionResult()
  191. {
  192. $get = Yii::$app->request->get();
  193. $id = isset($get['id']) ? $get['id'] : 0;
  194. $merchant = xhMerchantService::getById($id);
  195. $status = configDict::getConfig('merchantStatusName');
  196. $orMechantId = configDict::getConfig('merchantId');
  197. $originalMerchant = xhMerchantService::getById($orMechantId);
  198. return $this->renderPartial('result', ['originalMerchant' => $originalMerchant, 'merchant' => $merchant, 'status' => $status]);
  199. }
  200. /**
  201. * 商家申请入驻
  202. */
  203. public function actionAddMerchant()
  204. {
  205. $post = Yii::$app->request->post();
  206. $session = Yii::$app->session;
  207. if (isset($session['allowGenerateMerchant']) == false) {
  208. //util::fail('没有经过授权的操作');
  209. }
  210. unset($post['_csrf']);
  211. if (isset($session['wxAppId']) == false || empty($session['wxAppId'])) {
  212. util::fail('公众号appId不存在');
  213. }
  214. $wxAppId = $session['wxAppId'];
  215. if (isset($session['logo'])) {
  216. $logo = xhMerchantService::logoSave($session['logo'], $wxAppId);
  217. $post['logo'] = $logo;
  218. }
  219. if (isset($session['wxQrcodeUrl'])) {
  220. $wxQrCodeUrl = xhMerchantService::qrCodeSave($session['wxQrcodeUrl'], $wxAppId);
  221. $post['wxQrcodeUrl'] = $wxQrCodeUrl;
  222. }
  223. $date = date("Y-m-d H:i:s");
  224. $inviteCode = isset($post['inviteCode']) ? $post['inviteCode'] : '';
  225. $accountStyle = configDict::getConfig('accountStyle');
  226. $merchantStatus = configDict::getConfig('merchantStatus');
  227. $serviceAccount = $accountStyle['serviceAccount'];//认证服务号
  228. $checking = $merchantStatus['checking'];//审核中
  229. $merchantName = !empty($post['merchantName']) ? $post['merchantName'] : '';
  230. $exists = xhMerchantService::getByMerchantName($merchantName);
  231. if (!empty($exists)) {
  232. util::fail('花店名称已经存在了');
  233. }
  234. $post['wxAppId'] = $wxAppId;
  235. $post['wxUserName'] = $session['wxUserName'];
  236. $post['wxAliasName'] = $session['wxAliasName'];
  237. $post['wxAccessToken'] = $session['wxAccessToken'];
  238. $post['wxAccessTokenTime'] = $session['wxAccessTokenTime'];
  239. $post['wxRefreshToken'] = $session['wxRefreshToken'];
  240. $post['accountStyle'] = $serviceAccount;//认证服务号
  241. $post['status'] = $checking;//待审
  242. $post['createTime'] = $date;
  243. $post['updateTime'] = $date;
  244. $post['shopLat'] = isset($post['shopLat']) ? (string)$post['shopLat'] : (string)0;
  245. $post['shopLong'] = isset($post['shopLong']) ? (string)$post['shopLong'] : (string)0;
  246. $post['shopPrecision'] = isset($post['shopPrecision']) ? (string)$post['shopPrecision'] : (string)0;
  247. $account = stringUtil::buildOrderNo(0);
  248. $trainDemo = configDict::getConfig('trainDemo');
  249. $demoName = $trainDemo['merchant']['name'];//培训演示的公众号
  250. if (isset($post['merchantName']) && $post['merchantName'] == $demoName) {
  251. $account = $trainDemo['merchant']['account'];
  252. }
  253. $post['account'] = $account;
  254. $post['adminId'] = 0;
  255. $post['wxToken'] = stringUtil::buildWxToken(0);
  256. $shopPhotoListString = json_encode(["outdoor" => $post['shopImg'], 'indoor' => $post['shopImg2']]);//将门店照片组合成json
  257. $post['shopPhotoList'] = $shopPhotoListString;
  258. $merchant = xhMerchantService::applyCreateMerchant($post);
  259. $id = $merchant['id'];
  260. $account = $merchant['id'];
  261. unset($session['allowGenerateMerchant']);
  262. xhWxMenuService::applyInit($merchant);
  263. $set = xhSetMealService::getRandOne();
  264. $price = $set['price'];
  265. $actPrice = $price;
  266. $mainMerchantId = 0;
  267. $now = time();
  268. $orderDeadline = 0;
  269. if (!empty($inviteCode)) {
  270. $invite = xhInviteService::getByCode($inviteCode);
  271. if (empty($invite)) {
  272. util::fail('邀请码不存在');
  273. }
  274. if ($invite['takeStatus'] == 1) {//邀请码未使用,并且没有过期
  275. util::fail('邀请码已经使用');
  276. }
  277. $inviteDeadline = $invite['deadline'];
  278. if ($now > $inviteDeadline) {
  279. util::fail('邀请码已经过期');
  280. }
  281. $mainMerchantId = isset($invite['merchantId']) ? $invite['merchantId'] : 0;
  282. $actPrice = stringUtil::calcSub($set['price'], $invite['save']);//扣除邀请码里的钱
  283. }
  284. $toPay = $actPrice <= 0 ? 'no' : 'yes';//是否需要付款
  285. $inviteCodeStatus = $actPrice <= 0 ? 1 : 0;//邀请码是否已使用
  286. $payStatus = $actPrice <= 0 ? 1 : 0;//付款是否成功
  287. $createTime = date("Y-m-d H:i:s");
  288. $orderId = 'A' . stringUtil::buildOrderNo($id);
  289. $orderData = ['id' => $orderId, 'userId' => $this->userId, 'applyName' => $merchantName, 'email' => '',
  290. 'createTime' => $createTime, 'accountId' => 0, 'inviteCode' => $inviteCode, 'merchantId' => $mainMerchantId, 'invitedMerchantId' => $id,
  291. 'prePrice' => $price, 'actPrice' => $actPrice, 'deadline' => $orderDeadline, 'inviteCodeStatus' => (int)$inviteCodeStatus, 'payStatus' => $payStatus,
  292. ];
  293. xhApplyOrderService::add($orderData);//保存订单信息
  294. if ($actPrice <= 0 && !empty($inviteCode)) {
  295. xhInviteService::updateByCode($inviteCode, ['targetId' => $orderId, 'takeStatus' => 1, 'invitedMerchantId' => $id, 'inviteUseTo' => 0]);
  296. }
  297. $openMerchant = xhWxOpenService::getMerchant();
  298. $openMerchantAccount = $openMerchant['id'];
  299. $newAccount = urlencode(stringUtil::authcode($account, 'ENCODE', 300));
  300. util::success(['account' => $openMerchantAccount, 'newAccount' => $newAccount, 'toPay' => $toPay, 'orderId' => $orderId, 'actPrice' => $actPrice]);
  301. }
  302. public function actionCheckInviteCode()
  303. {
  304. $get = Yii::$app->request->get();
  305. $code = isset($get['code']) ? $get['code'] : '';
  306. $invite = xhInviteService::getByCode($code);
  307. if (empty($invite)) {
  308. util::fail('邀请码错误');
  309. }
  310. $now = time();
  311. if ($now > $invite['deadline']) {
  312. util::fail('邀请码已经失效');
  313. }
  314. if (!empty($invite['takeStatus'])) {
  315. util::fail('邀请码已经使用');
  316. }
  317. util::success($invite);
  318. }
  319. public function actionSelect()
  320. {
  321. $isWx = util::isWx();
  322. if ($isWx == false) {
  323. return $this->renderPartial('notWeixin');
  324. }
  325. return $this->renderPartial('select');
  326. }
  327. public function actionApi()
  328. {
  329. $openData = file_get_contents('php://input');
  330. if (isset ($openData) == false || empty($openData)) {
  331. util::stop('has no post data');
  332. }
  333. $weixinSecret = Yii::getAlias("@vendor/weixinSecret");
  334. require_once($weixinSecret . '/wxBizMsgCrypt.php');
  335. $get = Yii::$app->request->get();
  336. $encryptMsg = $openData;
  337. $openId = configDict::getConfig('openId');
  338. $open = xhWxOpenService::getById($openId);
  339. $encodingAesKey = $open['aesKey'];
  340. $token = $open['token'];
  341. $appId = $open['appId'];
  342. $signature = isset($get['signature']) ? $get['signature'] : '';
  343. $timestamp = isset($get['timestamp']) ? $get['timestamp'] : '';
  344. $nonce = isset($get['nonce']) ? $get['nonce'] : '';
  345. $encrypt_type = isset($get['encrypt_type']) ? $get['encrypt_type'] : '';
  346. $msg_signature = isset($get['msg_signature']) ? $get['msg_signature'] : '';
  347. $xml_tree = new \DOMDocument();
  348. $xml_tree->loadXML($encryptMsg);
  349. $array_e = $xml_tree->getElementsByTagName('Encrypt');
  350. $encrypt = $array_e->item(0)->nodeValue;
  351. $format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%s]]></Encrypt></xml>";
  352. $from_xml = sprintf($format, $encrypt);
  353. $formString = '1:' . $token . ' 2:' . $encodingAesKey . ' 3:' . $appId . ' 4:' . $msg_signature . ' 5:' . $timestamp . ' 6:' . $nonce . ' 7:' . $from_xml;
  354. Yii::warning("formString:" . $formString);
  355. //第三方收到公众号平台发送的消息
  356. $pc = new \WXBizMsgCrypt($token, $encodingAesKey, $appId);
  357. $msg = '';//解密后的消息
  358. $errCode = $pc->decryptMsg($msg_signature, $timestamp, $nonce, $from_xml, $msg);
  359. if ($errCode != 0) {
  360. Yii::warning("解密未成功,错误代码:" . $errCode);
  361. Yii::$app->end();
  362. }
  363. $postObj = simplexml_load_string($msg, 'SimpleXMLElement', LIBXML_NOCDATA);
  364. $infoType = $postObj->InfoType;
  365. switch ($infoType) {
  366. //推送 componentVerifyTicket
  367. case 'component_verify_ticket':
  368. $componentVerifyTicket = $postObj->ComponentVerifyTicket;
  369. if (!empty($componentVerifyTicket)) {
  370. $oData = [];
  371. $oData['verifyTicket'] = (string)$componentVerifyTicket;
  372. $oData['verifyTicketTime'] = date("Y-m-d H:i:s", $timestamp + 600);//每10分钟(600秒)推一次
  373. xhWxOpenService::updateById($openId, $oData);
  374. Yii::warning("component_verify_ticket:" . (string)$componentVerifyTicket);
  375. util::stop('success');
  376. }
  377. break;
  378. //取消授权通知
  379. case 'unauthorized':
  380. $AppId = $postObj->AppId;
  381. $authorizeAppid = $postObj->AuthorizerAppid;
  382. $merchant = xhMerchantService::getByAppId($authorizeAppid);
  383. if (!empty($merchant)) {
  384. $merchantId = $merchant['id'];
  385. xhMerchantService::updateById($merchantId, ['status' => 5]);//自主冻结
  386. //删除模板消息
  387. xhTMessageService::delTMessage($merchant);
  388. }
  389. break;
  390. //授权成功通知
  391. case 'authorized':
  392. $AppId = $postObj->AppId;//第三方平台appid
  393. $CreateTime = $postObj->CreateTime;//公众号
  394. $authorizeAppid = $postObj->AuthorizerAppid;//授权码,可用于换取公众号的接口调用凭据,详细见上面的说明
  395. $AuthorizationCode = $postObj->AuthorizationCode;
  396. $AuthorizationCodeExpiredTime = $postObj->AuthorizationCodeExpiredTime;//授权码过期时间
  397. break;
  398. //授权更新通知
  399. case 'updateauthorized':
  400. $AppId = $postObj->AppId;
  401. $CreateTime = $postObj->CreateTime;
  402. $authorizeAppid = $postObj->AuthorizerAppid;
  403. $AuthorizationCode = $postObj->AuthorizationCode;
  404. $AuthorizationCodeExpiredTime = $postObj->AuthorizationCodeExpiredTime;
  405. $authorize = wxUtil::getAuthorizer($AuthorizationCode);
  406. if (isset($authorize['authorization_info']) == false) {
  407. $msg = '授权回调获取到auth_code,但未换取公众号的接口调用凭据和授权信息!!';
  408. Yii::warning($msg, __METHOD__);
  409. Yii::$app->end();
  410. }
  411. $info = $authorize['authorization_info'];
  412. $authorizeAppId = $info['authorizer_appid'];
  413. $authorize_access_token = $info['authorizer_access_token'];
  414. $expires_in = $info['expires_in'];//7200
  415. $authorize_refresh_token = $info['authorizer_refresh_token'];
  416. $merchant = xhMerchantService::getByAppId($authorizeAppId);
  417. if (empty($merchant)) {
  418. return false;
  419. }
  420. $merchantId = $merchant['id'];
  421. $wxData = [];
  422. $wxData['wxAccessToken'] = $authorize_access_token;
  423. $wxData['wxRefreshToken'] = $authorize_refresh_token;
  424. $wxData['wxAccessTokenTime'] = date("Y-m-d H:i:s", (time() + $expires_in - 100));
  425. $wxData['status'] = 1;
  426. xhMerchantService::updateById($merchantId, $wxData);
  427. break;
  428. default:
  429. }
  430. Yii::warning("---wx open data end--- \n");
  431. }
  432. }