WxOpenController.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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. $authorize_access_token = $info['authorizer_access_token'];
  90. $expires_in = $info['expires_in'];//7200
  91. $authorize_refresh_token = $info['authorizer_refresh_token'];
  92. //获取授权方的公众号帐号基本信息
  93. $authorizeDetailInfo = wxUtil::getAuthorizerInfo($authorizeAppId);
  94. if (isset($authorizeDetailInfo['authorizer_info']) == false) {
  95. util::stop('没有获取到公众号帐号基本信息');
  96. }
  97. $authorize_info = $authorizeDetailInfo['authorizer_info'];
  98. //$nick_name = $authorize_info['nick_name'];
  99. $head_img = $authorize_info['head_img'];
  100. $service_type_info = $authorize_info['service_type_info'];
  101. if ($service_type_info['id'] != 2) {
  102. util::stop('公众号不是服务号');
  103. }
  104. $verify_type_info = $authorize_info['verify_type_info'];
  105. if ($verify_type_info['id'] != 0) {
  106. util::stop('公众号还没有认证哦');
  107. }
  108. $user_name = $authorize_info['user_name'];
  109. $alias = $authorize_info['alias'];
  110. $qrCodeUrl = $authorize_info['qrcode_url'];
  111. $accessTokenTime = date("Y-m-d H:i:s", (time() + $expires_in - 100));//安全起见,将过期时间设置得比微信里还短100秒
  112. //开放平台还没有关联公众号,先将开放平台关联公众号
  113. $open = WxOpenService::getOpen();
  114. if (isset($open['merchantId']) && empty($open['merchantId'])) {
  115. WxOpenService::updateById(1, ['merchantId' => $id]);
  116. }
  117. $merchant = MerchantService::getMerchantById($id);
  118. if (!empty($merchant['wxAppId']) && $merchant['wxAppId'] != $authorizeAppId) {
  119. util::stop('授权的公众号与商家不对应');
  120. }
  121. //小程序
  122. if (isset($authorize_info['MiniProgramInfo']) && !empty($authorize_info['MiniProgramInfo'])) {
  123. xhMerchantExtendService::updateByMerchantId($id, ['miniAppId' => $authorizeAppId, 'miniAccessToken' => $authorize_access_token, 'miniAccessTokenTime' => $accessTokenTime, 'miniRefreshToken' => $authorize_refresh_token]);
  124. Yii::info('小程序信息更新成功:' . json_encode($authorize_info));
  125. util::stop("小程序信息更新成功");
  126. }
  127. $upData = [];
  128. $appData['wxUserName'] = $user_name;
  129. $appData['wxAliasName'] = $alias;
  130. $upData['logo'] = xhMerchantService::logoSave($head_img, $authorizeAppId);//公众号logo
  131. $upData['wxQrcodeUrl'] = xhMerchantService::qrCodeSave($qrCodeUrl, $authorizeAppId);//公众号二维码
  132. $upData['wxAppId'] = $authorizeAppId;
  133. $upData['wxAccessToken'] = $authorize_access_token;
  134. $upData['wxAccessTokenTime'] = $accessTokenTime;
  135. $upData['wxRefreshToken'] = $authorize_refresh_token;
  136. $upData['status'] = 1;//审核通过
  137. xhMerchantService::updateById($id, $upData);
  138. MerchantExtendClass::updateByCondition(['merchantId' => $id], ['wxAppId' => $authorizeAppId]);
  139. //还没有完成初始化先进行初始化
  140. $extend = MerchantExtendClass::getByMerchantId($id);
  141. if (isset($extend['init']) && $extend['init'] == 0) {
  142. $data = ['merchantId' => $id];
  143. $producer = Yii::$app->rabbitmq->getProducer('openShopInitProducer');
  144. $msg = serialize($data);
  145. $producer->publish($msg, 'openShopInitExchange', 'openShopInitRoute');
  146. }
  147. echo 'ok';
  148. }
  149. public function actionResult()
  150. {
  151. $get = Yii::$app->request->get();
  152. $id = isset($get['id']) ? $get['id'] : 0;
  153. $merchant = xhMerchantService::getById($id);
  154. $status = configDict::getConfig('merchantStatusName');
  155. $orMechantId = configDict::getConfig('merchantId');
  156. $originalMerchant = xhMerchantService::getById($orMechantId);
  157. return $this->renderPartial('result', ['originalMerchant' => $originalMerchant, 'merchant' => $merchant, 'status' => $status]);
  158. }
  159. public function actionCheckInviteCode()
  160. {
  161. $get = Yii::$app->request->get();
  162. $code = isset($get['code']) ? $get['code'] : '';
  163. $invite = xhInviteService::getByCode($code);
  164. if (empty($invite)) {
  165. util::fail('邀请码错误');
  166. }
  167. $now = time();
  168. if ($now > $invite['deadline']) {
  169. util::fail('邀请码已经失效');
  170. }
  171. if (!empty($invite['takeStatus'])) {
  172. util::fail('邀请码已经使用');
  173. }
  174. util::success($invite);
  175. }
  176. public function actionSelect()
  177. {
  178. $isWx = util::isWx();
  179. if ($isWx == false) {
  180. return $this->renderPartial('notWeixin');
  181. }
  182. return $this->renderPartial('select');
  183. }
  184. public function actionApi()
  185. {
  186. $openData = file_get_contents('php://input');
  187. if (isset ($openData) == false || empty($openData)) {
  188. util::stop('has no post data');
  189. }
  190. $weixinSecret = Yii::getAlias("@vendor/weixinSecret");
  191. require_once($weixinSecret . '/wxBizMsgCrypt.php');
  192. $get = Yii::$app->request->get();
  193. $encryptMsg = $openData;
  194. $openId = configDict::getConfig('openId');
  195. $open = xhWxOpenService::getById($openId);
  196. $encodingAesKey = $open['aesKey'];
  197. $token = $open['token'];
  198. $appId = $open['appId'];
  199. $signature = isset($get['signature']) ? $get['signature'] : '';
  200. $timestamp = isset($get['timestamp']) ? $get['timestamp'] : '';
  201. $nonce = isset($get['nonce']) ? $get['nonce'] : '';
  202. $encrypt_type = isset($get['encrypt_type']) ? $get['encrypt_type'] : '';
  203. $msg_signature = isset($get['msg_signature']) ? $get['msg_signature'] : '';
  204. $xml_tree = new \DOMDocument();
  205. $xml_tree->loadXML($encryptMsg);
  206. $array_e = $xml_tree->getElementsByTagName('Encrypt');
  207. $encrypt = $array_e->item(0)->nodeValue;
  208. $format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%s]]></Encrypt></xml>";
  209. $from_xml = sprintf($format, $encrypt);
  210. $formString = '1:' . $token . ' 2:' . $encodingAesKey . ' 3:' . $appId . ' 4:' . $msg_signature . ' 5:' . $timestamp . ' 6:' . $nonce . ' 7:' . $from_xml;
  211. Yii::warning("formString:" . $formString);
  212. //第三方收到公众号平台发送的消息
  213. $pc = new \WXBizMsgCrypt($token, $encodingAesKey, $appId);
  214. $msg = '';//解密后的消息
  215. $errCode = $pc->decryptMsg($msg_signature, $timestamp, $nonce, $from_xml, $msg);
  216. if ($errCode != 0) {
  217. Yii::warning("解密未成功,错误代码:" . $errCode);
  218. Yii::$app->end();
  219. }
  220. $postObj = simplexml_load_string($msg, 'SimpleXMLElement', LIBXML_NOCDATA);
  221. $infoType = $postObj->InfoType;
  222. switch ($infoType) {
  223. //推送 componentVerifyTicket
  224. case 'component_verify_ticket':
  225. $componentVerifyTicket = $postObj->ComponentVerifyTicket;
  226. if (!empty($componentVerifyTicket)) {
  227. $oData = [];
  228. $oData['verifyTicket'] = (string)$componentVerifyTicket;
  229. $oData['verifyTicketTime'] = date("Y-m-d H:i:s", $timestamp + 600);//每10分钟(600秒)推一次
  230. xhWxOpenService::updateById($openId, $oData);
  231. Yii::warning("component_verify_ticket:" . (string)$componentVerifyTicket);
  232. util::stop('success');
  233. }
  234. break;
  235. //取消授权通知
  236. case 'unauthorized':
  237. $AppId = $postObj->AppId;
  238. $authorizeAppid = $postObj->AuthorizerAppid;
  239. $merchant = xhMerchantService::getByAppId($authorizeAppid);
  240. if (!empty($merchant)) {
  241. $merchantId = $merchant['id'];
  242. //自主冻结
  243. xhMerchantService::updateById($merchantId, ['status' => 5]);
  244. }
  245. break;
  246. //授权成功通知
  247. case 'authorized':
  248. $AppId = $postObj->AppId;//第三方平台appid
  249. $CreateTime = $postObj->CreateTime;//公众号
  250. $authorizeAppid = $postObj->AuthorizerAppid;//授权码,可用于换取公众号的接口调用凭据,详细见上面的说明
  251. $AuthorizationCode = $postObj->AuthorizationCode;
  252. $AuthorizationCodeExpiredTime = $postObj->AuthorizationCodeExpiredTime;//授权码过期时间
  253. break;
  254. //授权更新通知
  255. case 'updateauthorized':
  256. $AppId = $postObj->AppId;
  257. $CreateTime = $postObj->CreateTime;
  258. $authorizeAppid = $postObj->AuthorizerAppid;
  259. $AuthorizationCode = $postObj->AuthorizationCode;
  260. $AuthorizationCodeExpiredTime = $postObj->AuthorizationCodeExpiredTime;
  261. $authorize = wxUtil::getAuthorizer($AuthorizationCode);
  262. if (isset($authorize['authorization_info']) == false) {
  263. $msg = '授权回调获取到auth_code,但未换取公众号的接口调用凭据和授权信息!!';
  264. Yii::warning($msg, __METHOD__);
  265. Yii::$app->end();
  266. }
  267. $info = $authorize['authorization_info'];
  268. $authorizeAppId = $info['authorizer_appid'];
  269. $authorize_access_token = $info['authorizer_access_token'];
  270. $expires_in = $info['expires_in'];//7200
  271. $authorize_refresh_token = $info['authorizer_refresh_token'];
  272. $merchant = xhMerchantService::getByAppId($authorizeAppId);
  273. if (empty($merchant)) {
  274. return false;
  275. }
  276. $merchantId = $merchant['id'];
  277. $wxData = [];
  278. $wxData['wxAccessToken'] = $authorize_access_token;
  279. $wxData['wxRefreshToken'] = $authorize_refresh_token;
  280. $wxData['wxAccessTokenTime'] = date("Y-m-d H:i:s", (time() + $expires_in - 100));
  281. $wxData['status'] = 1;
  282. xhMerchantService::updateById($merchantId, $wxData);
  283. break;
  284. default:
  285. }
  286. Yii::warning("---wx open data end--- \n");
  287. }
  288. }