WxOpenController.php 12 KB

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