WxOpenController.php 19 KB

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