| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399 |
- <?php
- /**
- * 重庆赤晓店信息科技有限公司
- * https://www.chixiaodian.com
- * Copyright (c) 2023 赤店商城 All rights reserved.
- */
- namespace app\modules\common\controllers;
- use app\models\AggregateQrcode;
- use app\models\MerchantInfo;
- use app\models\Option;
- use app\models\Store;
- use app\models\WechatConfig;
- use app\models\StoreMini;
- use app\models\StoreMiniAuth;
- use app\models\StoreMiniAuthIcp;
- use app\modules\admin\models\WechatThirdForm;
- use app\utils\WechatMerchant\Merchant;
- use yii\log\Logger;
- use yii\web\Controller;
- use EasyWeChat\Factory;
- use EasyWeChat\OpenPlatform\Server\Guard;
- use Symfony\Component\HttpFoundation\HeaderBag;
- use Symfony\Component\HttpFoundation\Request as SymfonyRequest;
- use app\modules\admin\models\AdminForm;
- use app\models\Admin;
- use yii\web\Response;
- include_once "./utils/Wechat/crypt/wxBizMsgCrypt.php";
- class WechatGetTicketController extends Controller
- {
- public function beforeAction($action) {
- if (parent::beforeAction($action)) {
- $params = all_params();
- if(isset($params['echostr'])){
- \Yii::$app->response->format = Response::FORMAT_RAW;
- \Yii::$app->response->content = $params['echostr'];
- return false;
- }
- return true;
- }
- }
- //从服务市场登陆
- public function actionFuwuBuyerLogin(){
- $code = input_params('code', '');
- $cacheK = 'actionFuwuBuyerLogin_' . $code;
- $cacheV = cache()->get($cacheK);
- if($cacheV){
- echo '登陆太频繁,请等待一分钟后重试。';
- return;
- }
- cache()->set($cacheK, 1, 60);
- $form = new WechatThirdForm();
- $res = $form->servicemarketAuthCode($code);
- if($res['code'] != 0){
- echo '登陆失败,' . $res['msg'];
- return;
- }
- $mini = $res['data']['mini'];
- $store_id = $mini['store_id'];
- if(!$store_id){
- echo '登陆失败,店铺查找失败';
- return;
- }
- $admin = Admin::findOne(['type' => 'store', 'type_id' => $store_id, 'is_enable' => 1, 'is_delete' => 0]);
- if(!$admin){
- echo '登陆失败,管理员查找失败';
- return;
- }
- $model = new AdminForm();
- $model->username = $admin['username'];
- $model->loginType = 'username';
- $token = $model->generateToken(86400 * 100, $store_id);
- $data = [
- 'access_token' => $token,
- 'is_saas' => \Yii::$app->isSaas(),
- ];
- $cyy_code = 'cyy_code_login_' . $store_id . md5(time());
- cache()->set($cyy_code, $data, 60 * 3);
- $this->redirect(\Yii::$app->request->hostInfo . \Yii::$app->params['module_admin_login_uri'] . '?cyy_code=' . $cyy_code . '&redirect=' . urlencode(\Yii::$app->params['module_admin_login_uri'].'videoMarketing/manage'));
- }
- public function actionIndex(){
- $config = [
- 'app_id' => Option::get("platform_third_appid",0,'saas')['value'],
- 'secret' => Option::get("platform_third_secret",0,'saas')['value'],
- 'token' =>Option::get("platform_token",0,'saas')['value'],
- 'aes_key' => Option::get("platform_encodingAesKey",0,'saas')['value']
- ];
- $openPlatform = Factory::openPlatform($config);
- $request = \Yii::$app->req;
- if (\RUN_MODE == 'wokerman') {
- $symfony_request = new SymfonyRequest($request->get(), $request->post(), [], $request->cookie(), [], [], $request->rawBody());
- $symfony_request->headers = new HeaderBag($request->header());
- $openPlatform->rebind('request', $symfony_request);
- }
- $server = $openPlatform->server;
- $msg = $server->getMessage();
- \Yii::error($msg, '小程序审核通过回调');
- debug_log(['小程序审核通过回调', $msg], __CLASS__ . '.log');
- $server->push(function($msg) {
- if ($msg['InfoType'] == 'authorized' || $msg['InfoType'] == 'updateauthorized') {
-
- $appid = $msg['AuthorizerAppid'] ;
- $auth_code = $msg['AuthorizationCode'] ;
- $ExpiredTime = $msg['AuthorizationCodeExpiredTime'] ;
- $mini = StoreMini::find()->where(['appid'=>$appid])->one();
- $mini->auth_code = json_encode([
- 'authorization_code'=>$auth_code,
- 'end_time'=>time()*1 + $ExpiredTime*1
- ]);
- $mini->save();
- }
- if ($msg['InfoType'] == 'unauthorized') {
-
- $appid = $msg['AuthorizerAppid'];
- $mini = StoreMini::find()->where(['appid' => $appid])->one();
- $mini->is_cancle = 1;
- $mini->save();
- }
- // 小程序备案信息也会发送在这里
- // 小程序管理员人脸核身完成事件
- if ($msg['InfoType'] == 'notify_icpfiling_verify_result') {
- $storeMiniAuthIcp = StoreMiniAuthIcp::findOne(['task_id' => $msg['task_id']]);
- if (!intval($storeMiniAuthIcp->face_is_finish)) {
- if (in_array($msg['result'], [StoreMiniAuthIcp::FACE_STATUS_SUCCESS, StoreMiniAuthIcp::FACE_STATUS_FAIL])) {
- $storeMiniAuthIcp->face_status = $msg['result'];
- } elseif (intval($msg['result']) == StoreMiniAuthIcp::FACE_STATUS_INIT) {//超时未完成核验 需要重新提交
- $storeMiniAuthIcp->task_id = '';
- }
- if (isset($msg['along_with_auth_result'])) {
- $storeMiniAuthIcp->face_along_with_auth_result = $msg['along_with_auth_result'];
- }
- $storeMiniAuthIcp->save();
- }
- }
- //小程序认证审核费用支付完成的事件
- if ($msg['InfoType'] == 'notify_3rd_wxa_auth_and_icp') {
- if (isset($msg['procedure_id'])) {
- $storeMiniAuthIcp = StoreMiniAuthIcp::findOne(['procedure_id' => $msg['procedure_id']]);
- }
- if (isset($msg['taskid'])) {
- $storeMiniAuthIcp = StoreMiniAuthIcp::findOne(['task_id' => $msg['taskid']]);
- }
- if (!empty($storeMiniAuthIcp)) {
- //兼容提交时候报错 但是微信已经提交成功
- $storeMiniAuthIcp->procedure_status = $msg['procedure_status'];
- $storeMiniAuthIcp->save();
- } else {
- //兼容提交时候报错 但是微信已经提交成功
- if (isset($msg['appid'])) {
- $mini_id_list = StoreMini::find()->where(['appid' => $msg['appid'], 'is_cancle' => 0])
- ->select('id')->column();
- if ($mini_id_list) {
- StoreMiniAuthIcp::updateAll(['procedure_status' => $msg['procedure_status'], 'procedure_id' => $msg['procedure_id']], ['mini_id' => $mini_id_list]);
- }
- }
- }
- }
- });
- $server->push(function($msg) {
-
- $code = $msg['info']['code'];
-
- $mini = StoreMini::find()->where([
- 'code'=>$code
- ])->orderBy(['id' => SORT_DESC])->one();
- $mini->status = $msg['status'] == 0 ? 1 : 2;
- $mini->auth_code = json_encode([
- 'authorization_code' => $msg['auth_code'],
- 'end_time' => time() * 1 + 3600 * 1
- ]);
- $mini->msg = '状态码:'.$msg['status'].' 状态信息:'.$msg['msg'];
- $mini->fail_time = time();
- $mini->appid = $msg['appid'];
- \Yii::error([__METHOD__, $mini->status, $msg]);
- $mini->save();
- \Yii::error([__METHOD__, $mini]);
- if($msg['status'] == "0"){
- $form = new WechatThirdForm();
- $form->authorization_code = $msg['auth_code'];
- $form->mini_id = $mini->id;
- $form->store_id = $mini->store_id;
- $res = $form->getAuthorization_info($msg['auth_code']);
- $qrcode = AggregateQrcode::find()->where(['store_id' => $mini->store_id ])->one();
- if ($qrcode) {
- $qrcode->wx_mini_id = $mini->id;
- $res = $qrcode->save();
- }
-
- }
- \app\modules\alliance\models\store\SalesmanNewStoreForm::wechatPush($msg, $mini);
- }, Guard::EVENT_THIRD_FAST_REGISTERED);
- try {
- $server->push(function($msg) {
- if ($msg['InfoType'] == 'notify_3rd_wxa_auth') {
- $taskid = $msg['taskid'];
- $task_status = $msg['task_status'];
- $apply_status = $msg['apply_status'];
- $message = $msg['message'];
- $dispatch_info = $msg['dispatch_info'];
- $store_mini_auth = \app\models\StoreMiniAuth::findOne(['task_id' => $taskid]);
- $store_mini_auth->task_status = $task_status;
- if ($apply_status) {
- $store_mini_auth->apply_status = $apply_status;
- }
- if (in_array($task_status, [1, 2, 5, 8, 11, 14]) || in_array($apply_status, [3, 5])) {
- if ($store_mini_auth->is_use_service) {
- $store_mini_auth->is_use_service = 0;
- $store = Store::findOne($store_mini_auth->store_id);
- if (!$store) {
- throw new \Exception('店铺不存在');
- }
- $store->mini_auth_num += 1;
- if (!$store->save()) {
- throw new \Exception(json_encode($store->errors, JSON_UNESCAPED_UNICODE));
- }
- }
- }
- if ($dispatch_info) {
- $provider = $dispatch_info['provider'];
- $contact = $dispatch_info['contact'];
- $dispatch_time = $dispatch_info['dispatch_time'];
- $store_mini_auth->provider = $provider;
- $store_mini_auth->contact = $contact;
- $store_mini_auth->dispatch_time = $dispatch_time;
- $message = $message . ":" . $provider . ";" . $contact . ";" . date('Y-m-d H:i:s', $dispatch_time) . ";";
- }
- $store_mini_auth->task_message = $message;
- $store_mini_auth->save();
- }
- //测试数据
- if (isset($msg['Event'])) {
- debug_log($msg, 'event.log');
- }
- });
- } catch (\Throwable $e) {
- debug_log(['code' => $e->getCode(), 'message' => $e->getMessage()], 'event.log');
- }
- $server->push(function($msg) {
- //判断是否解密成功 成功则存储设置component_verify_ticket
- $ticket = $msg['ComponentVerifyTicket'];
- Option::set("component_verify_ticket",$ticket,0,'saas');
- }, Guard::EVENT_COMPONENT_VERIFY_TICKET);
- $server->serve();
- return 'success';
- }
- //消息与事件接收
- public function actionCallback(){
- if(\Yii::$app->prod_is_duli()){
- $app = \app\utils\Wechat\WechatMini::getWechatConfig(1);
- // $app->config->set('token', 'weixin');
- // $app->config->set('aes_key', '2XJmAod7fTYTjQ9rr4vw730VsKlr7DYOYr9IacLEi6a');
- // var_dump($app->getConfig(), $app->access_token->getToken(), get_params(), post_params());die;
- }else{
- $config = [
- 'app_id' => Option::get("platform_third_appid",0,'saas')['value'],
- 'secret' => Option::get("platform_third_secret",0,'saas')['value'],
- 'token' =>Option::get("platform_token",0,'saas')['value'],
- 'aes_key' => Option::get("platform_encodingAesKey",0,'saas')['value']
- ];
- $app = Factory::openPlatform($config);
- }
- $request = \Yii::$app->req;
- if (\RUN_MODE == 'wokerman') {
- $symfony_request = new SymfonyRequest($request->get(), $request->post(), [], $request->cookie(), [], [], $request->rawBody());
- $symfony_request->headers = new HeaderBag($request->header());
- $app->rebind('request', $symfony_request);
- }
- $server = $app->server;
- try{
- $msg = $server->getMessage();
- } catch (\Exception $e){
- \Yii::error($e);
- return 'err0';
- }
- $appid = get_params('appid');
- $file_name = \Yii::$app->runtimePath . '/logs/app_wechat.log';
- file_put_contents($file_name, "\r\n" . '[审核事件接受][' . date('Y-m-d H:i:s') . $appid . ']' . json_encode($msg), FILE_APPEND);
- // if (\RUN_MODE == 'wokerman') {
- // $text = $request->rawBody();
- // } else {
- // $text = file_get_contents("php://input");
- // }
- // $res = $this->base($text);
- // file_put_contents($file_name, "\r\n" . '[审核事件接受-old][' . date('Y-m-d H:i:s') . $appid . ']' . json_encode($res), FILE_APPEND);
- // if($res['errCode'] === 0){
-
- // $xml_tree = new \DOMDocument();
- // $xml_tree->loadXML($res['msg']);
- // $array_Event = $xml_tree->getElementsByTagName('Event');
- // $Event = $array_Event->item(0)->nodeValue;
- $Event = $msg['Event'];
- if ($Event == "weapp_audit_success") {//代码上传审核通过
- StoreMini::updateAll(['mini_up' => 2], ['appid'=>$appid]);
- } elseif ($Event == "weapp_audit_fail") {//代码上传审核不通过
- // $array_Reason = $xml_tree->getElementsByTagName('Reason');
- // $Reason = $array_Reason->item(0)->nodeValue;
- StoreMini::updateAll(['mini_up' => 3, 'mini_up_error' => $msg['Reason']], ['appid'=>$appid]);
- } elseif($Event == "weapp_audit_delay") {//代码上传审核延后
- StoreMini::updateAll(['mini_up' => 4], ['appid'=>$appid]);
- } elseif($Event == "retail_pay_notify") {
- \app\utils\Wechat\B2b\B2bPay::notify($msg);
- } elseif($Event == "retail_refund_notify") {
- return 'success';
- } elseif($Event == "wxa_nickname_audit") {//名称审核结果推送
- // $ret = $xml_tree->getElementsByTagName('ret')->item(0)->nodeValue;
- if ($msg['ret'] == 3) {
- StoreMini::updateAll(['apply_name_status' => 3, 'apply_name_error' => ''], ['appid'=>$appid]);
- $wechat = new WechatThirdForm();
- $wechat->getMiniInfo("",$appid);
- }
- if ($msg['ret'] == 2) {
- // $reason = $xml_tree->getElementsByTagName('reason')->item(0)->nodeValue;
- StoreMini::updateAll(['apply_name_status' => 2, 'mini_up' => 2, 'mini_up_error' => $msg['reason'], 'apply_name_error' => $msg['reason']], ['appid'=>$appid]);
- }
- }else{
- return 'err1';
- }
- // }
- }
- public function base($text){
-
- \Yii::getLogger()->log($text,Logger::LEVEL_ERROR);
- $token = Option::get("platform_token",0,'saas')['value'];
- $encodingAesKey = Option::get("platform_encodingAesKey",0,'saas')['value'];
- $appid = Option::get("platform_third_appid",0,'saas')['value'];
- if(!empty(get_params())){
- $getParam = get_params();
- }else{
- $getParam = post_params();
- }
- //解密
- $wx = new \WXBizMsgCrypt($token,$encodingAesKey,$appid);
- $xml_tree = new \DOMDocument();
- $xml_tree->loadXML($text);
- $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);
- $msg = "";
- $errCode = $wx->decryptMsg($getParam['msg_signature'],$getParam['timestamp'],$getParam['nonce'],$from_xml,$msg);
- return [
- 'errCode'=>$errCode,
- 'msg'=>$msg
- ];
- }
- }
|