WxOpenController.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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. if (isset($authorize_info['MiniProgramInfo']) == false || empty($authorize_info['MiniProgramInfo'])) {
  103. util::stop('公众号不是服务号');
  104. }
  105. }
  106. $verify_type_info = $authorize_info['verify_type_info'];
  107. if ($verify_type_info['id'] != 0) {
  108. if (isset($authorize_info['MiniProgramInfo']) == false || empty($authorize_info['MiniProgramInfo'])) {
  109. util::stop('公众号还没有认证哦');
  110. }
  111. }
  112. $user_name = $authorize_info['user_name'];
  113. $alias = $authorize_info['alias'];
  114. $qrCodeUrl = $authorize_info['qrcode_url'];
  115. $accessTokenTime = date("Y-m-d H:i:s", (time() + $expires_in - 100));//安全起见,将过期时间设置得比微信里还短100秒
  116. //开放平台还没有关联公众号,先将开放平台关联公众号
  117. $open = WxOpenService::getOpen();
  118. if (isset($open['merchantId']) && empty($open['merchantId'])) {
  119. WxOpenService::updateById(1, ['merchantId' => $id]);
  120. }
  121. $extend = MerchantExtendClass::getByMerchantId($id);
  122. if (isset($authorize_info['MiniProgramInfo']) && !empty($authorize_info['MiniProgramInfo'])) {
  123. if (isset($extend['miniAppId']) && !empty($extend['miniAppId'])) {
  124. if ($extend['miniAppId'] != $authorizeAppId) {
  125. util::stop('授权的小程序与商家已绑定的小程序不一致');
  126. }
  127. }else{
  128. util::stop('数据库请先填写小程序 miniAppId miniAppSecret');
  129. }
  130. }else{
  131. if (isset($extend['wxAppId']) && !empty($extend['wxAppId'])) {
  132. if ($extend['wxAppId'] != $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,'miniAuth'=>1]);
  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,'wxAuth'=>1]);
  156. //还没有完成初始化先进行初始化
  157. if (isset($extend['init']) && $extend['init'] == 0) {
  158. $data = ['merchantId' => $id];
  159. $producer = Yii::$app->rabbitmq->getProducer('openShopInitProducer');
  160. $msg = serialize($data);
  161. $producer->publish($msg, 'openShopInitExchange', 'openShopInitRoute');
  162. }
  163. echo 'ok';
  164. }
  165. public function actionResult()
  166. {
  167. $get = Yii::$app->request->get();
  168. $id = isset($get['id']) ? $get['id'] : 0;
  169. $merchant = xhMerchantService::getById($id);
  170. $status = configDict::getConfig('merchantStatusName');
  171. $orMechantId = configDict::getConfig('merchantId');
  172. $originalMerchant = xhMerchantService::getById($orMechantId);
  173. return $this->renderPartial('result', ['originalMerchant' => $originalMerchant, 'merchant' => $merchant, 'status' => $status]);
  174. }
  175. public function actionCheckInviteCode()
  176. {
  177. $get = Yii::$app->request->get();
  178. $code = isset($get['code']) ? $get['code'] : '';
  179. $invite = xhInviteService::getByCode($code);
  180. if (empty($invite)) {
  181. util::fail('邀请码错误');
  182. }
  183. $now = time();
  184. if ($now > $invite['deadline']) {
  185. util::fail('邀请码已经失效');
  186. }
  187. if (!empty($invite['takeStatus'])) {
  188. util::fail('邀请码已经使用');
  189. }
  190. util::success($invite);
  191. }
  192. public function actionSelect()
  193. {
  194. $isWx = util::isWx();
  195. if ($isWx == false) {
  196. return $this->renderPartial('notWeixin');
  197. }
  198. return $this->renderPartial('select');
  199. }
  200. public function actionApi()
  201. {
  202. $openData = file_get_contents('php://input');
  203. if (isset ($openData) == false || empty($openData)) {
  204. util::stop('has no post data');
  205. }
  206. $weixinSecret = Yii::getAlias("@vendor/weixinSecret");
  207. require_once($weixinSecret . '/wxBizMsgCrypt.php');
  208. $get = Yii::$app->request->get();
  209. $encryptMsg = $openData;
  210. $openId = configDict::getConfig('openId');
  211. $open = xhWxOpenService::getById($openId);
  212. $encodingAesKey = $open['aesKey'];
  213. $token = $open['token'];
  214. $appId = $open['appId'];
  215. $signature = isset($get['signature']) ? $get['signature'] : '';
  216. $timestamp = isset($get['timestamp']) ? $get['timestamp'] : '';
  217. $nonce = isset($get['nonce']) ? $get['nonce'] : '';
  218. $encrypt_type = isset($get['encrypt_type']) ? $get['encrypt_type'] : '';
  219. $msg_signature = isset($get['msg_signature']) ? $get['msg_signature'] : '';
  220. $xml_tree = new \DOMDocument();
  221. $xml_tree->loadXML($encryptMsg);
  222. $array_e = $xml_tree->getElementsByTagName('Encrypt');
  223. $encrypt = $array_e->item(0)->nodeValue;
  224. $format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%s]]></Encrypt></xml>";
  225. $from_xml = sprintf($format, $encrypt);
  226. $formString = '1:' . $token . ' 2:' . $encodingAesKey . ' 3:' . $appId . ' 4:' . $msg_signature . ' 5:' . $timestamp . ' 6:' . $nonce . ' 7:' . $from_xml;
  227. Yii::warning("formString:" . $formString);
  228. //第三方收到公众号平台发送的消息
  229. $pc = new \WXBizMsgCrypt($token, $encodingAesKey, $appId);
  230. $msg = '';//解密后的消息
  231. $errCode = $pc->decryptMsg($msg_signature, $timestamp, $nonce, $from_xml, $msg);
  232. if ($errCode != 0) {
  233. Yii::warning("解密未成功,错误代码:" . $errCode);
  234. Yii::$app->end();
  235. }
  236. $postObj = simplexml_load_string($msg, 'SimpleXMLElement', LIBXML_NOCDATA);
  237. $infoType = $postObj->InfoType;
  238. switch ($infoType) {
  239. //推送 componentVerifyTicket
  240. case 'component_verify_ticket':
  241. $componentVerifyTicket = $postObj->ComponentVerifyTicket;
  242. if (!empty($componentVerifyTicket)) {
  243. $oData = [];
  244. $oData['verifyTicket'] = (string)$componentVerifyTicket;
  245. $oData['verifyTicketTime'] = date("Y-m-d H:i:s", $timestamp + 600);//每10分钟(600秒)推一次
  246. xhWxOpenService::updateById($openId, $oData);
  247. Yii::warning("component_verify_ticket:" . (string)$componentVerifyTicket);
  248. util::stop('success');
  249. }
  250. break;
  251. //取消授权通知
  252. case 'unauthorized':
  253. $AppId = $postObj->AppId;
  254. $authorizeAppid = $postObj->AuthorizerAppid;
  255. $merchant = xhMerchantService::getByAppId($authorizeAppid);
  256. if (!empty($merchant)) {
  257. $merchantId = $merchant['id'];
  258. //自主冻结
  259. xhMerchantService::updateById($merchantId, ['status' => 5]);
  260. }
  261. break;
  262. //授权成功通知
  263. case 'authorized':
  264. $AppId = $postObj->AppId;//第三方平台appid
  265. $CreateTime = $postObj->CreateTime;//公众号
  266. $authorizeAppid = $postObj->AuthorizerAppid;//授权码,可用于换取公众号的接口调用凭据,详细见上面的说明
  267. $AuthorizationCode = $postObj->AuthorizationCode;
  268. $AuthorizationCodeExpiredTime = $postObj->AuthorizationCodeExpiredTime;//授权码过期时间
  269. break;
  270. //授权更新通知
  271. case 'updateauthorized':
  272. $AppId = $postObj->AppId;
  273. $CreateTime = $postObj->CreateTime;
  274. $authorizeAppid = $postObj->AuthorizerAppid;
  275. $AuthorizationCode = $postObj->AuthorizationCode;
  276. $AuthorizationCodeExpiredTime = $postObj->AuthorizationCodeExpiredTime;
  277. util::stop();
  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. }