WxOpenController.php 11 KB

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