WxOpenController.php 16 KB

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