WxOpenController.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. <?php
  2. namespace www\controllers;
  3. use biz\ad\classes\AdClass;
  4. use biz\goods\classes\CategoryClass;
  5. use biz\merchant\classes\MerchantExtendClass;
  6. use biz\merchant\services\MerchantService;
  7. use biz\weixin\services\WxOpenService;
  8. use common\services\xhMerchantExtendService;
  9. use Yii;
  10. use common\services\xhApplyOrderService;
  11. use common\services\xhWxMenuService;
  12. use common\services\xhMerchantService;
  13. use common\services\xhInviteService;
  14. use common\components\util;
  15. use common\components\configDict;
  16. use common\services\xhWxOpenService;
  17. use common\components\stringUtil;
  18. use common\components\wxUtil;
  19. use common\services\xhSetMealService;
  20. /**
  21. * 微信开放平台相关
  22. */
  23. class WxOpenController extends PublicController
  24. {
  25. public $withoutLogin = [];
  26. //开放平台开始授权 shish 2020.1.16
  27. public function actionBeginAuth()
  28. {
  29. $merchantId = Yii::$app->request->get('id', 0);
  30. $open = WxOpenService::getOpen();
  31. //1只显示公众号 2只显示小程序 3显示公众号和小程序
  32. $authType = Yii::$app->request->get('authType', 3);
  33. $pre = wxUtil::getPreAuthCode($open);
  34. $appId = $open['appId'];
  35. $oData = [];
  36. $oData['preAuthCodeTime'] = date("Y-m-d H:i:s");
  37. //设置预授码过期,让下个用户可以获取新的预授码
  38. xhWxOpenService::updateById(1, $oData);
  39. $url = Yii::$app->params['wHost'] . '/wx-open-callback/' . $merchantId;
  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. //平台没有绑定商家公众号时初始化一个商家 shish 2020.2.11
  43. public function actionAddMerchant()
  44. {
  45. AdClass::initAdd(12362);
  46. //CategoryClass::initCategoryGoods(12362);
  47. $return = MerchantService::initOpenMerchant();
  48. dd($return);
  49. }
  50. public function actionCheckMerchantName()
  51. {
  52. $get = Yii::$app->request->get();
  53. $merchantName = isset($get['merchantName']) ? $get['merchantName'] : '';
  54. $m = xhMerchantService::getByMerchantName($merchantName);
  55. if (!empty($m)) {
  56. util::fail('公众号名称已经使用');
  57. }
  58. util::ok();
  59. }
  60. /**
  61. * 下载微信里的图片到服务器
  62. */
  63. public function actionDownloadWxImg()
  64. {
  65. $get = Yii::$app->request->get();
  66. $mediaId = isset($get['mediaId']) ? $get['mediaId'] : '';
  67. $imgList = wxUtil::downloadmediaIdImg($this->merchant, $mediaId);
  68. if (!empty($imgList)) {
  69. util::success($imgList);
  70. }
  71. util::fail();
  72. }
  73. //创建平台使用的公众号
  74. public function actionCallback()
  75. {
  76. $get = Yii::$app->request->get();
  77. if (isset($get['auth_code']) == false) {
  78. util::stop('公众号授权回调未成功');
  79. }
  80. $id = isset($get['id']) ? $get['id'] : 0;
  81. $code = $get['auth_code'];
  82. //使用授权码换取公众号的接口调用凭据和授权信息
  83. $authorize = wxUtil::getAuthorizer($code);
  84. if (isset($authorize['authorization_info']) == false) {
  85. util::stop('未换取公众号的接口调用凭据和授权信息');
  86. }
  87. $info = $authorize['authorization_info'];
  88. $authorizeAppId = $info['authorizer_appid'];
  89. dd($info);
  90. $authorize_access_token = $info['authorizer_access_token'];
  91. $expires_in = $info['expires_in'];//7200
  92. $authorize_refresh_token = $info['authorizer_refresh_token'];
  93. //获取授权方的公众号帐号基本信息
  94. $authorizeDetailInfo = wxUtil::getAuthorizerInfo($authorizeAppId);
  95. if (isset($authorizeDetailInfo['authorizer_info']) == false) {
  96. util::stop('没有获取到公众号帐号基本信息');
  97. }
  98. $authorize_info = $authorizeDetailInfo['authorizer_info'];
  99. //$nick_name = $authorize_info['nick_name'];
  100. $head_img = $authorize_info['head_img'];
  101. $service_type_info = $authorize_info['service_type_info'];
  102. if ($service_type_info['id'] != 2) {
  103. if (isset($authorize_info['MiniProgramInfo']) == false || empty($authorize_info['MiniProgramInfo'])) {
  104. util::stop('公众号不是服务号');
  105. }
  106. }
  107. $verify_type_info = $authorize_info['verify_type_info'];
  108. if ($verify_type_info['id'] != 0) {
  109. if (isset($authorize_info['MiniProgramInfo']) == false || empty($authorize_info['MiniProgramInfo'])) {
  110. util::stop('公众号还没有认证哦');
  111. }
  112. }
  113. $user_name = $authorize_info['user_name'];
  114. $alias = $authorize_info['alias'];
  115. $qrCodeUrl = $authorize_info['qrcode_url'];
  116. $accessTokenTime = date("Y-m-d H:i:s", (time() + $expires_in - 100));//安全起见,将过期时间设置得比微信里还短100秒
  117. //开放平台还没有关联公众号,先将开放平台关联公众号
  118. $open = WxOpenService::getOpen();
  119. if (isset($open['merchantId']) && empty($open['merchantId'])) {
  120. WxOpenService::updateById(1, ['merchantId' => $id]);
  121. }
  122. $merchant = MerchantService::getMerchantById($id);
  123. if (isset($merchant['wxAppId']) && !empty($merchant['wxAppId'])) {
  124. if (isset($authorize_info['MiniProgramInfo']) == false || empty($authorize_info['MiniProgramInfo'])) {
  125. if ($merchant['wxAppId'] != $authorizeAppId) {
  126. util::stop('授权的公众号与商家已绑定的公众号不一致');
  127. }
  128. }
  129. }
  130. if (isset($merchant['miniAppId']) && !empty($merchant['miniAppId'])) {
  131. if (isset($authorize_info['MiniProgramInfo']) && !empty($authorize_info['MiniProgramInfo'])) {
  132. if ($merchant['miniAppId'] != $authorizeAppId) {
  133. util::stop('授权的小程序与商家已绑定的小程序不一致');
  134. }
  135. }
  136. }
  137. //小程序
  138. if (isset($authorize_info['MiniProgramInfo']) && !empty($authorize_info['MiniProgramInfo'])) {
  139. xhMerchantExtendService::updateByMerchantId($id, ['miniAppId' => $authorizeAppId, 'miniAccessToken' => $authorize_access_token, 'miniAccessTokenTime' => $accessTokenTime, 'miniRefreshToken' => $authorize_refresh_token]);
  140. MerchantService::updateById($id, ['miniAppId' => $authorizeAppId]);
  141. Yii::info('小程序信息更新成功:' . json_encode($authorize_info));
  142. util::stop("小程序信息更新成功");
  143. }
  144. $upData = [];
  145. $appData['wxUserName'] = $user_name;
  146. $appData['wxAliasName'] = $alias;
  147. $upData['logo'] = xhMerchantService::logoSave($head_img, $authorizeAppId);//公众号logo
  148. $upData['wxQrcodeUrl'] = xhMerchantService::qrCodeSave($qrCodeUrl, $authorizeAppId);//公众号二维码
  149. $upData['wxAppId'] = $authorizeAppId;
  150. $upData['wxAccessToken'] = $authorize_access_token;
  151. $upData['wxAccessTokenTime'] = $accessTokenTime;
  152. $upData['wxRefreshToken'] = $authorize_refresh_token;
  153. $upData['status'] = 1;//审核通过
  154. xhMerchantService::updateById($id, $upData);
  155. MerchantExtendClass::updateByCondition(['merchantId' => $id], ['wxAppId' => $authorizeAppId]);
  156. //还没有完成初始化先进行初始化
  157. $extend = MerchantExtendClass::getByMerchantId($id);
  158. if (isset($extend['init']) && $extend['init'] == 0) {
  159. $data = ['merchantId' => $id];
  160. $producer = Yii::$app->rabbitmq->getProducer('openShopInitProducer');
  161. $msg = serialize($data);
  162. $producer->publish($msg, 'openShopInitExchange', 'openShopInitRoute');
  163. }
  164. echo 'ok';
  165. }
  166. public function actionResult()
  167. {
  168. $get = Yii::$app->request->get();
  169. $id = isset($get['id']) ? $get['id'] : 0;
  170. $merchant = xhMerchantService::getById($id);
  171. $status = configDict::getConfig('merchantStatusName');
  172. $orMechantId = configDict::getConfig('merchantId');
  173. $originalMerchant = xhMerchantService::getById($orMechantId);
  174. return $this->renderPartial('result', ['originalMerchant' => $originalMerchant, 'merchant' => $merchant, 'status' => $status]);
  175. }
  176. public function actionCheckInviteCode()
  177. {
  178. $get = Yii::$app->request->get();
  179. $code = isset($get['code']) ? $get['code'] : '';
  180. $invite = xhInviteService::getByCode($code);
  181. if (empty($invite)) {
  182. util::fail('邀请码错误');
  183. }
  184. $now = time();
  185. if ($now > $invite['deadline']) {
  186. util::fail('邀请码已经失效');
  187. }
  188. if (!empty($invite['takeStatus'])) {
  189. util::fail('邀请码已经使用');
  190. }
  191. util::success($invite);
  192. }
  193. public function actionSelect()
  194. {
  195. $isWx = util::isWx();
  196. if ($isWx == false) {
  197. return $this->renderPartial('notWeixin');
  198. }
  199. return $this->renderPartial('select');
  200. }
  201. public function actionApi()
  202. {
  203. $openData = file_get_contents('php://input');
  204. if (isset ($openData) == false || empty($openData)) {
  205. util::stop('has no post data');
  206. }
  207. $weixinSecret = Yii::getAlias("@vendor/weixinSecret");
  208. require_once($weixinSecret . '/wxBizMsgCrypt.php');
  209. $get = Yii::$app->request->get();
  210. $encryptMsg = $openData;
  211. $openId = configDict::getConfig('openId');
  212. $open = xhWxOpenService::getById($openId);
  213. $encodingAesKey = $open['aesKey'];
  214. $token = $open['token'];
  215. $appId = $open['appId'];
  216. $signature = isset($get['signature']) ? $get['signature'] : '';
  217. $timestamp = isset($get['timestamp']) ? $get['timestamp'] : '';
  218. $nonce = isset($get['nonce']) ? $get['nonce'] : '';
  219. $encrypt_type = isset($get['encrypt_type']) ? $get['encrypt_type'] : '';
  220. $msg_signature = isset($get['msg_signature']) ? $get['msg_signature'] : '';
  221. $xml_tree = new \DOMDocument();
  222. $xml_tree->loadXML($encryptMsg);
  223. $array_e = $xml_tree->getElementsByTagName('Encrypt');
  224. $encrypt = $array_e->item(0)->nodeValue;
  225. $format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%s]]></Encrypt></xml>";
  226. $from_xml = sprintf($format, $encrypt);
  227. $formString = '1:' . $token . ' 2:' . $encodingAesKey . ' 3:' . $appId . ' 4:' . $msg_signature . ' 5:' . $timestamp . ' 6:' . $nonce . ' 7:' . $from_xml;
  228. Yii::warning("formString:" . $formString);
  229. //第三方收到公众号平台发送的消息
  230. $pc = new \WXBizMsgCrypt($token, $encodingAesKey, $appId);
  231. $msg = '';//解密后的消息
  232. $errCode = $pc->decryptMsg($msg_signature, $timestamp, $nonce, $from_xml, $msg);
  233. if ($errCode != 0) {
  234. Yii::warning("解密未成功,错误代码:" . $errCode);
  235. Yii::$app->end();
  236. }
  237. $postObj = simplexml_load_string($msg, 'SimpleXMLElement', LIBXML_NOCDATA);
  238. $infoType = $postObj->InfoType;
  239. switch ($infoType) {
  240. //推送 componentVerifyTicket
  241. case 'component_verify_ticket':
  242. $componentVerifyTicket = $postObj->ComponentVerifyTicket;
  243. if (!empty($componentVerifyTicket)) {
  244. $oData = [];
  245. $oData['verifyTicket'] = (string)$componentVerifyTicket;
  246. $oData['verifyTicketTime'] = date("Y-m-d H:i:s", $timestamp + 600);//每10分钟(600秒)推一次
  247. xhWxOpenService::updateById($openId, $oData);
  248. Yii::warning("component_verify_ticket:" . (string)$componentVerifyTicket);
  249. util::stop('success');
  250. }
  251. break;
  252. //取消授权通知
  253. case 'unauthorized':
  254. $AppId = $postObj->AppId;
  255. $authorizeAppid = $postObj->AuthorizerAppid;
  256. $merchant = xhMerchantService::getByAppId($authorizeAppid);
  257. if (!empty($merchant)) {
  258. $merchantId = $merchant['id'];
  259. //自主冻结
  260. xhMerchantService::updateById($merchantId, ['status' => 5]);
  261. }
  262. break;
  263. //授权成功通知
  264. case 'authorized':
  265. $AppId = $postObj->AppId;//第三方平台appid
  266. $CreateTime = $postObj->CreateTime;//公众号
  267. $authorizeAppid = $postObj->AuthorizerAppid;//授权码,可用于换取公众号的接口调用凭据,详细见上面的说明
  268. $AuthorizationCode = $postObj->AuthorizationCode;
  269. $AuthorizationCodeExpiredTime = $postObj->AuthorizationCodeExpiredTime;//授权码过期时间
  270. break;
  271. //授权更新通知
  272. case 'updateauthorized':
  273. $AppId = $postObj->AppId;
  274. $CreateTime = $postObj->CreateTime;
  275. $authorizeAppid = $postObj->AuthorizerAppid;
  276. $AuthorizationCode = $postObj->AuthorizationCode;
  277. $AuthorizationCodeExpiredTime = $postObj->AuthorizationCodeExpiredTime;
  278. $authorize = wxUtil::getAuthorizer($AuthorizationCode);
  279. if (isset($authorize['authorization_info']) == false) {
  280. $msg = '授权回调获取到auth_code,但未换取公众号的接口调用凭据和授权信息!!';
  281. Yii::warning($msg, __METHOD__);
  282. Yii::$app->end();
  283. }
  284. $info = $authorize['authorization_info'];
  285. $authorizeAppId = $info['authorizer_appid'];
  286. $authorize_access_token = $info['authorizer_access_token'];
  287. $expires_in = $info['expires_in'];//7200
  288. $authorize_refresh_token = $info['authorizer_refresh_token'];
  289. $merchant = xhMerchantService::getByAppId($authorizeAppId);
  290. if (empty($merchant)) {
  291. return false;
  292. }
  293. $merchantId = $merchant['id'];
  294. $wxData = [];
  295. $wxData['wxAccessToken'] = $authorize_access_token;
  296. $wxData['wxRefreshToken'] = $authorize_refresh_token;
  297. $wxData['wxAccessTokenTime'] = date("Y-m-d H:i:s", (time() + $expires_in - 100));
  298. $wxData['status'] = 1;
  299. xhMerchantService::updateById($merchantId, $wxData);
  300. break;
  301. default:
  302. }
  303. Yii::warning("---wx open data end--- \n");
  304. }
  305. }