Эх сурвалжийг харах

平台公众号小程序关联

shish 6 жил өмнө
parent
commit
862bfdc8a4

+ 489 - 459
app/saas/controllers/WxOpenController.php

@@ -5,6 +5,8 @@ namespace saas\controllers;
 use biz\merchant\services\MerchantExtendService;
 use biz\merchant\services\MerchantService;
 use biz\weixin\services\MiniProgramService;
+use biz\weixin\services\WxBaseService;
+use biz\weixin\services\WxMiniBaseService;
 use common\components\util;
 use Yii;
 use common\components\wxUtil;
@@ -20,463 +22,491 @@ use common\services\xhWxOpenService;
 
 class WxOpenController extends BaseController
 {
-
-    public $withoutLogin = ['bind-open'];
-
-    public function actionBindOpen()
-    {
-        $merchantId = Yii::$app->request->get('merchantId', 0);
-        $merchant = MerchantService::getMerchantById($merchantId);
-        if (empty($merchant)) {
-            util::fail('没有找到商家');
-        }
-        $wxAppId = $merchant['wxAppId'];
-        $miniAppId = $merchant['miniAppId'];
-        $open_appid = $merchant['openAppId'];
-
-        echo "<pre>";
-
-        $id = Yii::$app->request->get('id', 0);
-        //创建平台,并将公众号绑定到平台
-        if ($id == 1) {
-            wxUtil::createOpenAccount($wxAppId, $merchant);
-            $return = wxUtil::getOpenAccount($wxAppId, $merchant);
-            print_r($return);
-            if ($return['errcode'] == 0) {
-                $openAppId = $return['open_appid'];
-                MerchantService::updateById($merchantId, ['openAppId' => $openAppId]);
-                MerchantExtendService::updateByCondition(['merchantId' => $merchantId], ['openAppId' => $openAppId, 'openAppBind' => 1, 'wxAuth' => 1]);
-            }
-        }
-        //将小程序绑定到平台
-        if ($id == 2) {
-            $openAppId = $merchant['openAppId'];
-            $r = wxUtil::bindOpenAccount($miniAppId, $openAppId, $merchant, true);
-            MerchantExtendService::updateByCondition(['merchantId' => $merchantId], ['openAppBind' => 3, 'miniAuth' => 1]);
-            print_r($r);
-        }
-        //查询公众号 小程序的绑定情况
-        if ($id == 3) {
-            $return = wxUtil::getOpenAccount($wxAppId, $merchant);
-            print_r($return);
-            $return = wxUtil::getOpenAccount($miniAppId, $merchant, true);
-            print_r($return);
-        }
-
-        //设置小程序服务器域名
-        if ($id == 4) {
-            wxUtil::setDomain($merchant);
-            wxUtil::setWebViewDomain($merchant);
-        }
-
-        //为授权的小程序帐号上传小程序代码
-        if ($id == 5) {
-            $tId = $_GET['tId'];
-            wxUtil::miniCommit($merchant, $tId);
-        }
-
-        //获取小程序体验码
-        if ($id == 6) {
-            wxUtil::getExperienceQrCode($merchant);
-        }
-
-        //获取授权小程序帐号已设置的类目
-        if ($id == 7) {
-            wxUtil::getMiniCategory($merchant);
-        }
-
-        //获取小程序的第三方提交代码的页面配置
-        if ($id == 8) {
-            wxUtil::getMiniPage($merchant);
-        }
-
-        //将第三方提交的代码包提交审核
-        if ($id == 9) {
-            wxUtil::miniSubmitAudit($merchant);
-        }
-
-        //查询最新一次提交的审核状态
-        if ($id == 10) {
-            wxUtil::miniGetLatestAuditStatus($merchant);
-        }
-
-        //发布已通过审核的小程序
-        if ($id == 11) {
-            $r = MiniProgramService::release($merchant);
-            print_r($r);
-        }
-
-        //撤回审核
-        if ($id == 12) {
-            wxUtil::rollbackCheck($merchant);
-        }
-        //生成 申请会员页 的小程序码
-        if ($id == 13) {
-            wxUtil::generateMemberCode($merchant);
-        }
-        //解绑小程序和公众号绑定的平台
-        if ($id == 14) {
-            wxUtil::unbindAccount($merchant);
-            wxUtil::unbindMiniProgram($merchant);
-        }
-        Yii::$app->end();
-
-        $r = wxUtil::bindOpenAccount($miniAppId, $open_appid, $merchant, true);
-        print_r($r);
-        echo $miniAppId . ' ' . $open_appid . ' ';
-
-        $return = wxUtil::getOpenAccount($wxAppId, $merchant);
-        print_r($return);
-        die;
-
-        $return = wxUtil::createOpenAccount($wxAppId, $merchant);
-        print_r($return);
-        die;
-
-        $r = wxUtil::bindOpenAccount($miniAppId, $open_appid, $merchant);
-        print_r($r);
-        echo $miniAppId . ' ' . $open_appid . ' ';
-
-        $return = wxUtil::getOpenAccount($wxAppId, $merchant);
-        print_r($return);
-        $return = wxUtil::getOpenAccount($miniAppId, $merchant);
-        print_r($return);
-        die;
-
-        if ($return['errcode'] == 0) {
-            $open_appid = isset($return['open_appid']) ? $return['open_appid'] : '';
-        } else {
-            $return = wxUtil::createOpenAccount($wxAppId, $merchant);
-            if ($return['errcode'] == 0) {
-                $open_appid = isset($return['open_appid']) ? $return['open_appid'] : '';
-            }
-        }
-        echo "<br />open_appid:" . $open_appid . "<br />";
-        if (!empty($open_appid)) {
-            xhMerchantService::updateById($merchantId, ['openAppId' => $open_appid]);
-            MerchantExtendService::updateByCondition(['merchantId' => $merchantId], ['openAppId' => $open_appid, 'openAppBind' => 3, 'miniAuth' => 1]);
-            $r = wxUtil::bindOpenAccount($miniAppId, $open_appid, $merchant);
-            echo "绑定小程序结果:<br />";
-            print_r($r);
-        }
-        echo "<br /><br />";
-        $return = wxUtil::getOpenAccount($wxAppId, $merchant);
-        echo "微信appId:{$wxAppId}<br />";
-        print_r($return);
-        $return = wxUtil::getOpenAccount($miniAppId, $merchant);
-        echo "<br />小程序appId:{$miniAppId}<br />";
-        print_r($return);
-    }
-
-    //开放平台开始授权 shish 2020.1.16
-    public function actionBeginAuth()
-    {
-        $merchantId = Yii::$app->request->get('id', 0);
-        $open = WxOpenService::getOpen();
-        //1只显示公众号 2只显示小程序  3显示公众号和小程序
-        $authType = Yii::$app->request->get('authType', 3);
-        $pre = wxUtil::getPreAuthCode($open);
-        $appId = $open['appId'];
-        $oData = [];
-        $oData['preAuthCodeTime'] = date("Y-m-d H:i:s");
-        //设置预授码过期,让下个用户可以获取新的预授码
-        xhWxOpenService::updateById(1, $oData);
-        $url = Yii::$app->params['saasHost'] . '/wx-open-callback/' . $merchantId;
-        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>";
-    }
-
-    //平台没有绑定商家公众号时初始化一个商家 shish 2020.2.11
-    public function actionAddMerchant()
-    {
-        AdClass::initAdd(12362);
-        $return = MerchantService::initOpenMerchant();
-        dd($return);
-    }
-
-    public function actionCheckMerchantName()
-    {
-        $get = Yii::$app->request->get();
-        $merchantName = isset($get['merchantName']) ? $get['merchantName'] : '';
-        $m = xhMerchantService::getByMerchantName($merchantName);
-        if (!empty($m)) {
-            util::fail('公众号名称已经使用');
-        }
-        util::complete();
-    }
-
-    /**
-     * 下载微信里的图片到服务器
-     */
-    public function actionDownloadWxImg()
-    {
-        $get = Yii::$app->request->get();
-        $mediaId = isset($get['mediaId']) ? $get['mediaId'] : '';
-        $imgList = wxUtil::downloadmediaIdImg($this->merchant, $mediaId);
-        if (!empty($imgList)) {
-            util::success($imgList);
-        }
-        util::fail();
-    }
-
-    //创建平台使用的公众号
-    public function actionCallback()
-    {
-        $get = Yii::$app->request->get();
-        if (isset($get['auth_code']) == false) {
-            util::stop('公众号授权回调未成功');
-        }
-        $id = isset($get['id']) ? $get['id'] : 0;
-        $code = $get['auth_code'];
-        //使用授权码换取公众号的接口调用凭据和授权信息
-        $authorize = wxUtil::getAuthorizer($code);
-        if (isset($authorize['authorization_info']) == false) {
-            util::stop('未换取公众号的接口调用凭据和授权信息');
-        }
-        $info = $authorize['authorization_info'];
-        $authorizeAppId = $info['authorizer_appid'];
-        $authorize_access_token = $info['authorizer_access_token'];
-        $expires_in = $info['expires_in'];//7200
-        $authorize_refresh_token = $info['authorizer_refresh_token'];
-        //获取授权方的公众号帐号基本信息
-        $authorizeDetailInfo = wxUtil::getAuthorizerInfo($authorizeAppId);
-        if (isset($authorizeDetailInfo['authorizer_info']) == false) {
-            util::stop('没有获取到公众号帐号基本信息');
-        }
-        $authorize_info = $authorizeDetailInfo['authorizer_info'];
-        //$nick_name = $authorize_info['nick_name'];
-        $head_img = $authorize_info['head_img'];
-        $service_type_info = $authorize_info['service_type_info'];
-        if ($service_type_info['id'] != 2) {
-            if (isset($authorize_info['MiniProgramInfo']) == false || empty($authorize_info['MiniProgramInfo'])) {
-                util::stop('公众号不是服务号');
-            }
-        }
-        $verify_type_info = $authorize_info['verify_type_info'];
-        if ($verify_type_info['id'] != 0) {
-            if (isset($authorize_info['MiniProgramInfo']) == false || empty($authorize_info['MiniProgramInfo'])) {
-                util::stop('公众号还没有认证哦');
-            }
-        }
-        $user_name = $authorize_info['user_name'];
-        $alias = $authorize_info['alias'];
-        $qrCodeUrl = $authorize_info['qrcode_url'];
-        $accessTokenTime = date("Y-m-d H:i:s", (time() + $expires_in - 100));//安全起见,将过期时间设置得比微信里还短100秒
-
-        //开放平台还没有关联公众号,先将开放平台关联公众号
-        $open = WxOpenService::getOpen();
-        if (isset($open['merchantId']) && empty($open['merchantId'])) {
-            WxOpenService::updateById(1, ['merchantId' => $id]);
-        }
-
-        $extend = MerchantExtendClass::getByMerchantId($id);
-
-        if (isset($authorize_info['MiniProgramInfo']) && !empty($authorize_info['MiniProgramInfo'])) {
-            if (isset($extend['miniAppId']) && !empty($extend['miniAppId'])) {
-                if ($extend['miniAppId'] != $authorizeAppId) {
-                    util::stop('授权的小程序与商家已绑定的小程序不一致');
-                }
-            } else {
-                util::stop('数据库请先填写小程序 miniAppId miniAppSecret');
-            }
-        } else {
-            if (isset($extend['wxAppId']) && !empty($extend['wxAppId'])) {
-                if ($extend['wxAppId'] != $authorizeAppId) {
-                    util::stop('授权的公众号与商家已绑定的公众号不一致');
-                }
-            }
-        }
-
-        //小程序
-        if (isset($authorize_info['MiniProgramInfo']) && !empty($authorize_info['MiniProgramInfo'])) {
-            xhMerchantExtendService::updateByMerchantId($id, ['miniAppId' => $authorizeAppId, 'miniAuth' => 1, 'miniAccessToken' => $authorize_access_token, 'miniAccessTokenTime' => $accessTokenTime, 'miniRefreshToken' => $authorize_refresh_token]);
-            MerchantService::updateById($id, ['miniAppId' => $authorizeAppId]);
-            Yii::info('小程序信息更新成功:' . json_encode($authorize_info));
-            util::stop("小程序信息更新成功");
-        }
-
-        $upData = [];
-        $appData['wxUserName'] = $user_name;
-        $appData['wxAliasName'] = $alias;
-        //公众号logo
-        $upData['logo'] = WxBaseClass::saveLogo($head_img, $id);
-        //公众号二维码
-        $upData['wxQrCodeUrl'] = WxBaseClass::saveQrCode($qrCodeUrl, $id);
-        $upData['wxAppId'] = $authorizeAppId;
-        $upData['wxAccessToken'] = $authorize_access_token;
-        $upData['wxAccessTokenTime'] = $accessTokenTime;
-        $upData['wxRefreshToken'] = $authorize_refresh_token;
-        $upData['status'] = 1;//审核通过
-        xhMerchantService::updateById($id, $upData);
-        MerchantExtendClass::updateByCondition(['merchantId' => $id], ['wxAppId' => $authorizeAppId, 'wxAuth' => 1]);
-
-        //还没有完成初始化先进行初始化
-        if (isset($extend['init']) && $extend['init'] == 0) {
-            $data = ['merchantId' => $id];
-            $producer = Yii::$app->rabbitmq->getProducer('openShopInitProducer');
-            $msg = serialize($data);
-            $producer->publish($msg, 'openShopInitExchange', 'openShopInitRoute');
-        }
-
-        echo 'ok';
-    }
-
-    public function actionResult()
-    {
-        $get = Yii::$app->request->get();
-        $id = isset($get['id']) ? $get['id'] : 0;
-        $merchant = xhMerchantService::getById($id);
-        $status = configDict::getConfig('merchantStatusName');
-        $orMechantId = configDict::getConfig('merchantId');
-        $originalMerchant = xhMerchantService::getById($orMechantId);
-        return $this->renderPartial('result', ['originalMerchant' => $originalMerchant, 'merchant' => $merchant, 'status' => $status]);
-    }
-
-    public function actionCheckInviteCode()
-    {
-        $get = Yii::$app->request->get();
-        $code = isset($get['code']) ? $get['code'] : '';
-        $invite = xhInviteService::getByCode($code);
-        if (empty($invite)) {
-            util::fail('邀请码错误');
-        }
-        $now = time();
-        if ($now > $invite['deadline']) {
-            util::fail('邀请码已经失效');
-        }
-        if (!empty($invite['takeStatus'])) {
-            util::fail('邀请码已经使用');
-        }
-        util::success($invite);
-    }
-
-    public function actionSelect()
-    {
-        $isWx = util::isWx();
-        if ($isWx == false) {
-            return $this->renderPartial('notWeixin');
-        }
-        return $this->renderPartial('select');
-    }
-
-    public function actionApi()
-    {
-        $openData = file_get_contents('php://input');
-        if (isset ($openData) == false || empty($openData)) {
-            util::stop('has no post data');
-        }
-        $weixinSecret = Yii::getAlias("@vendor/weixinSecret");
-        require_once($weixinSecret . '/wxBizMsgCrypt.php');
-        $get = Yii::$app->request->get();
-        $encryptMsg = $openData;
-        $openId = configDict::getConfig('openId');
-        $open = xhWxOpenService::getById($openId);
-        $encodingAesKey = $open['aesKey'];
-        $token = $open['token'];
-        $appId = $open['appId'];
-        $appSecret = $open['appSecret'];
-        $signature = isset($get['signature']) ? $get['signature'] : '';
-        $timestamp = isset($get['timestamp']) ? $get['timestamp'] : '';
-        $nonce = isset($get['nonce']) ? $get['nonce'] : '';
-        $encrypt_type = isset($get['encrypt_type']) ? $get['encrypt_type'] : '';
-        $msg_signature = isset($get['msg_signature']) ? $get['msg_signature'] : '';
-        $xml_tree = new \DOMDocument();
-        $xml_tree->loadXML($encryptMsg);
-        $array_e = $xml_tree->getElementsByTagName('Encrypt');
-        $encrypt = $array_e->item(0)->nodeValue;
-        $format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%s]]></Encrypt></xml>";
-        $from_xml = sprintf($format, $encrypt);
-
-        $formString = " token:" . $token . "\n encodingAesKey:" . $encodingAesKey . "\n appId:" . $appId . "\n msg_signature:" . $msg_signature . "\n appSecret:" . $appSecret . "\n timestamp:" . $timestamp . "\n nonce:" . $nonce;
-        Yii::warning($formString);
-
-        $formString2 = "from_xml:" . $from_xml;
-        Yii::warning($formString2);
-
-        //第三方收到公众号平台发送的消息
-        $pc = new \WXBizMsgCrypt($token, $encodingAesKey, $appId);
-        $msg = '';//解密后的消息
-        $errCode = $pc->decryptMsg($msg_signature, $timestamp, $nonce, $from_xml, $msg);
-        if ($errCode != 0) {
-            Yii::warning("解密未成功,错误代码:" . $errCode . "。(出现过的情况汇总:-40001 有可能token、encodingAesKey、appId等填写不对,请仔细核对每个值)");
-            util::stop();
-        }
-        $postObj = simplexml_load_string($msg, 'SimpleXMLElement', LIBXML_NOCDATA);
-        $infoType = $postObj->InfoType;
-        switch ($infoType) {
-            //推送 componentVerifyTicket
-            case 'component_verify_ticket':
-                $componentVerifyTicket = $postObj->ComponentVerifyTicket;
-                if (!empty($componentVerifyTicket)) {
-                    $oData = [];
-                    $oData['verifyTicket'] = (string)$componentVerifyTicket;
-                    $oData['verifyTicketTime'] = date("Y-m-d H:i:s", $timestamp + 600);//每10分钟(600秒)推一次
-                    xhWxOpenService::updateById($openId, $oData);
-                    Yii::warning("component_verify_ticket:" . (string)$componentVerifyTicket);
-                    util::stop('success');
-                }
-                break;
-            //取消授权通知
-            case 'unauthorized':
-                $AppId = $postObj->AppId;
-                $authorizeAppid = $postObj->AuthorizerAppid;
-                $merchant = xhMerchantService::getByAppId($authorizeAppid);
-                if (!empty($merchant)) {
-                    $merchantId = $merchant['id'];
-                    //自主冻结
-                    xhMerchantService::updateById($merchantId, ['status' => 5]);
-                }
-                break;
-            //授权成功通知
-            case 'authorized':
-                $AppId = $postObj->AppId;//第三方平台appid
-                $CreateTime = $postObj->CreateTime;//公众号
-                $authorizeAppid = $postObj->AuthorizerAppid;//授权码,可用于换取公众号的接口调用凭据,详细见上面的说明
-                $AuthorizationCode = $postObj->AuthorizationCode;
-                $AuthorizationCodeExpiredTime = $postObj->AuthorizationCodeExpiredTime;//授权码过期时间
-                break;
-            //授权更新通知
-            case 'updateauthorized':
-                $AppId = $postObj->AppId;
-                $CreateTime = $postObj->CreateTime;
-                $authorizeAppid = $postObj->AuthorizerAppid;
-                $AuthorizationCode = $postObj->AuthorizationCode;
-                $AuthorizationCodeExpiredTime = $postObj->AuthorizationCodeExpiredTime;
-
-                util::stop();
-
-                $authorize = wxUtil::getAuthorizer($AuthorizationCode);
-                if (isset($authorize['authorization_info']) == false) {
-                    $msg = '授权回调获取到auth_code,但未换取公众号的接口调用凭据和授权信息!!';
-                    Yii::warning($msg, __METHOD__);
-                    Yii::$app->end();
-                }
-                $info = $authorize['authorization_info'];
-                $authorizeAppId = $info['authorizer_appid'];
-                $authorize_access_token = $info['authorizer_access_token'];
-                $expires_in = $info['expires_in'];//7200
-                $authorize_refresh_token = $info['authorizer_refresh_token'];
-                $merchant = xhMerchantService::getByAppId($authorizeAppId);
-                if (empty($merchant)) {
-                    return false;
-                }
-                $merchantId = $merchant['id'];
-                $wxData = [];
-                $wxData['wxAccessToken'] = $authorize_access_token;
-                $wxData['wxRefreshToken'] = $authorize_refresh_token;
-                $wxData['wxAccessTokenTime'] = date("Y-m-d H:i:s", (time() + $expires_in - 100));
-                $wxData['status'] = 1;
-                xhMerchantService::updateById($merchantId, $wxData);
-                break;
-            default:
-        }
-        Yii::warning("---wx open data end--- \n");
-    }
-
-    //获取平台信息 shish 2020.4.12
-    public function actionGetWxOpen()
-    {
-        $open = WxOpenService::getOpen();
-        util::success($open);
-    }
-
+	
+	public $withoutLogin = ['bind-open'];
+	
+	public function actionBindOpen()
+	{
+		$merchantId = Yii::$app->request->get('merchantId', 0);
+		$merchant = MerchantService::getMerchantById($merchantId);
+		if (empty($merchant)) {
+			util::fail('没有找到商家');
+		}
+		$wxAppId = $merchant['wxAppId'];
+		$miniAppId = $merchant['miniAppId'];
+		$open_appid = $merchant['openAppId'];
+		
+		echo "<pre>";
+		
+		$id = Yii::$app->request->get('id', 0);
+		//创建平台,并将公众号绑定到平台
+		if ($id == 1) {
+			wxUtil::createOpenAccount($wxAppId, $merchant);
+			$return = wxUtil::getOpenAccount($wxAppId, $merchant);
+			print_r($return);
+			if ($return['errcode'] == 0) {
+				$openAppId = $return['open_appid'];
+				MerchantService::updateById($merchantId, ['openAppId' => $openAppId]);
+				MerchantExtendService::updateByCondition(['merchantId' => $merchantId], ['openAppId' => $openAppId, 'openAppBind' => 1, 'wxAuth' => 1]);
+			}
+		}
+		//将小程序绑定到平台
+		if ($id == 2) {
+			$openAppId = $merchant['openAppId'];
+			$r = wxUtil::bindOpenAccount($miniAppId, $openAppId, $merchant, true);
+			MerchantExtendService::updateByCondition(['merchantId' => $merchantId], ['openAppBind' => 3, 'miniAuth' => 1]);
+			print_r($r);
+		}
+		//查询公众号 小程序的绑定情况
+		if ($id == 3) {
+			$return = wxUtil::getOpenAccount($wxAppId, $merchant);
+			print_r($return);
+			$return = wxUtil::getOpenAccount($miniAppId, $merchant, true);
+			print_r($return);
+		}
+		
+		//设置小程序服务器域名
+		if ($id == 4) {
+			wxUtil::setDomain($merchant);
+			wxUtil::setWebViewDomain($merchant);
+		}
+		
+		//为授权的小程序帐号上传小程序代码
+		if ($id == 5) {
+			$tId = $_GET['tId'];
+			wxUtil::miniCommit($merchant, $tId);
+		}
+		
+		//获取小程序体验码
+		if ($id == 6) {
+			wxUtil::getExperienceQrCode($merchant);
+		}
+		
+		//获取授权小程序帐号已设置的类目
+		if ($id == 7) {
+			wxUtil::getMiniCategory($merchant);
+		}
+		
+		//获取小程序的第三方提交代码的页面配置
+		if ($id == 8) {
+			wxUtil::getMiniPage($merchant);
+		}
+		
+		//将第三方提交的代码包提交审核
+		if ($id == 9) {
+			wxUtil::miniSubmitAudit($merchant);
+		}
+		
+		//查询最新一次提交的审核状态
+		if ($id == 10) {
+			wxUtil::miniGetLatestAuditStatus($merchant);
+		}
+		
+		//发布已通过审核的小程序
+		if ($id == 11) {
+			$r = MiniProgramService::release($merchant);
+			print_r($r);
+		}
+		
+		//撤回审核
+		if ($id == 12) {
+			wxUtil::rollbackCheck($merchant);
+		}
+		//生成 申请会员页 的小程序码
+		if ($id == 13) {
+			wxUtil::generateMemberCode($merchant);
+		}
+		//解绑小程序和公众号绑定的平台
+		if ($id == 14) {
+			wxUtil::unbindAccount($merchant);
+			wxUtil::unbindMiniProgram($merchant);
+		}
+		Yii::$app->end();
+		
+		$r = wxUtil::bindOpenAccount($miniAppId, $open_appid, $merchant, true);
+		print_r($r);
+		echo $miniAppId . ' ' . $open_appid . ' ';
+		
+		$return = wxUtil::getOpenAccount($wxAppId, $merchant);
+		print_r($return);
+		die;
+		
+		$return = wxUtil::createOpenAccount($wxAppId, $merchant);
+		print_r($return);
+		die;
+		
+		$r = wxUtil::bindOpenAccount($miniAppId, $open_appid, $merchant);
+		print_r($r);
+		echo $miniAppId . ' ' . $open_appid . ' ';
+		
+		$return = wxUtil::getOpenAccount($wxAppId, $merchant);
+		print_r($return);
+		$return = wxUtil::getOpenAccount($miniAppId, $merchant);
+		print_r($return);
+		die;
+		
+		if ($return['errcode'] == 0) {
+			$open_appid = isset($return['open_appid']) ? $return['open_appid'] : '';
+		} else {
+			$return = wxUtil::createOpenAccount($wxAppId, $merchant);
+			if ($return['errcode'] == 0) {
+				$open_appid = isset($return['open_appid']) ? $return['open_appid'] : '';
+			}
+		}
+		echo "<br />open_appid:" . $open_appid . "<br />";
+		if (!empty($open_appid)) {
+			xhMerchantService::updateById($merchantId, ['openAppId' => $open_appid]);
+			MerchantExtendService::updateByCondition(['merchantId' => $merchantId], ['openAppId' => $open_appid, 'openAppBind' => 3, 'miniAuth' => 1]);
+			$r = wxUtil::bindOpenAccount($miniAppId, $open_appid, $merchant);
+			echo "绑定小程序结果:<br />";
+			print_r($r);
+		}
+		echo "<br /><br />";
+		$return = wxUtil::getOpenAccount($wxAppId, $merchant);
+		echo "微信appId:{$wxAppId}<br />";
+		print_r($return);
+		$return = wxUtil::getOpenAccount($miniAppId, $merchant);
+		echo "<br />小程序appId:{$miniAppId}<br />";
+		print_r($return);
+	}
+	
+	//开放平台开始授权 shish 2020.1.16
+	public function actionBeginAuth()
+	{
+		$merchantId = Yii::$app->request->get('id', 0);
+		$open = WxOpenService::getOpen();
+		//1只显示公众号 2只显示小程序  3显示公众号和小程序
+		$authType = Yii::$app->request->get('authType', 3);
+		$pre = wxUtil::getPreAuthCode($open);
+		$appId = $open['appId'];
+		$oData = [];
+		$oData['preAuthCodeTime'] = date("Y-m-d H:i:s");
+		//设置预授码过期,让下个用户可以获取新的预授码
+		xhWxOpenService::updateById(1, $oData);
+		$url = Yii::$app->params['saasHost'] . '/wx-open-callback/' . $merchantId;
+		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>";
+	}
+	
+	//平台没有绑定商家公众号时初始化一个商家 shish 2020.2.11
+	public function actionAddMerchant()
+	{
+		AdClass::initAdd(12362);
+		$return = MerchantService::initOpenMerchant();
+		dd($return);
+	}
+	
+	public function actionCheckMerchantName()
+	{
+		$get = Yii::$app->request->get();
+		$merchantName = isset($get['merchantName']) ? $get['merchantName'] : '';
+		$m = xhMerchantService::getByMerchantName($merchantName);
+		if (!empty($m)) {
+			util::fail('公众号名称已经使用');
+		}
+		util::complete();
+	}
+	
+	/**
+	 * 下载微信里的图片到服务器
+	 */
+	public function actionDownloadWxImg()
+	{
+		$get = Yii::$app->request->get();
+		$mediaId = isset($get['mediaId']) ? $get['mediaId'] : '';
+		$imgList = wxUtil::downloadmediaIdImg($this->merchant, $mediaId);
+		if (!empty($imgList)) {
+			util::success($imgList);
+		}
+		util::fail();
+	}
+	
+	//创建平台使用的公众号
+	public function actionCallback()
+	{
+		$get = Yii::$app->request->get();
+		if (isset($get['auth_code']) == false) {
+			util::stop('公众号授权回调未成功');
+		}
+		$id = isset($get['id']) ? $get['id'] : 0;
+		$code = $get['auth_code'];
+		//使用授权码换取公众号的接口调用凭据和授权信息
+		$authorize = wxUtil::getAuthorizer($code);
+		if (isset($authorize['authorization_info']) == false) {
+			util::stop('未换取公众号的接口调用凭据和授权信息');
+		}
+		$info = $authorize['authorization_info'];
+		$authorizeAppId = $info['authorizer_appid'];
+		$authorize_access_token = $info['authorizer_access_token'];
+		$expires_in = $info['expires_in'];//7200
+		$authorize_refresh_token = $info['authorizer_refresh_token'];
+		//获取授权方的公众号帐号基本信息
+		$authorizeDetailInfo = wxUtil::getAuthorizerInfo($authorizeAppId);
+		if (isset($authorizeDetailInfo['authorizer_info']) == false) {
+			util::stop('没有获取到公众号帐号基本信息');
+		}
+		$authorize_info = $authorizeDetailInfo['authorizer_info'];
+		//$nick_name = $authorize_info['nick_name'];
+		$head_img = $authorize_info['head_img'];
+		$service_type_info = $authorize_info['service_type_info'];
+		if ($service_type_info['id'] != 2) {
+			if (isset($authorize_info['MiniProgramInfo']) == false || empty($authorize_info['MiniProgramInfo'])) {
+				util::stop('公众号不是服务号');
+			}
+		}
+		$verify_type_info = $authorize_info['verify_type_info'];
+		if ($verify_type_info['id'] != 0) {
+			if (isset($authorize_info['MiniProgramInfo']) == false || empty($authorize_info['MiniProgramInfo'])) {
+				util::stop('公众号还没有认证哦');
+			}
+		}
+		$user_name = $authorize_info['user_name'];
+		$alias = $authorize_info['alias'];
+		$qrCodeUrl = $authorize_info['qrcode_url'];
+		$accessTokenTime = date("Y-m-d H:i:s", (time() + $expires_in - 100));//安全起见,将过期时间设置得比微信里还短100秒
+		
+		//开放平台还没有关联公众号,先将开放平台关联公众号
+		$open = WxOpenService::getOpen();
+		if (isset($open['merchantId']) && empty($open['merchantId'])) {
+			WxOpenService::updateById(1, ['merchantId' => $id]);
+		}
+		
+		$extend = MerchantExtendClass::getByMerchantId($id);
+		
+		if (isset($authorize_info['MiniProgramInfo']) && !empty($authorize_info['MiniProgramInfo'])) {
+			if (isset($extend['miniAppId']) && !empty($extend['miniAppId'])) {
+				if ($extend['miniAppId'] != $authorizeAppId) {
+					util::stop('授权的小程序与商家已绑定的小程序不一致');
+				}
+			} else {
+				util::stop('数据库请先填写小程序 miniAppId miniAppSecret');
+			}
+		} else {
+			if (isset($extend['wxAppId']) && !empty($extend['wxAppId'])) {
+				if ($extend['wxAppId'] != $authorizeAppId) {
+					util::stop('授权的公众号与商家已绑定的公众号不一致');
+				}
+			}
+		}
+		
+		$open = WxOpenService::getOpen();
+		
+		//小程序
+		if (isset($authorize_info['MiniProgramInfo']) && !empty($authorize_info['MiniProgramInfo'])) {
+
+			$miniData = [
+				'miniAppId' => $authorizeAppId,
+				'miniAuth' => 1,
+				'miniAccessToken' => $authorize_access_token,
+				'miniAccessTokenTime' => $accessTokenTime,
+				'miniRefreshToken' => $authorize_refresh_token,
+			];
+
+			//开放平台没有小程序先绑定开放平台要用的小程序
+			if (isset($open['wx_mini_base_id']) == false || empty($open['wx_mini_base_id'])) {
+				$miniData['addTime'] = $time;
+				$wxMiniBaseRespond = WxMiniBaseService::add($wxData);
+				$wxMiniBaseId = $wxMiniBaseRespond['id'];
+				WxOpenService::updateOpen(['wx_mini_base_id' => $wxMiniBaseId]);
+				util::stop('ok');
+			}
+
+			xhMerchantExtendService::updateByMerchantId($id, $miniData);
+			MerchantService::updateById($id, ['miniAppId' => $authorizeAppId]);
+			Yii::info('小程序信息更新成功:' . json_encode($authorize_info));
+			util::stop("小程序信息更新成功");
+		}
+
+		$wxData = [];
+		$appData['wxUserName'] = $user_name;
+		$appData['wxAliasName'] = $alias;
+		//公众号logo
+		$wxData['logo'] = WxBaseClass::saveLogo($head_img, $id);
+		//公众号二维码
+		$wxData['wxQrCodeUrl'] = WxBaseClass::saveQrCode($qrCodeUrl, $id);
+		$wxData['wxAppId'] = $authorizeAppId;
+		$wxData['wxAccessToken'] = $authorize_access_token;
+		$wxData['wxAccessTokenTime'] = $accessTokenTime;
+		$wxData['wxRefreshToken'] = $authorize_refresh_token;
+		$time = time();
+		//开放平台还没有公众号先绑定开放平台的公众号
+		if (isset($open['wx_base_id']) == false || empty($open['wx_base_id'])) {
+			$wxData['addTime'] = $time;
+			$wxBaseRespond = WxBaseService::add($wxData);
+			$wxBaseId = $wxBaseRespond['id'];
+			WxOpenService::updateOpen(['wx_base_id' => $wxBaseId]);
+			util::stop('ok');
+		}
+		$wxData['status'] = 1;//审核通过
+		xhMerchantService::updateById($id, $wxData);
+		MerchantExtendClass::updateByCondition(['merchantId' => $id], ['wxAppId' => $authorizeAppId, 'wxAuth' => 1]);
+		
+		//还没有完成初始化先进行初始化
+		if (isset($extend['init']) && $extend['init'] == 0) {
+			$data = ['merchantId' => $id];
+			$producer = Yii::$app->rabbitmq->getProducer('openShopInitProducer');
+			$msg = serialize($data);
+			$producer->publish($msg, 'openShopInitExchange', 'openShopInitRoute');
+		}
+		echo 'ok';
+	}
+	
+	public function actionResult()
+	{
+		$get = Yii::$app->request->get();
+		$id = isset($get['id']) ? $get['id'] : 0;
+		$merchant = xhMerchantService::getById($id);
+		$status = configDict::getConfig('merchantStatusName');
+		$orMechantId = configDict::getConfig('merchantId');
+		$originalMerchant = xhMerchantService::getById($orMechantId);
+		return $this->renderPartial('result', ['originalMerchant' => $originalMerchant, 'merchant' => $merchant, 'status' => $status]);
+	}
+	
+	public function actionCheckInviteCode()
+	{
+		$get = Yii::$app->request->get();
+		$code = isset($get['code']) ? $get['code'] : '';
+		$invite = xhInviteService::getByCode($code);
+		if (empty($invite)) {
+			util::fail('邀请码错误');
+		}
+		$now = time();
+		if ($now > $invite['deadline']) {
+			util::fail('邀请码已经失效');
+		}
+		if (!empty($invite['takeStatus'])) {
+			util::fail('邀请码已经使用');
+		}
+		util::success($invite);
+	}
+	
+	public function actionSelect()
+	{
+		$isWx = util::isWx();
+		if ($isWx == false) {
+			return $this->renderPartial('notWeixin');
+		}
+		return $this->renderPartial('select');
+	}
+	
+	public function actionApi()
+	{
+		$openData = file_get_contents('php://input');
+		if (isset ($openData) == false || empty($openData)) {
+			util::stop('has no post data');
+		}
+		$weixinSecret = Yii::getAlias("@vendor/weixinSecret");
+		require_once($weixinSecret . '/wxBizMsgCrypt.php');
+		$get = Yii::$app->request->get();
+		$encryptMsg = $openData;
+		$openId = configDict::getConfig('openId');
+		$open = xhWxOpenService::getById($openId);
+		$encodingAesKey = $open['aesKey'];
+		$token = $open['token'];
+		$appId = $open['appId'];
+		$appSecret = $open['appSecret'];
+		$signature = isset($get['signature']) ? $get['signature'] : '';
+		$timestamp = isset($get['timestamp']) ? $get['timestamp'] : '';
+		$nonce = isset($get['nonce']) ? $get['nonce'] : '';
+		$encrypt_type = isset($get['encrypt_type']) ? $get['encrypt_type'] : '';
+		$msg_signature = isset($get['msg_signature']) ? $get['msg_signature'] : '';
+		$xml_tree = new \DOMDocument();
+		$xml_tree->loadXML($encryptMsg);
+		$array_e = $xml_tree->getElementsByTagName('Encrypt');
+		$encrypt = $array_e->item(0)->nodeValue;
+		$format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%s]]></Encrypt></xml>";
+		$from_xml = sprintf($format, $encrypt);
+		
+		$formString = " token:" . $token . "\n encodingAesKey:" . $encodingAesKey . "\n appId:" . $appId . "\n msg_signature:" . $msg_signature . "\n appSecret:" . $appSecret . "\n timestamp:" . $timestamp . "\n nonce:" . $nonce;
+		Yii::warning($formString);
+		
+		$formString2 = "from_xml:" . $from_xml;
+		Yii::warning($formString2);
+		
+		//第三方收到公众号平台发送的消息
+		$pc = new \WXBizMsgCrypt($token, $encodingAesKey, $appId);
+		$msg = '';//解密后的消息
+		$errCode = $pc->decryptMsg($msg_signature, $timestamp, $nonce, $from_xml, $msg);
+		if ($errCode != 0) {
+			Yii::warning("解密未成功,错误代码:" . $errCode . "。(出现过的情况汇总:-40001 有可能token、encodingAesKey、appId等填写不对,请仔细核对每个值)");
+			util::stop();
+		}
+		$postObj = simplexml_load_string($msg, 'SimpleXMLElement', LIBXML_NOCDATA);
+		$infoType = $postObj->InfoType;
+		switch ($infoType) {
+			//推送 componentVerifyTicket
+			case 'component_verify_ticket':
+				$componentVerifyTicket = $postObj->ComponentVerifyTicket;
+				if (!empty($componentVerifyTicket)) {
+					$oData = [];
+					$oData['verifyTicket'] = (string)$componentVerifyTicket;
+					$oData['verifyTicketTime'] = date("Y-m-d H:i:s", $timestamp + 600);//每10分钟(600秒)推一次
+					xhWxOpenService::updateById($openId, $oData);
+					Yii::warning("component_verify_ticket:" . (string)$componentVerifyTicket);
+					util::stop('success');
+				}
+				break;
+			//取消授权通知
+			case 'unauthorized':
+				$AppId = $postObj->AppId;
+				$authorizeAppid = $postObj->AuthorizerAppid;
+				$merchant = xhMerchantService::getByAppId($authorizeAppid);
+				if (!empty($merchant)) {
+					$merchantId = $merchant['id'];
+					//自主冻结
+					xhMerchantService::updateById($merchantId, ['status' => 5]);
+				}
+				break;
+			//授权成功通知
+			case 'authorized':
+				$AppId = $postObj->AppId;//第三方平台appid
+				$CreateTime = $postObj->CreateTime;//公众号
+				$authorizeAppid = $postObj->AuthorizerAppid;//授权码,可用于换取公众号的接口调用凭据,详细见上面的说明
+				$AuthorizationCode = $postObj->AuthorizationCode;
+				$AuthorizationCodeExpiredTime = $postObj->AuthorizationCodeExpiredTime;//授权码过期时间
+				break;
+			//授权更新通知
+			case 'updateauthorized':
+				$AppId = $postObj->AppId;
+				$CreateTime = $postObj->CreateTime;
+				$authorizeAppid = $postObj->AuthorizerAppid;
+				$AuthorizationCode = $postObj->AuthorizationCode;
+				$AuthorizationCodeExpiredTime = $postObj->AuthorizationCodeExpiredTime;
+				
+				util::stop();
+				
+				$authorize = wxUtil::getAuthorizer($AuthorizationCode);
+				if (isset($authorize['authorization_info']) == false) {
+					$msg = '授权回调获取到auth_code,但未换取公众号的接口调用凭据和授权信息!!';
+					Yii::warning($msg, __METHOD__);
+					Yii::$app->end();
+				}
+				$info = $authorize['authorization_info'];
+				$authorizeAppId = $info['authorizer_appid'];
+				$authorize_access_token = $info['authorizer_access_token'];
+				$expires_in = $info['expires_in'];//7200
+				$authorize_refresh_token = $info['authorizer_refresh_token'];
+				$merchant = xhMerchantService::getByAppId($authorizeAppId);
+				if (empty($merchant)) {
+					return false;
+				}
+				$merchantId = $merchant['id'];
+				$wxData = [];
+				$wxData['wxAccessToken'] = $authorize_access_token;
+				$wxData['wxRefreshToken'] = $authorize_refresh_token;
+				$wxData['wxAccessTokenTime'] = date("Y-m-d H:i:s", (time() + $expires_in - 100));
+				$wxData['status'] = 1;
+				xhMerchantService::updateById($merchantId, $wxData);
+				break;
+			default:
+		}
+		Yii::warning("---wx open data end--- \n");
+	}
+	
+	//获取平台信息 shish 2020.4.12
+	public function actionGetWxOpen()
+	{
+		$open = WxOpenService::getOpen();
+		util::success($open);
+	}
+	
 }

