WxOpenController.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. <?php
  2. namespace saas\controllers;
  3. use biz\merchant\services\MerchantExtendService;
  4. use biz\merchant\services\MerchantService;
  5. use biz\weixin\services\MiniProgramService;
  6. use biz\weixin\services\WxBaseService;
  7. use biz\weixin\services\WxMiniBaseService;
  8. use common\components\util;
  9. use Yii;
  10. use common\components\wxUtil;
  11. use biz\ad\classes\AdClass;
  12. use biz\merchant\classes\MerchantExtendClass;
  13. use biz\weixin\classes\WxBaseClass;
  14. use biz\weixin\services\WxOpenService;
  15. use common\services\xhMerchantExtendService;
  16. use common\services\xhMerchantService;
  17. use common\services\xhInviteService;
  18. use common\components\configDict;
  19. use common\services\xhWxOpenService;
  20. class WxOpenController extends BaseController
  21. {
  22. public $withoutLogin = ['bind-open'];
  23. public function actionBindOpen()
  24. {
  25. $isOpen = Yii::$app->request->get('isOpen', 0);
  26. if ($isOpen == 1) {
  27. $merchant = WxOpenService::getWxInfo();
  28. } else {
  29. $merchantId = Yii::$app->request->get('merchantId', 0);
  30. $merchant = MerchantService::getMerchantById($merchantId);
  31. if (empty($merchant)) {
  32. util::fail('没有找到商家');
  33. }
  34. }
  35. $wxAppId = $merchant['wxAppId'];
  36. $miniAppId = $merchant['miniAppId'];
  37. $open_appid = $merchant['openAppId'];
  38. echo "<pre>";
  39. $id = Yii::$app->request->get('id', 0);
  40. //创建平台,并将公众号绑定到平台
  41. if ($id == 1) {
  42. wxUtil::createOpenAccount($wxAppId, $merchant);
  43. $return = wxUtil::getOpenAccount($wxAppId, $merchant);
  44. print_r($return);
  45. if ($return['errcode'] == 0) {
  46. $openAppId = $return['open_appid'];
  47. MerchantService::updateById($merchantId, ['openAppId' => $openAppId]);
  48. MerchantExtendService::updateByCondition(['merchantId' => $merchantId], ['openAppId' => $openAppId, 'openAppBind' => 1, 'wxAuth' => 1]);
  49. }
  50. }
  51. //将小程序绑定到平台
  52. if ($id == 2) {
  53. $openAppId = $merchant['openAppId'];
  54. $r = wxUtil::bindOpenAccount($miniAppId, $openAppId, $merchant, true);
  55. MerchantExtendService::updateByCondition(['merchantId' => $merchantId], ['openAppBind' => 3, 'miniAuth' => 1]);
  56. print_r($r);
  57. }
  58. //查询公众号 小程序的绑定情况
  59. if ($id == 3) {
  60. $return = wxUtil::getOpenAccount($wxAppId, $merchant);
  61. print_r($return);
  62. $return = wxUtil::getOpenAccount($miniAppId, $merchant, true);
  63. print_r($return);
  64. }
  65. //设置小程序服务器域名
  66. if ($id == 4) {
  67. wxUtil::setDomain($merchant);
  68. wxUtil::setWebViewDomain($merchant);
  69. }
  70. //为授权的小程序帐号上传小程序代码
  71. if ($id == 5) {
  72. $tId = $_GET['tId'];
  73. wxUtil::miniCommit($merchant, $tId);
  74. }
  75. //获取小程序体验码
  76. if ($id == 6) {
  77. wxUtil::getExperienceQrCode($merchant);
  78. }
  79. //获取授权小程序帐号已设置的类目
  80. if ($id == 7) {
  81. wxUtil::getMiniCategory($merchant);
  82. }
  83. //获取小程序的第三方提交代码的页面配置
  84. if ($id == 8) {
  85. wxUtil::getMiniPage($merchant);
  86. }
  87. //将第三方提交的代码包提交审核
  88. if ($id == 9) {
  89. wxUtil::miniSubmitAudit($merchant);
  90. }
  91. //查询最新一次提交的审核状态
  92. if ($id == 10) {
  93. wxUtil::miniGetLatestAuditStatus($merchant);
  94. }
  95. //发布已通过审核的小程序
  96. if ($id == 11) {
  97. $r = MiniProgramService::release($merchant);
  98. print_r($r);
  99. }
  100. //撤回审核
  101. if ($id == 12) {
  102. wxUtil::rollbackCheck($merchant);
  103. }
  104. //生成 申请会员页 的小程序码
  105. if ($id == 13) {
  106. wxUtil::generateMemberCode($merchant);
  107. }
  108. //解绑小程序和公众号绑定的平台
  109. if ($id == 14) {
  110. wxUtil::unbindAccount($merchant);
  111. wxUtil::unbindMiniProgram($merchant);
  112. }
  113. Yii::$app->end();
  114. $r = wxUtil::bindOpenAccount($miniAppId, $open_appid, $merchant, true);
  115. print_r($r);
  116. echo $miniAppId . ' ' . $open_appid . ' ';
  117. $return = wxUtil::getOpenAccount($wxAppId, $merchant);
  118. print_r($return);
  119. die;
  120. $return = wxUtil::createOpenAccount($wxAppId, $merchant);
  121. print_r($return);
  122. die;
  123. $r = wxUtil::bindOpenAccount($miniAppId, $open_appid, $merchant);
  124. print_r($r);
  125. echo $miniAppId . ' ' . $open_appid . ' ';
  126. $return = wxUtil::getOpenAccount($wxAppId, $merchant);
  127. print_r($return);
  128. $return = wxUtil::getOpenAccount($miniAppId, $merchant);
  129. print_r($return);
  130. die;
  131. if ($return['errcode'] == 0) {
  132. $open_appid = isset($return['open_appid']) ? $return['open_appid'] : '';
  133. } else {
  134. $return = wxUtil::createOpenAccount($wxAppId, $merchant);
  135. if ($return['errcode'] == 0) {
  136. $open_appid = isset($return['open_appid']) ? $return['open_appid'] : '';
  137. }
  138. }
  139. echo "<br />open_appid:" . $open_appid . "<br />";
  140. if (!empty($open_appid)) {
  141. xhMerchantService::updateById($merchantId, ['openAppId' => $open_appid]);
  142. MerchantExtendService::updateByCondition(['merchantId' => $merchantId], ['openAppId' => $open_appid, 'openAppBind' => 3, 'miniAuth' => 1]);
  143. $r = wxUtil::bindOpenAccount($miniAppId, $open_appid, $merchant);
  144. echo "绑定小程序结果:<br />";
  145. print_r($r);
  146. }
  147. echo "<br /><br />";
  148. $return = wxUtil::getOpenAccount($wxAppId, $merchant);
  149. echo "微信appId:{$wxAppId}<br />";
  150. print_r($return);
  151. $return = wxUtil::getOpenAccount($miniAppId, $merchant);
  152. echo "<br />小程序appId:{$miniAppId}<br />";
  153. print_r($return);
  154. }
  155. //开放平台开始授权 shish 2020.1.16
  156. public function actionBeginAuth()
  157. {
  158. $merchantId = Yii::$app->request->get('id', 0);
  159. $open = WxOpenService::getOpen();
  160. //1只显示公众号 2只显示小程序 3显示公众号和小程序
  161. $authType = Yii::$app->request->get('authType', 3);
  162. $pre = wxUtil::getPreAuthCode($open);
  163. $appId = $open['appId'];
  164. $oData = [];
  165. $oData['preAuthCodeTime'] = date("Y-m-d H:i:s");
  166. //设置预授码过期,让下个用户可以获取新的预授码
  167. xhWxOpenService::updateById(1, $oData);
  168. $url = Yii::$app->params['saasHost'] . '/wx-open-callback/' . $merchantId;
  169. 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>";
  170. }
  171. //平台没有绑定商家公众号时初始化一个商家 shish 2020.2.11
  172. public function actionAddMerchant()
  173. {
  174. AdClass::initAdd(12362);
  175. $return = MerchantService::initOpenMerchant();
  176. dd($return);
  177. }
  178. public function actionCheckMerchantName()
  179. {
  180. $get = Yii::$app->request->get();
  181. $merchantName = isset($get['merchantName']) ? $get['merchantName'] : '';
  182. $m = xhMerchantService::getByMerchantName($merchantName);
  183. if (!empty($m)) {
  184. util::fail('公众号名称已经使用');
  185. }
  186. util::complete();
  187. }
  188. /**
  189. * 下载微信里的图片到服务器
  190. */
  191. public function actionDownloadWxImg()
  192. {
  193. $get = Yii::$app->request->get();
  194. $mediaId = isset($get['mediaId']) ? $get['mediaId'] : '';
  195. $imgList = wxUtil::downloadmediaIdImg($this->merchant, $mediaId);
  196. if (!empty($imgList)) {
  197. util::success($imgList);
  198. }
  199. util::fail();
  200. }
  201. //创建平台使用的公众号
  202. public function actionCallback()
  203. {
  204. $get = Yii::$app->request->get();
  205. if (isset($get['auth_code']) == false) {
  206. util::stop('公众号授权回调未成功');
  207. }
  208. $id = isset($get['id']) ? $get['id'] : 0;
  209. $code = $get['auth_code'];
  210. //使用授权码换取公众号的接口调用凭据和授权信息
  211. $authorize = wxUtil::getAuthorizer($code);
  212. if (isset($authorize['authorization_info']) == false) {
  213. util::stop('未换取公众号的接口调用凭据和授权信息');
  214. }
  215. $info = $authorize['authorization_info'];
  216. $authorizeAppId = $info['authorizer_appid'];
  217. $authorize_access_token = $info['authorizer_access_token'];
  218. $expires_in = $info['expires_in'];//7200
  219. $authorize_refresh_token = $info['authorizer_refresh_token'];
  220. //获取授权方的公众号帐号基本信息
  221. $authorizeDetailInfo = wxUtil::getAuthorizerInfo($authorizeAppId);
  222. if (isset($authorizeDetailInfo['authorizer_info']) == false) {
  223. util::stop('没有获取到公众号帐号基本信息');
  224. }
  225. $authorize_info = $authorizeDetailInfo['authorizer_info'];
  226. //$nick_name = $authorize_info['nick_name'];
  227. $head_img = $authorize_info['head_img'];
  228. $service_type_info = $authorize_info['service_type_info'];
  229. if ($service_type_info['id'] != 2) {
  230. if (isset($authorize_info['MiniProgramInfo']) == false || empty($authorize_info['MiniProgramInfo'])) {
  231. util::stop('公众号不是服务号');
  232. }
  233. }
  234. $verify_type_info = $authorize_info['verify_type_info'];
  235. if ($verify_type_info['id'] != 0) {
  236. if (isset($authorize_info['MiniProgramInfo']) == false || empty($authorize_info['MiniProgramInfo'])) {
  237. util::stop('公众号还没有认证哦');
  238. }
  239. }
  240. $user_name = $authorize_info['user_name'];
  241. $alias = $authorize_info['alias'];
  242. $qrCodeUrl = $authorize_info['qrcode_url'];
  243. $accessTokenTime = date("Y-m-d H:i:s", (time() + $expires_in - 100));//安全起见,将过期时间设置得比微信里还短100秒
  244. //开放平台还没有关联公众号,先将开放平台关联公众号
  245. $open = WxOpenService::getOpen();
  246. if (isset($open['merchantId']) && empty($open['merchantId'])) {
  247. WxOpenService::updateById(1, ['merchantId' => $id]);
  248. }
  249. $extend = MerchantExtendClass::getByMerchantId($id);
  250. $open = WxOpenService::getOpen();
  251. $time = time();
  252. //小程序
  253. if (isset($authorize_info['MiniProgramInfo']) && !empty($authorize_info['MiniProgramInfo'])) {
  254. $miniData = [
  255. 'miniAppId' => $authorizeAppId,
  256. 'miniAuth' => 1,
  257. 'miniAccessToken' => $authorize_access_token,
  258. 'miniAccessTokenTime' => $accessTokenTime,
  259. 'miniRefreshToken' => $authorize_refresh_token,
  260. ];
  261. //开放平台没有小程序先绑定开放平台要用的小程序
  262. if (isset($open['wx_mini_base_id']) == false || empty($open['wx_mini_base_id'])) {
  263. $miniData['addTime'] = $time;
  264. //花卉宝
  265. $miniAppSecret = 'f1ae43c87080da21ac631609b0dbb147';
  266. if (getenv('YII_ENV') == 'dev') {
  267. //花美玲
  268. $miniAppSecret = '12f90039b1245ba6abf2e4184462fb30';
  269. }
  270. $miniData['miniAppSecret'] = $miniAppSecret;
  271. $wxMiniBaseRespond = WxMiniBaseService::add($miniData);
  272. $wxMiniBaseId = $wxMiniBaseRespond['id'];
  273. WxOpenService::updateOpen(['wx_mini_base_id' => $wxMiniBaseId]);
  274. util::stop('开放平台成功绑定小程序');
  275. }
  276. if (isset($extend['miniAppId']) && !empty($extend['miniAppId'])) {
  277. if ($extend['miniAppId'] != $authorizeAppId) {
  278. util::stop('授权的小程序与商家已绑定的小程序不一致');
  279. }
  280. } else {
  281. util::stop('数据库请先填写小程序 miniAppId miniAppSecret');
  282. }
  283. xhMerchantExtendService::updateByMerchantId($id, $miniData);
  284. MerchantService::updateById($id, ['miniAppId' => $authorizeAppId]);
  285. Yii::info('小程序信息更新成功:' . json_encode($authorize_info));
  286. util::stop("小程序信息更新成功");
  287. } else {
  288. if (isset($extend['wxAppId']) && !empty($extend['wxAppId'])) {
  289. if ($extend['wxAppId'] != $authorizeAppId) {
  290. util::stop('授权的公众号与商家已绑定的公众号不一致');
  291. }
  292. }
  293. }
  294. $wxData = [];
  295. $appData['wxUserName'] = $user_name;
  296. $appData['wxAliasName'] = $alias;
  297. //公众号logo
  298. $wxData['logo'] = WxBaseClass::saveLogo($head_img, $id);
  299. //公众号二维码
  300. $wxData['wxQrCodeUrl'] = WxBaseClass::saveQrCode($qrCodeUrl, $id);
  301. $wxData['wxAppId'] = $authorizeAppId;
  302. $wxData['wxAccessToken'] = $authorize_access_token;
  303. $wxData['wxAccessTokenTime'] = $accessTokenTime;
  304. $wxData['wxRefreshToken'] = $authorize_refresh_token;
  305. //开放平台还没有公众号先绑定开放平台的公众号
  306. if (isset($open['wx_base_id']) == false || empty($open['wx_base_id'])) {
  307. $wxData['addTime'] = $time;
  308. $wxBaseRespond = WxBaseService::add($wxData);
  309. $wxBaseId = $wxBaseRespond['id'];
  310. WxOpenService::updateOpen(['wx_base_id' => $wxBaseId]);
  311. util::stop('开放平台成功绑定公众号');
  312. }
  313. $wxData['status'] = 1;//审核通过
  314. xhMerchantService::updateById($id, $wxData);
  315. MerchantExtendClass::updateByCondition(['merchantId' => $id], ['wxAppId' => $authorizeAppId, 'wxAuth' => 1]);
  316. //还没有完成初始化先进行初始化
  317. if (isset($extend['init']) && $extend['init'] == 0) {
  318. $data = ['merchantId' => $id];
  319. $producer = Yii::$app->rabbitmq->getProducer('openShopInitProducer');
  320. $msg = serialize($data);
  321. $producer->publish($msg, 'openShopInitExchange', 'openShopInitRoute');
  322. }
  323. echo 'ok';
  324. }
  325. public function actionResult()
  326. {
  327. $get = Yii::$app->request->get();
  328. $id = isset($get['id']) ? $get['id'] : 0;
  329. $merchant = xhMerchantService::getById($id);
  330. $status = configDict::getConfig('merchantStatusName');
  331. $orMechantId = configDict::getConfig('merchantId');
  332. $originalMerchant = xhMerchantService::getById($orMechantId);
  333. return $this->renderPartial('result', ['originalMerchant' => $originalMerchant, 'merchant' => $merchant, 'status' => $status]);
  334. }
  335. public function actionCheckInviteCode()
  336. {
  337. $get = Yii::$app->request->get();
  338. $code = isset($get['code']) ? $get['code'] : '';
  339. $invite = xhInviteService::getByCode($code);
  340. if (empty($invite)) {
  341. util::fail('邀请码错误');
  342. }
  343. $now = time();
  344. if ($now > $invite['deadline']) {
  345. util::fail('邀请码已经失效');
  346. }
  347. if (!empty($invite['takeStatus'])) {
  348. util::fail('邀请码已经使用');
  349. }
  350. util::success($invite);
  351. }
  352. public function actionSelect()
  353. {
  354. $isWx = util::isWx();
  355. if ($isWx == false) {
  356. return $this->renderPartial('notWeixin');
  357. }
  358. return $this->renderPartial('select');
  359. }
  360. public function actionApi()
  361. {
  362. $openData = file_get_contents('php://input');
  363. if (isset ($openData) == false || empty($openData)) {
  364. util::stop('has no post data');
  365. }
  366. $weixinSecret = Yii::getAlias("@vendor/weixinSecret");
  367. require_once($weixinSecret . '/wxBizMsgCrypt.php');
  368. $get = Yii::$app->request->get();
  369. $encryptMsg = $openData;
  370. $openId = configDict::getConfig('openId');
  371. $open = xhWxOpenService::getById($openId);
  372. $encodingAesKey = $open['aesKey'];
  373. $token = $open['token'];
  374. $appId = $open['appId'];
  375. $appSecret = $open['appSecret'];
  376. $signature = isset($get['signature']) ? $get['signature'] : '';
  377. $timestamp = isset($get['timestamp']) ? $get['timestamp'] : '';
  378. $nonce = isset($get['nonce']) ? $get['nonce'] : '';
  379. $encrypt_type = isset($get['encrypt_type']) ? $get['encrypt_type'] : '';
  380. $msg_signature = isset($get['msg_signature']) ? $get['msg_signature'] : '';
  381. $xml_tree = new \DOMDocument();
  382. $xml_tree->loadXML($encryptMsg);
  383. $array_e = $xml_tree->getElementsByTagName('Encrypt');
  384. $encrypt = $array_e->item(0)->nodeValue;
  385. $format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%s]]></Encrypt></xml>";
  386. $from_xml = sprintf($format, $encrypt);
  387. $formString = " token:" . $token . "\n encodingAesKey:" . $encodingAesKey . "\n appId:" . $appId . "\n msg_signature:" . $msg_signature . "\n appSecret:" . $appSecret . "\n timestamp:" . $timestamp . "\n nonce:" . $nonce;
  388. Yii::warning($formString);
  389. $formString2 = "from_xml:" . $from_xml;
  390. Yii::warning($formString2);
  391. //第三方收到公众号平台发送的消息
  392. $pc = new \WXBizMsgCrypt($token, $encodingAesKey, $appId);
  393. $msg = '';//解密后的消息
  394. $errCode = $pc->decryptMsg($msg_signature, $timestamp, $nonce, $from_xml, $msg);
  395. if ($errCode != 0) {
  396. Yii::warning("解密未成功,错误代码:" . $errCode . "。(出现过的情况汇总:-40001 有可能token、encodingAesKey、appId等填写不对,请仔细核对每个值)");
  397. util::stop();
  398. }
  399. $postObj = simplexml_load_string($msg, 'SimpleXMLElement', LIBXML_NOCDATA);
  400. $infoType = $postObj->InfoType;
  401. switch ($infoType) {
  402. //推送 componentVerifyTicket
  403. case 'component_verify_ticket':
  404. $componentVerifyTicket = $postObj->ComponentVerifyTicket;
  405. if (!empty($componentVerifyTicket)) {
  406. $oData = [];
  407. $oData['verifyTicket'] = (string)$componentVerifyTicket;
  408. $oData['verifyTicketTime'] = date("Y-m-d H:i:s", $timestamp + 600);//每10分钟(600秒)推一次
  409. xhWxOpenService::updateById($openId, $oData);
  410. Yii::warning("component_verify_ticket:" . (string)$componentVerifyTicket);
  411. util::stop('success');
  412. }
  413. break;
  414. //取消授权通知
  415. case 'unauthorized':
  416. $AppId = $postObj->AppId;
  417. $authorizeAppid = $postObj->AuthorizerAppid;
  418. $merchant = xhMerchantService::getByAppId($authorizeAppid);
  419. if (!empty($merchant)) {
  420. $merchantId = $merchant['id'];
  421. //自主冻结
  422. xhMerchantService::updateById($merchantId, ['status' => 5]);
  423. }
  424. break;
  425. //授权成功通知
  426. case 'authorized':
  427. $AppId = $postObj->AppId;//第三方平台appid
  428. $CreateTime = $postObj->CreateTime;//公众号
  429. $authorizeAppid = $postObj->AuthorizerAppid;//授权码,可用于换取公众号的接口调用凭据,详细见上面的说明
  430. $AuthorizationCode = $postObj->AuthorizationCode;
  431. $AuthorizationCodeExpiredTime = $postObj->AuthorizationCodeExpiredTime;//授权码过期时间
  432. break;
  433. //授权更新通知
  434. case 'updateauthorized':
  435. $AppId = $postObj->AppId;
  436. $CreateTime = $postObj->CreateTime;
  437. $authorizeAppid = $postObj->AuthorizerAppid;
  438. $AuthorizationCode = $postObj->AuthorizationCode;
  439. $AuthorizationCodeExpiredTime = $postObj->AuthorizationCodeExpiredTime;
  440. util::stop();
  441. $authorize = wxUtil::getAuthorizer($AuthorizationCode);
  442. if (isset($authorize['authorization_info']) == false) {
  443. $msg = '授权回调获取到auth_code,但未换取公众号的接口调用凭据和授权信息!!';
  444. Yii::warning($msg, __METHOD__);
  445. Yii::$app->end();
  446. }
  447. $info = $authorize['authorization_info'];
  448. $authorizeAppId = $info['authorizer_appid'];
  449. $authorize_access_token = $info['authorizer_access_token'];
  450. $expires_in = $info['expires_in'];//7200
  451. $authorize_refresh_token = $info['authorizer_refresh_token'];
  452. $merchant = xhMerchantService::getByAppId($authorizeAppId);
  453. if (empty($merchant)) {
  454. return false;
  455. }
  456. $merchantId = $merchant['id'];
  457. $wxData = [];
  458. $wxData['wxAccessToken'] = $authorize_access_token;
  459. $wxData['wxRefreshToken'] = $authorize_refresh_token;
  460. $wxData['wxAccessTokenTime'] = date("Y-m-d H:i:s", (time() + $expires_in - 100));
  461. $wxData['status'] = 1;
  462. xhMerchantService::updateById($merchantId, $wxData);
  463. break;
  464. default:
  465. }
  466. Yii::warning("---wx open data end--- \n");
  467. }
  468. //获取平台信息 shish 2020.4.12
  469. public function actionGetWxOpen()
  470. {
  471. $open = WxOpenService::getOpen();
  472. util::success($open);
  473. }
  474. }