WxOpenController.php 18 KB

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