WxOpenController.php 12 KB

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