WxOpenController.php 18 KB

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