WxOpenController.php 21 KB

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