WxOpenController.php 11 KB

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