WxOpenController.php 18 KB

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