WxOpenController.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  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}&auth_type={$authType}&redirect_uri={$url}'>授权</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. if (empty($merchant)) {
  128. util::stop('这个商家没有生成过基本信息。appid:' . $authorizeAppId);
  129. }
  130. if (empty($merchant)) {
  131. //引导生成商家
  132. $date = date("Y-m-d H:i:s");
  133. $trainDemo = configDict::getConfig('trainDemo');
  134. //$logo = xhMerchantService::logoSave($head_img, $authorizeAppId);
  135. $logo = '';
  136. $appData['logo'] = $logo;
  137. //保存公众号二维码
  138. //$wxQrCodeUrl = xhMerchantService::qrCodeSave($qrCodeUrl, $authorizeAppId);
  139. $wxQrCodeUrl = '';
  140. $appData['wxQrcodeUrl'] = $wxQrCodeUrl;
  141. $appData['wxAppId'] = $authorizeAppId;
  142. $appData['wxUserName'] = $user_name;
  143. $appData['wxAliasName'] = $alias;
  144. $appData['wxAccessToken'] = $authorize_access_token;
  145. $appData['wxAccessTokenTime'] = $wxAccessTokenTime;
  146. $appData['wxRefreshToken'] = $authorize_refresh_token;
  147. $appData['accountStyle'] = 0;//认证服务号
  148. $appData['status'] = 0;//待审核
  149. $appData['createTime'] = $date;
  150. $appData['updateTime'] = $date;
  151. $appData['shopLat'] = (string)0;
  152. $appData['shopLong'] = (string)0;
  153. $appData['shopPrecision'] = (string)0;
  154. $appData['account'] = $trainDemo['platform']['account'];
  155. $appData['adminId'] = 0;
  156. $appData['wxToken'] = stringUtil::buildWxToken(0);
  157. $appData['shopPhotoList'] = '';
  158. $appData['merchantName'] = $nick_name;
  159. $appData['shopProvince'] = '福建';
  160. $appData['shopCity'] = '厦门';
  161. $appData['shopDist'] = '思明区';
  162. $appData['alipayAccount'] = 'shish@zhhinc.com';
  163. $appData['alipayAccountName'] = '石少华';
  164. $appData['agentLevel'] = 1;//默认设置为代理商
  165. $merchant = xhMerchantService::applyCreateMerchant($appData);
  166. $merchantId = $merchant['id'];
  167. $wxOpenId = configDict::getConfig('openId');
  168. $open = xhWxOpenService::getById($wxOpenId);
  169. $platform = 0;
  170. if (isset($open['merchantId']) && empty($open['merchantId'])) {
  171. xhWxOpenService::updateById($wxOpenId, ['merchantId' => $merchantId]);
  172. $platform = 1;
  173. }
  174. $data = ['merchantId' => $merchantId, 'platform' => $platform];
  175. $producer = Yii::$app->rabbitmq->getProducer('openShopInitProducer');
  176. $msg = serialize($data);
  177. $producer->publish($msg, 'openShopInitExchange', 'openShopInitRoute');
  178. } else {
  179. $cData = [];
  180. $cData['wxAccessToken'] = $authorize_access_token;
  181. $cData['wxAccessTokenTime'] = $accessTokenTime;
  182. $cData['wxRefreshToken'] = $authorize_refresh_token;
  183. //审核通过
  184. $cData['status'] = 1;
  185. $merchantId = $merchant['id'];
  186. xhMerchantService::updateById($merchantId, $cData);
  187. }
  188. echo 'ok';
  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. //自主冻结
  386. xhMerchantService::updateById($merchantId, ['status' => 5]);
  387. }
  388. break;
  389. //授权成功通知
  390. case 'authorized':
  391. $AppId = $postObj->AppId;//第三方平台appid
  392. $CreateTime = $postObj->CreateTime;//公众号
  393. $authorizeAppid = $postObj->AuthorizerAppid;//授权码,可用于换取公众号的接口调用凭据,详细见上面的说明
  394. $AuthorizationCode = $postObj->AuthorizationCode;
  395. $AuthorizationCodeExpiredTime = $postObj->AuthorizationCodeExpiredTime;//授权码过期时间
  396. break;
  397. //授权更新通知
  398. case 'updateauthorized':
  399. $AppId = $postObj->AppId;
  400. $CreateTime = $postObj->CreateTime;
  401. $authorizeAppid = $postObj->AuthorizerAppid;
  402. $AuthorizationCode = $postObj->AuthorizationCode;
  403. $AuthorizationCodeExpiredTime = $postObj->AuthorizationCodeExpiredTime;
  404. $authorize = wxUtil::getAuthorizer($AuthorizationCode);
  405. if (isset($authorize['authorization_info']) == false) {
  406. $msg = '授权回调获取到auth_code,但未换取公众号的接口调用凭据和授权信息!!';
  407. Yii::warning($msg, __METHOD__);
  408. Yii::$app->end();
  409. }
  410. $info = $authorize['authorization_info'];
  411. $authorizeAppId = $info['authorizer_appid'];
  412. $authorize_access_token = $info['authorizer_access_token'];
  413. $expires_in = $info['expires_in'];//7200
  414. $authorize_refresh_token = $info['authorizer_refresh_token'];
  415. $merchant = xhMerchantService::getByAppId($authorizeAppId);
  416. if (empty($merchant)) {
  417. return false;
  418. }
  419. $merchantId = $merchant['id'];
  420. $wxData = [];
  421. $wxData['wxAccessToken'] = $authorize_access_token;
  422. $wxData['wxRefreshToken'] = $authorize_refresh_token;
  423. $wxData['wxAccessTokenTime'] = date("Y-m-d H:i:s", (time() + $expires_in - 100));
  424. $wxData['status'] = 1;
  425. xhMerchantService::updateById($merchantId, $wxData);
  426. break;
  427. default:
  428. }
  429. Yii::warning("---wx open data end--- \n");
  430. }
  431. }