+ 16 - 0
biz/weixin/classes/WxMiniBaseClass.php

@@ -0,0 +1,16 @@
+<?php
+
+namespace biz\weixin\classes;
+
+use common\components\dirUtil;
+use Yii;
+use biz\base\classes\BaseClass;
+use yii\imagine\Image;
+use linslin\yii2\curl;
+
+class WxMiniBaseClass extends BaseClass
+{
+
+	public static $baseFile = '\biz\weixin\models\WxMiniBase';
+
+}

+ 11 - 5
biz/weixin/classes/WxOpenClass.php

@@ -9,20 +9,20 @@ use biz\base\classes\BaseClass;
 
 class WxOpenClass extends BaseClass
 {
-
+	
 	public static $baseFile = '\biz\weixin\models\WxOpen';
-
+	
 	//平台管理员的手机号
 	const ADMIN_MOBILE = 15280215347;
 	const PLATFORM_ACCOUNT = 12359;
 	const ID = 1;
-
+	
 	//取平台的帐号
 	public static function getPlatformAccount()
 	{
 		return self::PLATFORM_ACCOUNT;
 	}
-
+	
 	//获取平台基础信息 shish 2020.2.11
 	public static function getOpen()
 	{
@@ -34,7 +34,7 @@ class WxOpenClass extends BaseClass
 	{
 		return self::ADMIN_MOBILE;
 	}
-
+	
 	//获取平台微信信息
 	public static function getOpenInfo()
 	{
@@ -46,4 +46,10 @@ class WxOpenClass extends BaseClass
 		util::fail('没有找到平台信息');
 	}
 
+	//更新开放平台信息 shish 2020.4.13
+	public static function updateOpen($data)
+	{
+		self::updateById(self::ID, $data);
+	}
+	
 }

+ 13 - 0
biz/weixin/models/WxMiniBase.php

@@ -0,0 +1,13 @@
+<?php
+namespace biz\weixin\models;
+use biz\base\models\Base;
+
+class WxMiniBase extends Base
+{
+
+	public static function tableName()
+	{
+		return 'xhWxMiniBase';
+	}
+
+}

+ 17 - 0
biz/weixin/services/WxMiniBaseService.php

@@ -0,0 +1,17 @@
+<?php
+
+namespace biz\weixin\services;
+
+use biz\base\services\BaseService;
+use biz\weixin\classes\WxMenuClass;
+use biz\weixin\classes\WxOpenClass;
+use common\components\httpUtil;
+use common\components\tree;
+use Yii;
+
+class WxMiniBaseService extends BaseService
+{
+
+	public static $baseFile = '\biz\weixin\classes\WxMiniBaseClass';
+
+}

+ 10 - 5
biz/weixin/services/WxOpenService.php

@@ -8,31 +8,36 @@ use Yii;
 
 class WxOpenService extends BaseService
 {
-
+	
 	public static $baseFile = '\biz\weixin\classes\WxOpenClass';
-
+	
 	//获取平台基础信息 shish 2020.2.11
 	public static function getOpen()
 	{
 		return WxOpenClass::getOpen();
 	}
 
+	public static function updateOpen($data)
+	{
+		return WxOpenClass::updateOpen($data);
+	}
+	
 	//获取平台管理员手机号 shish 2020.3.4
 	public static function getAdminMobile()
 	{
 		return WxOpenClass::getAdminMobile();
 	}
-
+	
 	//取平台帐号 shish 2020.3.7
 	public static function getPlatformAccount()
 	{
 		return WxOpenClass::getPlatformAccount();
 	}
-
+	
 	//获取平台微信信息
 	public static function getOpenInfo()
 	{
 		return WxOpenClass::getOpenInfo();
 	}
-
+	
 }