123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304 |
- <?php
- namespace app\api\controller;
- use app\admin\model\PalmpaySplitAccountLog;
- use app\common\constants\BigData;
- use app\common\controller\Api;
- use app\common\library\Redis;
- use app\common\library\WeChatObject;
- use app\common\model\Orders;
- use app\common\service\CampaignService;
- use app\common\service\KuaifenService;
- use app\common\service\UserVipExtendService;
- use app\common\utility\WhiteList;
- use app\main\constants\AdminConstants;
- use app\main\constants\ApiConstants;
- use app\main\constants\CacheConstants;
- use app\main\constants\CampaignConstants;
- use app\main\constants\ErrorCodeConstants;
- use app\main\constants\KafkaDotConstants;
- use app\main\constants\MqConstants;
- use app\main\constants\OpenPlatformConstants;
- use app\main\constants\OrderContents;
- use app\main\constants\PayConstants;
- use app\main\constants\PostbackConstants;
- use app\main\constants\UcCacheConstants;
- use app\main\model\object\AnalysisObject;
- use app\main\model\object\DotBookCollectObject;
- use app\main\model\object\DotObject;
- use app\main\model\object\OrderObject;
- use app\main\model\object\UserObject;
- use app\main\service\ActivityService;
- use app\main\service\AdminKlService;
- use app\main\service\AdminService;
- use app\main\service\AliH5PayService;
- use app\main\service\ApiService;
- use app\main\service\BookDotService;
- use app\main\service\BookService;
- use app\main\service\BuyMoreService;
- use app\main\service\ExportFansService;
- use app\main\service\FinancialService;
- use app\main\service\FloatTipsService;
- use app\main\service\GdtMpApiService;
- use app\main\service\GdtService;
- use app\main\service\IpaynowPayService;
- use app\main\service\KafkaDotService;
- use app\main\service\LogService;
- use app\main\service\MihuaPayService;
- use app\main\service\MqService;
- use app\main\service\MqUserPaySuccessService;
- use app\main\service\OfficialAccountsEventService;
- use app\main\service\OfficialAccountsService;
- use app\main\service\OpenPlatformService;
- use app\main\service\OrderService;
- use app\main\service\ReferralService;
- use app\main\service\ReportKlService;
- use app\main\service\SinglePushService;
- use app\main\service\SmartPushDotService;
- use app\main\service\SubscripService;
- use app\main\service\ToutiaoNotifyService;
- use app\main\service\UcNotifyService;
- use app\main\service\UnsPayService;
- use app\main\service\UrlService;
- use app\main\service\UserService;
- use app\main\service\WeChatAdService;
- use app\main\service\WechatH5Payservice;
- use app\source\model\UserUpdate;
- use EasyWeChat\Factory;
- use EasyWeChat\Kernel\Support\XML;
- use EasyWeChat\OpenPlatform\Server\Guard;
- use Symfony\Component\Cache\Simple\RedisCache;
- use think\Config;
- use think\Log;
- use think\Request;
- class Wechat extends Api
- {
- /**
- * 检测权限
- * @param $authUser
- * @throws \Exception
- */
- private function checkWeChatAuth($authUser)
- {
- if (!isset($authUser['authorizer_info']['service_type_info']['id'])) {
- throw new \Exception('获取授权信息失败,请重新扫码授权');
- }
- if ($authUser['authorizer_info']['service_type_info']['id'] != 2) {
- throw new \Exception('当前授权公众号类型非服务号,请使用服务号进行扫码');
- }
- if ($authUser['authorizer_info']['verify_type_info']['id'] == -1) {
- throw new \Exception('当前授权服务号未认证,请使用认证服务号进行扫码');
- }
- $authList = array_column(array_column($authUser['authorization_info']['func_info'], 'funcscope_category'), 'id');
- if (empty($authList)) {
- throw new \Exception('获取授权信息失败');
- }
- if (!in_array(1, $authList)) {
- throw new \Exception('必须授予-消息管理权限');
- }
- if (!in_array(15, $authList)) {
- throw new \Exception('必须授予-自定义菜单权限');
- }
- if (!in_array(4, $authList)) {
- throw new \Exception('必须授予-网页服务权限');
- }
- if (!in_array(2, $authList)) {
- throw new \Exception('必须授予-用户管理权限');
- }
- if (!in_array(3, $authList)) {
- throw new \Exception('必须授予-帐号服务权限');
- }
- if (!in_array(11, $authList)) {
- throw new \Exception('必须授予-素材管理权限');
- }
- if(!in_array(23,$authList)){
- throw new \Exception('必须授予-广告管理权限');
- }
- }
- /**
- * 接收open开放平台事件通知
- */
- public function opticket()
- {
- Log::info('[ WeChat ] [ OPEN ] [ Ticket ] GET: ' . json_encode(var_export($this->request->get(), true),
- JSON_UNESCAPED_UNICODE));
- Log::info('[ WeChat ] [ OPEN ] [ Ticket ] INPUT: ' . json_encode(var_export($this->request->getInput(), true),
- JSON_UNESCAPED_UNICODE));
- $request = XML::parse($this->request->getInput());
- $result = OpenPlatformService::instance()->initPlatformByAppId($request['AppId']);
- if($result->code != ErrorCodeConstants::SUCCESS){
- $this->error($result->msg);
- }
- $openPlatform = OpenPlatformService::instance()->getOpenPlatform();
- $openPlatform['cache'] = new RedisCache(Redis::instanceCache());
- $server = $openPlatform->server;
- Log::info('[ WeChat ] [ OPEN ] [ Ticket ] Message: ' . json_encode(var_export($server->getMessage(), true),
- JSON_UNESCAPED_UNICODE));
- // 处理授权成功事件 //callback中已处理
- // $server->push(function ($message) {
- // }, Guard::EVENT_AUTHORIZED);
- // 处理授权更新事件
- $server->push(function ($message) use ($openPlatform) {
- try {
- $appid = $message['AuthorizerAppid'];
- $platformAppid = $message['AppId'];
- $authCode = $message['AuthorizationCode'];
- $auth = $openPlatform->handleAuthorize($authCode); // 使用授权码换取接口调用凭据和授权信息
- $mp = $openPlatform->getAuthorizer($appid); // 获取授权方的帐号基本信息
- //检测权限
- $this->checkWeChatAuth($mp);
- $data = [
- 'refresh_token' => $auth['authorization_info']['authorizer_refresh_token'],
- 'json' => $mp,
- 'is_auth' => 1,
- ];
- model('AdminConfig')->update($data, ['appid' => $appid]);
- //维护Ptoken信息
- if ($adminConfig = model('AdminConfig')->getAdminInfoByAppId($appid)) {
- if ($platform = model('Platform')->where(['appid' => $platformAppid])->find()) {
- $map = ['admin_id' => $adminConfig['admin_id'], 'platform_id' => $platform['id']];
- if (model('Ptoken')->where($map)->find()) {
- model('Ptoken')->where($map)->update(['refresh_token' => $auth['authorization_info']['authorizer_refresh_token'], 'updatetime' => time()]);
- } else {
- model('Ptoken')->insert(array_merge($map, ['refresh_token' => $auth['authorization_info']['authorizer_refresh_token'], 'createtime' => time(), 'updatetime' => time()]));
- }
- }
- }
- } catch (\Exception $e) {
- Log::info("API 授权更新回调错误,Error:" . $e->getMessage());
- }
- }, Guard::EVENT_UPDATE_AUTHORIZED);
- // 处理授权取消事件
- $server->push(function ($message) {
- try{
- $appid = $message['AuthorizerAppid'];
- $platformAppid = $message['AppId'];
- if ($appid != 'wx570bc396a51b8ff8') {
- $data = [
- 'is_auth' => 0,
- 'wx_ad_source_id' => 0,
- 'wx_ad_state' => 0
- ];
- model('AdminConfig')->update($data, ['appid' => $appid]);
- //维护Ptoken信息
- if ($adminConfig = model('AdminConfig')->getAdminInfoByAppId($appid)) {
- if ($platform = model('Platform')->where(['appid' => $platformAppid])->find()) {
- $map = ['admin_id' => $adminConfig['admin_id'], 'platform_id' => $platform['id']];
- if (model('Ptoken')->where($map)->find()) {
- model('Ptoken')->where($map)->delete();
- }
- }
- }
- }
- }catch (\Exception $e) {
- Log::info("API 取消授权回调错误,Error:" . $e->getMessage());
- }
- }, Guard::EVENT_UNAUTHORIZED);
- $server->serve()->send();
- LogService::info("REQUEST_TIME_END:".microtime(true));
- }
- /**
- * 初始化平台参数
- */
- public function initPlatform()
- {
- $mOphost = OfficialAccountsService::instance()->getOphostModel();
- $hosts = $mOphost->getHosts();
- $host = UrlService::instance()->getSourceDomain();
- if (in_array($host, $hosts) && $ophost = $mOphost->getInfoByHost($host)) {
- $result = OpenPlatformService::instance()->initPlatformById($ophost['platform_id']);
- if($result->code != ErrorCodeConstants::SUCCESS){
- $this->error($result->msg);
- }
- } else {
- LogService::info('API_LOG 未匹配到域名信息:' . $host . ':' . json_encode($hosts));
- }
- }
- /**
- * 接收mp公众平台消息与事件
- */
- public function mpapi($appid)
- {
- LogService::info('[ WeChat ] [ MP ] [ API ] GET: ' . json_encode(var_export($this->request->get(), true),
- JSON_UNESCAPED_UNICODE));
- LogService::info('[ WeChat ] [ MP ] [ API ] INPUT: ' . json_encode(var_export($this->request->getInput(), true),
- JSON_UNESCAPED_UNICODE));
- $this->initPlatform();
- try {
- if (in_array($appid, OpenPlatformConstants::$app_id_for_all)) { //全网发布处理
- OfficialAccountsEventService::instance()->eventForAllNet($appid);
- } else { //正常业务处理
- $result = OfficialAccountsEventService::instance()->eventForNormal($appid);
- if($result->msg){
- return;
- }
- }
- } catch (\Exception $e) {
- LogService::exception($e);
- }
- LogService::info("REQUEST_TIME_END:".microtime(true));
- OfficialAccountsEventService::instance()->processCallbackUserInfo($appid);
- }
- /**
- * 根据 admin_id 获取 appid,token
- */
- public function getToken()
- {
- $admin_id = $this->request->param('admin_id');
- $data = [];
- $errMsg = '';
- try {
- if (!$admin_id) {
- $this->error('缺少参数');
- }
- $adminConfig = model('AdminConfig')->getAdminInfoAll($admin_id);
- if (!$adminConfig) {
- $this->error('无此数据');
- }
- $wechat = new WeChatObject($adminConfig);
- $officialAccount = $wechat->getOfficialAccount();
- $token = $officialAccount->access_token->getToken();
- if (!is_array($token) || !array_key_exists('authorizer_access_token', $token)) {
- $errMsg = '获取token失败';
- } else {
- $proxy = OpenPlatformService::instance()->getProxyconfigByChannel($admin_id, null, 'job_proxy_config',true);
- $data = [
- 'appid' => $adminConfig['appid'],
- 'token' => $token['authorizer_access_token'],
- 'proxy_config' => $proxy ?: [],
- ];
- }
- } catch (\Exception $exception) {
- Log::info('API getToken触发异常!admin_id:' . $admin_id . ' message:' . $exception->getMessage());
- $this->error('获取异常'.json_encode(['errcode' => $exception->getCode(), 'errmsg' => $exception->getMessage()]));
- }
- if (!empty($data)) {
- exit(json_encode(['code' => 1, 'msg' => 'success', 'time' => time(), 'data' => $data], JSON_UNESCAPED_SLASHES));
- //$this->success('success', $data);
- } else {
- $this->error($errMsg);
- }
- }
- /**
- * 根据 admin_id 获取业务域名
- */
- public function getUrl()
- {
- $admin_id = $this->request->param('admin_id');
- $data = [];
- $errMsg = '';
- try {
- if (!$admin_id) {
- $this->error('缺少参数');
- }
- $info = model('AdminConfig')->getAdminInfoAll($admin_id);
- if (!empty($info) && $info['ophost_host']) {
- $data = [
- 'url' => $info['ophost_host'],
- ];
- } else {
- $errMsg = '获取业务域名失败!';
- }
- } catch (\Exception $exception) {
- Log::error('API getUrl触发异常!admin_id:' . $admin_id . ' message:' . $exception->getMessage());
- $this->error('获取异常'.json_encode(['errcode' => $exception->getCode(), 'errmsg' => $exception->getMessage()]));
- }
- if (!empty($data)) {
- $this->success('success', $data);
- } else {
- $this->error($errMsg);
- }
- }
- /**
- * 微信支付回调
- */
- public function pay()
- {
- Log::info('[ WeChat ] [ PAY ] [ CALLBACK ] GET: ' . json_encode(var_export($this->request->get(), true),
- JSON_UNESCAPED_UNICODE));
- Log::info('[ WeChat ] [ PAY ] [ CALLBACK ] INPUT: ' . json_encode(var_export($this->request->getInput(), true),
- JSON_UNESCAPED_UNICODE));
- $paymentApplication = Factory::payment(Config::get('wechat'));
- $paymentApplication['cache'] = new RedisCache(Redis::instanceCache());
- $parent_point = $this;
- $response = $paymentApplication->handlePaidNotify(function ($message, $fail) use ($parent_point) {
- Log::info('[ WeChat ] [ PAY ] [ CALLBACK ] Message: ' . json_encode(var_export($message, true),
- JSON_UNESCAPED_UNICODE));
- if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态,不代表支付状态
- if (isset($message['result_code']) && $message['result_code'] === 'SUCCESS') { // 用户是否支付成功
- $orders = model('Orders')->get(['out_trade_no' => $message['out_trade_no']]);
- if ($orders['state'] == 1) { // 已支付
- return true;
- }
- $parent_point->saveOrder($orders, $message['transaction_id'], '');
- Log::info(sprintf('wechatpay_callback_success!wxpay_id:%s,channel_id:%s,money:%s,good_id:%s,out_trade_no:%s'
- , $orders['wxpay_id'], $orders['admin_id'], $orders['money'], $orders['goods_id'],
- $orders['out_trade_no']));
- return true;
- } elseif (!isset($message['result_code']) || $message['result_code'] === 'FAIL') { // 用户支付失败
- return true;
- } else {
- return $fail('参数错误,请稍后再通知我');
- }
- } else {
- return $fail('通信失败,请稍后再通知我');
- }
- });
- $response->send();
- }
- /**
- * 四方支付回调
- */
- public function palmpay()
- {
- Log::info('[ palmpay ] [ PAY ] [ CALLBACK ] GET: ' . json_encode(var_export($this->request->get(), true),
- JSON_UNESCAPED_UNICODE));
- Log::info('[ palmpay ] [ PAY ] [ CALLBACK ] INPUT: ' . json_encode(var_export($this->request->getInput(), true),
- JSON_UNESCAPED_UNICODE));
- $params = $this->request->post();
- if (isset($params['status']) && $params['status'] === 'success') {
- $order = model('Orders')->get(['out_trade_no' => $params['outTradeNo']]);
- if ($order['state'] == 1) {
- Log::info('订单已经支付,out_trade_no:' . $params['outTradeNo']);
- return 'success';
- }
- $payInfo = model('Wxpay')->getInfoByHost($this->currentPayHost);
- if (empty($payInfo['quartet_app_key'])) {
- Log::error('quartet_app_key不存在');
- return 'quartet_app_key不存在';
- }
- $appKey = $payInfo['quartet_app_key'];
- if (!$this->_checkSign($params, $appKey)) {
- Log::error('sign校验失败');
- return 'sign校验失败';
- }
- Log::info(sprintf('palmpay_callback_success!wxpay_id:%s,channel_id:%s,money:%s,good_id:%s,out_trade_no:%s'
- , $order['wxpay_id'], $order['admin_id'], $order['money'], $order['goods_id'],
- $order['out_trade_no']));
- $this->saveOrder($order, $params['chorderid'], $params['pdorderid']);
- Log::info('订单支付回调成功,pdorderid:' . $params['pdorderid']);
- return 'success';
- } else {
- $status = empty($params['status']) ? -1 : $params['status'];
- Log::error('充值不成功,status:' . $status);
- return $status;
- }
- }
- /**
- * 汇聚支付回调
- */
- public function joinpay()
- {
- Log::info('[ joinpay ] [ PAY ] [ CALLBACK ] GET: ' . json_encode(var_export($this->request->get(), true),
- JSON_UNESCAPED_UNICODE));
- Log::info('[ joinpay ] [ PAY ] [ CALLBACK ] INPUT: ' . json_encode(var_export($this->request->getInput(), true),
- JSON_UNESCAPED_UNICODE));
- $params = $this->request->get();
- if (isset($params['r6_Status']) && $params['r6_Status'] == 100) {
- $order = model('Orders')->get(['out_trade_no' => $params['r2_OrderNo']]);
- if ($order['state'] == 1) {
- Log::info('订单已经支付,out_trade_no:' . $params['r2_OrderNo']);
- return 'success';
- }
- Log::info(sprintf('joinpay_callback_success!wxpay_id:%s,channel_id:%s,money:%s,good_id:%s,out_trade_no:%s'
- , $order['wxpay_id'], $order['admin_id'], $order['money'], $order['goods_id'],
- $order['out_trade_no']));
- $this->saveOrder($order, $params['r7_TrxNo'], '');
- Log::info('订单支付回调成功,transaction_id:' . $params['r7_TrxNo']);
- return 'success';
- } else {
- $status = empty($params['r6_Status']) ? -1 : $params['r6_Status'];
- Log::error('充值不成功,status:' . $status);
- return $status;
- }
- }
- public function mihuapay()
- {
- Config::set('app_trace', false);
- Log::info('[ mihuapay ] [ PAY ] [ CALLBACK ] GET: ' . json_encode(var_export($this->request->get(), true),
- JSON_UNESCAPED_UNICODE));
- Log::info('[ mihuapay ] [ PAY ] [ CALLBACK ] INPUT: ' . json_encode(var_export($this->request->getInput(),
- true),
- JSON_UNESCAPED_UNICODE));
- $params = $this->request->get();
- $pureHost = UrlService::instance()->getSourceDomain();
- $payInfo = model('Wxpay')->getInfoByHost($pureHost);
- if (empty($payInfo)) {
- Log::error('回调域名对应的支付信息不存在。host:' . $pureHost);
- return '';
- }
- $data = $params['data'];
- $mihuaService = MihuaPayService::instance($payInfo['quartet_app_key'],
- $payInfo['quartet_app_public_key']);
- $jsonStr = $mihuaService->decrypt($data);
- Log::info(sprintf('支付回调返回值明文:%s', $jsonStr));
- $result = json_decode($jsonStr, true);
- if ($mihuaService->checkSign($result)) {
- if ($result['orderStatus'] == 'SUCCESS') {
- $order = model('Orders')->get(['out_trade_no' => $result['orderId']]);
- if ($order['state'] == 1) {
- Log::info('订单已经支付,out_trade_no:' . $result['orderId']);
- return 'SUCCESS';
- }
- Log::info(sprintf('mihuapay_callback_success!wxpay_id:%s,channel_id:%s,money:%s,good_id:%s,out_trade_no:%s'
- , $order['wxpay_id'], $order['admin_id'], $order['money'], $order['goods_id'],
- $order['out_trade_no']));
- $transactionId = empty($result['bankOrderNo']) ? $result['mbOrderId'] : $result['bankOrderNo'];
- $this->saveOrder($order, $transactionId, '');
- Log::info('订单支付回调成功,transaction_id:' . $transactionId);
- return 'SUCCESS';
- } else {
- Log::error('米花支付回调失败,msg:' . $jsonStr);
- return '';
- }
- } else {
- Log::error('公钥验证签名出错,msg:' . $jsonStr);
- return '';
- }
- }
- public function unspay()
- {
- Config::set('app_trace', false);
- Log::info('[ unsapay ] [ PAY ] [ CALLBACK ] POST: ' . json_encode(var_export($this->request->post(), true),
- JSON_UNESCAPED_UNICODE));
- Log::info('[ unsapay ] [ PAY ] [ CALLBACK ] INPUT: ' . json_encode(var_export($this->request->getInput(),
- true),
- JSON_UNESCAPED_UNICODE));
- $params = $this->request->post();
- $pureHost = UrlService::instance()->getSourceDomain();
- $payInfo = model('Wxpay')->getInfoByHost($pureHost);
- if (empty($payInfo)) {
- Log::error('回调域名对应的支付信息不存在。host:' . $pureHost);
- return '';
- }
- $params['accountId'] = $payInfo['quartet_app_id'];
- $verifyResponseResult = UnsPayService::instance($payInfo['quartet_app_key'])->verifyCallbackMacParams($params);
- if (isset($params['result_code']) && $params['result_code'] == '0000' && $verifyResponseResult) {
- $order = model('Orders')->get(['out_trade_no' => $params['orderId']]);
- if ($order['state'] == 1) {
- Log::info('订单已经支付,out_trade_no:' . $params['r2_OrderNo']);
- $aResult = [
- 'result_code' => "000000",
- 'channel_refund_trade_no' => $order['transaction_id'],
- ];
- return json_encode($aResult);
- }
- Log::info(sprintf('unspay_callback_success!wxpay_id:%s,channel_id:%s,money:%s,good_id:%s,out_trade_no:%s'
- , $order['wxpay_id'], $order['admin_id'], $order['money'], $order['goods_id'],
- $order['out_trade_no']));
- $this->saveOrder($order, $params['channel_refund_trade_no']);
- Log::info('订单支付回调成功,transaction_id:' . $params['channel_refund_trade_no']);
- $aResult = [
- 'result_code' => "000000",
- 'channel_refund_trade_no' => $params['channel_refund_trade_no'],
- ];
- return json_encode($aResult);
- } else {
- Log::error('充值不成功,result_code:' . $params['result_code']);
- return $params['result_code'];
- }
- }
- public function ipaynowpay()
- {
- Config::set('app_trace', false);
- Log::info('[ ipaynowpay ] [ PAY ] [ CALLBACK ] POST: ' . json_encode(var_export($this->request->post(), true),
- JSON_UNESCAPED_UNICODE));
- Log::info('[ ipaynowpay ] [ PAY ] [ CALLBACK ] INPUT: ' . json_encode(var_export($this->request->getInput(),
- true), JSON_UNESCAPED_UNICODE));
- $strParams = $this->request->getInput();
- parse_str($strParams, $params);
- $payInfo = model('Wxpay')->getInfoByHost($this->currentPayHost);
- $verifyResult = IpaynowPayService::instance($payInfo['quartet_app_private_no'])->verifySign($params);
- if (isset($params['transStatus']) && $params['transStatus'] === 'A001' && $verifyResult) {
- $order = model('Orders')->get(['out_trade_no' => $params['mhtOrderNo']]);
- if ($order['state'] == 1) {
- Log::info('订单已经支付,out_trade_no:' . $params['mhtOrderNo']);
- return 'success=Y';
- }
- Log::info(sprintf('ipaynow_callback_success!wxpay_id:%s,channel_id:%s,money:%s,good_id:%s,out_trade_no:%s'
- , $order['wxpay_id'], $order['admin_id'], $order['money'], $order['goods_id'],
- $order['out_trade_no']));
- $this->saveOrder($order, $params['channelOrderNo'], $params['nowPayOrderNo']);
- Log::info('订单支付回调成功,mhtOrderNo:' . $params['mhtOrderNo']);
- return 'success=Y';
- } else {
- $status = empty($params['transStatus']) ? -1 : $params['transStatus'];
- Log::error('充值不成功,status:' . $status);
- return 'success=N';
- }
- }
- /**
- * 支付宝h5支付
- */
- public function alih5pay()
- {
- Log::info('[ WECHAT ] [ PAY ] [ CALLBACK ] GET: ' . json_encode(var_export($this->request->get(), true)));
- try {
- $alipay = AliH5PayService::instance()->init(ApiConstants::PAYMENT_METHOD_ALIPAYH5)->initPay();
- $data = $alipay->verify();
- LogService::debug('Alipay notify' . $data->toJson());
- $out_trade_no = $data->get("out_trade_no");
- $orders = model('Orders')->get(['out_trade_no' => $out_trade_no]);
- if ($orders['state'] != OrderContents::ORDER_STATE_PAID) { // 已支付
- $this->saveOrder($orders, $data->get('trade_no'));
- Log::info(sprintf('alih5pay_callback_success!wxpay_id:%s,channel_id:%s,money:%s,good_id:%s,out_trade_no:%s'
- , $orders['wxpay_id'], $orders['admin_id'], $orders['money'], $orders['goods_id'],
- $orders['out_trade_no']));
- }
- return $alipay->success()->send();
- } catch (\Exception $e) {
- LogService::exception($e);
- }
- }
- /**
- * 微信支付回调
- */
- public function wxh5pay()
- {
- Log::info('[ WeChat ] [ PAY ] [ CALLBACK ] GET: ' . json_encode(var_export($this->request->get(), true),
- JSON_UNESCAPED_UNICODE));
- Log::info('[ WeChat ] [ PAY ] [ CALLBACK ] INPUT: ' . json_encode(var_export($this->request->getInput(), true),
- JSON_UNESCAPED_UNICODE));
- try {
- $wxPay = WechatH5Payservice::instance()->init(ApiConstants::PAYMENT_METHOD_WECHATH5)->initPay();
- $data = $wxPay->verify();
- LogService::debug('wxPay notify' . $data->toJson());
- $out_trade_no = $data->get("out_trade_no");
- $orders = model('Orders')->get(['out_trade_no' => $out_trade_no]);
- if ($orders['state'] != OrderContents::ORDER_STATE_PAID) { // 已支付
- $this->saveOrder($orders, $data->get('trade_no'));
- Log::info(sprintf('alih5pay_callback_success!wxpay_id:%s,channel_id:%s,money:%s,good_id:%s,out_trade_no:%s'
- , $orders['wxpay_id'], $orders['admin_id'], $orders['money'], $orders['goods_id'],
- $orders['out_trade_no']));
- }
- return $wxPay->success()->send();
- } catch (\Exception $e) {
- LogService::exception($e);
- }
- }
- /**
- * 校验回调签名
- * @param $params post参数
- * @param $appKey
- * @return bool
- */
- private function _checkSign($params, $appKey)
- {
- if (!isset($params['sign'])) {
- Log::error('sign不存在');
- return false;
- }
- $arrSign = [];
- ksort($params);
- $originalSign = $params['sign'];
- foreach ($params as $k => $param) {
- if ($k == 'sign') {
- continue;
- }
- $strTmp = trim($k) . '=' . trim($param);
- $arrSign[] = $strTmp;
- }
- $arrSign[] = 'key=' . $appKey;
- $strSign = implode('&', $arrSign);
- $sign = md5($strSign);
- return $originalSign == $sign;
- }
- /**
- * 保存订单信息,并保存统计信息
- * @param $orders
- * @param string $transactionId 微信支付订单号
- * @param string $pdorderid 四方支付订单号
- */
- private function saveOrder(Orders $orders, $transactionId = '', $pdorderid = '')
- {
- $time = Request::instance()->server('REQUEST_TIME');
- $business = $orders->business_line??'0';
- $oOrder = (new OrderObject())->bind($orders->getData());
- $cacheKey = OrderService::instance()->getOrderCacheKey($oOrder)->data;
- LogService::debug("清除缓存:" . $cacheKey);
- Redis::instance()->delete($cacheKey);
- if (!OrderService::instance()->getOrderModel()->update([
- 'transaction_id' => $transactionId,
- 'pdorderid' => $pdorderid,
- 'state' => OrderContents::ORDER_STATE_PAID,
- 'finishtime' => $time,
- 'updatetime' => $time,
- ], ['id' => $orders['id'], 'state' => OrderContents::ORDER_STATE_TO_PAY])) {
- LogService::error('订单未更新');
- return;
- }
- BuyMoreService::instance()->checkOrderBuyMore($orders['user_id'], $orders['out_trade_no'], $orders['id']);
- //如果为复粉支付号,加入用户缓存
- $wxpay = OfficialAccountsService::instance()->getWxpayModel()->getInfoById($oOrder->wxpay_id);
- if ($wxpay['fufen']) {
- $cache = CacheConstants::getWxpayFunfen($oOrder->user_id);
- Redis::instance()->sAdd($cache, $oOrder->wxpay_id);
- }
- //记录用户充值完成时间
- WhiteList::addUserPayTime($orders['user_id']);
- //处理取消充值redis标志位
- $redis = Redis::instance();
- $payCancelKey = "O-C:{$orders['user_id']}:{$orders['goods_id']}";
- if ($redis->exists($payCancelKey)) {
- //redis标记设置
- $redis->setex($payCancelKey, 600, 2); // (600秒)10分钟 状态改为2
- }
- //取消充值ssdb首充标志位
- $userInfo = model('User')->getUserInfo($orders['user_id']);
- //起充人数
- $cid = AdminService::instance()->getAdminExtendModel()->getChannelId($userInfo['channel_id']);
- $cacheKey = CacheConstants::getPayUserLimitCacheKey($cid);
- Redis::instance()->pfAdd($cacheKey, $userInfo['id']);
- Redis::instance()->expire($cacheKey, 86400);
- if (Config::get('site.smallpay_goods_id') == $orders['goods_id']) {
- $cacheKey = CacheConstants::getSmallPayCache($orders['user_id']);
- Redis::instance()->set($cacheKey, 1);
- }
- $cacheOrderCount = CacheConstants::getUserOrderCompletedCountCacheKey($orders['user_id']);
- if ($count = Redis::instance()->get($cacheOrderCount)) {
- Redis::instance()->incr($cacheOrderCount);
- } else {
- $count = OrderService::instance()->getOrderModel()
- ->where('user_id', $orders['user_id'])
- ->where('state', OrderContents::ORDER_STATE_PAID)
- ->count();
- Redis::instance()->set($cacheOrderCount, $count + 1);
- }
- //未设置的,都按已激活算
- $isPay = $userInfo['first_cancel_pay'] ?? 1;
- if($isPay){
- // $is_update = model('User')
- // ->setConnect($orders['user_id'])
- // ->where('id',$orders['user_id'])
- // ->update(['first_cancel_pay'=>0]);
- $is_update = UserService::instance()->update(['first_cancel_pay' => 0], ['id' => $orders['user_id']]);
- if($is_update === false){
- Log::error("支付回调: UserId:{$orders['user_id']} first_cancel_pay:0 更新用户首冲标志位失败");
- }
- $redis->del("UN:{$orders['user_id']}");
- }
- $this_money_benefit = round($orders['money_benefit'], 2);
- //写统计数据
- //今天
- $today = date('Ymd', $orders['createtime']);
- //本月
- // //统计活动充值
- $oAna = new AnalysisObject();
- $oAna->event_time = $oOrder->createtime;
- $oAna->type = KafkaDotConstants::TYPE_ORDER_COMPLETE;
- $oAna->data = [
- 'orders_type' => $orders['type'],
- 'money' => $orders['money'],
- 'user_collect' => 1,
- ];
- if ($orders['book_id']) {
- $oAna->data['book_id'] = $orders['book_id'];
- }
- try {
- //活动且非扣量,进行数据统计
- if ($oOrder->activity_id && !$oOrder->resource_id) {
- // $oAna->user_from['activity_id'] = $oOrder->activity_id;
- $oActivityAna = new AnalysisObject();
- $oActivityAna->type = KafkaDotConstants::TYPE_ACTIVITY;
- $oActivityAna->user_from = [
- 'activity_id' => $oOrder->admin_id
- ];
- $oActivityAna->data = [
- 'stage' => 'end'
- ];
- KafkaDotService::instance()->sendMsg($oOrder->user_id, $oActivityAna);
- //如果是渠道自定义活动在处理
- if(model('Activity')->checkIsChannelActivity($orders->activity_id)){
- $pay_count_key = "ATPU:{$orders['activity_id']}";
- $activity_config = Config::get('site.activity_config');
- $redis->hIncrBy($pay_count_key,$orders['user_id'],1);
- $redis->expire($pay_count_key,(intval($activity_config['time_interval'])*86400)*2);
- }
- $activityCollect = model('ActivityCollect');
- $activityCollectAll = model('ActivityCollectAll');
- $dayFindArr = ['aid' => $orders->activity_id, 'admin_id' => $orders->admin_id, 'createdate' => $today, 'business_line'=>$business];
- $allFindArr = ['aid' => $orders->activity_id, 'admin_id' => $orders->admin_id, 'business_line'=>$business];
- //管理员条件
- $managerDayFindArr = ['aid' => $orders->activity_id, 'admin_id' => 0, 'createdate' => $today, 'business_line'=>$business];
- $managerAllFindArr = ['aid' => $orders->activity_id, 'admin_id' => 0, 'business_line'=>$business];
- $dayRes = $activityCollect->where($dayFindArr)->find();
- $allRes = $activityCollectAll->where($allFindArr)->find();
- $manageDayRes = $activityCollect->where($managerDayFindArr)->find();
- $manageAllRes = $activityCollectAll->where($managerAllFindArr)->find();
- //按日统计
- if ($dayRes) { //更新
- //渠道商代理商
- $dayArrAc['money'] = ['exp', "`money`+{$orders['money']}"];
- $dayArrAc['recharge_count'] = ['exp', "`recharge_count`+1"];
- $dayArrAc['updatetime'] = time();
- $sqlRes = $activityCollect->update($dayArrAc, $dayFindArr);
- if(empty($sqlRes)){
- Log::info('统计sql执行失败--表:activityCollect--数据:'.json_encode($dayArrAc).'where条件:'.json_encode($dayFindArr));
- }
- } else { //插入
- $dayFindArr['money'] = $orders['money'];
- $dayFindArr['recharge_count'] = 1;
- $dayFindArr['createtime'] = time();
- $dayFindArr['updatetime'] = time();
- $sqlRes = $activityCollect->insert($dayFindArr);
- if(empty($sqlRes)){
- Log::info('统计sql执行失败--表:activityCollect--数据:'.json_encode($dayFindArr));
- }
- }
- //管理员按日统计
- if ($manageDayRes) { //更新
- //渠道商代理商
- $mdayArrAc['money'] = ['exp', "`money`+{$orders['money']}"];
- $mdayArrAc['recharge_count'] = ['exp', "`recharge_count`+1"];
- $mdayArrAc['updatetime'] = time();
- $sqlRes = $activityCollect->update($mdayArrAc, $managerDayFindArr);
- if(empty($sqlRes)){
- Log::info('统计sql执行失败--表:activityCollect--数据:'.json_encode($mdayArrAc).'where条件:'.json_encode($managerDayFindArr));
- }
- } else { //插入
- $managerDayFindArr['money'] = $orders['money'];
- $managerDayFindArr['recharge_count'] = 1;
- $managerDayFindArr['createtime'] = time();
- $managerDayFindArr['updatetime'] = time();
- $sqlRes = $activityCollect->insert($managerDayFindArr);
- if(empty($sqlRes)){
- Log::info('统计sql执行失败--表:activityCollect--数据:'.json_encode($managerDayFindArr));
- }
- }
- //汇总统计
- if ($allRes) { //更新
- $allArrAc['money'] = ['exp', "`money`+{$orders['money']}"];
- $allArrAc['recharge_count'] = ['exp', "`recharge_count`+1"];
- $allArrAc['updatetime'] = time();
- $sqlRes = $activityCollectAll->update($allArrAc, $allFindArr);
- if(empty($sqlRes)){
- Log::info('统计sql执行失败--表:activityCollect--数据:'.json_encode($allArrAc).'where条件:'.json_encode($allFindArr));
- }
- } else { //插入
- $allFindArr['money'] = $orders['money'];
- $allFindArr['recharge_count'] = 1;
- $allFindArr['createtime'] = time();
- $allFindArr['updatetime'] = time();
- $sqlRes = $activityCollectAll->insert($allFindArr);
- if(empty($sqlRes)){
- Log::info('统计sql执行失败--表:activityCollect--数据:'.json_encode($allFindArr));
- }
- }
- //管理员汇总统计
- if ($manageAllRes) { //更新
- $mallArrAc['money'] = ['exp', "`money`+{$orders['money']}"];
- $mallArrAc['recharge_count'] = ['exp', "`recharge_count`+1"];
- $mallArrAc['updatetime'] = time();
- $sqlRes = $activityCollectAll->update($mallArrAc, $managerAllFindArr);
- if(empty($sqlRes)){
- Log::info('统计sql执行失败--表:activityCollect--数据:'.json_encode($mallArrAc).'where条件:'.json_encode($managerAllFindArr));
- }
- } else { //插入
- $managerAllFindArr['money'] = $orders['money'];
- $managerAllFindArr['recharge_count'] = 1;
- $managerAllFindArr['createtime'] = time();
- $managerAllFindArr['updatetime'] = time();
- $sqlRes = $activityCollectAll->insert($managerAllFindArr);
- if(empty($sqlRes)){
- Log::info('统计sql执行失败--表:activityCollect--数据:'.json_encode($managerAllFindArr));
- }
- }
- }
- } catch (\Exception $exception) {
- Log::error('支付回调插入活动表出错'.json_encode(['errcode' => $exception->getCode(), 'errmsg' => $exception->getMessage()]));
- }
- try {
- /**
- * referral 推广表
- */
- if (!empty($orders['referral_id']) && $business == PayConstants::BUSINESS_WECHAT) { // 是推广链接产生的订单
- $oAna->user_from['referral_id'] = $orders['referral_id'];
- $redis = Redis::instance();
- if (empty($orders['resource_id'])) { // 非转移订单&非扣量订单
- model('referral')->update(['money' => ['exp', "`money`+{$orders['money']}"], 'orders_num' => ['exp', "`orders_num`+1"]],
- ['id' => $orders['referral_id']]);
- //当天充值金额
- $dayMTkey = "M-T:" . $orders['referral_id'] . ":" . date("d");
- if ($redis->exists($dayMTkey)) {
- $redis->incrBy($dayMTkey, intval($orders['money'] * 100));
- } else {
- $redis->set($dayMTkey,intval($orders['money'] * 100));
- $redis->expire($dayMTkey,86400);
- }
- //当天充值笔数
- $dayMTkey = "M-T-N:" . $orders['referral_id'] . ":" . date("d");
- if ($redis->exists($dayMTkey)) {
- $redis->incrBy($dayMTkey, 1);
- } else {
- $redis->set($dayMTkey,1);
- $redis->expire($dayMTkey,86400);
- }
- //更新每日数据
- ReferralService::instance()->updateDayData($orders['referral_id'], ['orders_num' => 1, 'recharge_money' => $orders['money']], $orders['createtime']);
- }
- }
- /**
- * referral 推广表
- */
- if (!empty($orders['referral_id_permanent']) && $orders['referral_id_permanent'] != $orders['referral_id'] && $business == PayConstants::BUSINESS_WECHAT) { // 是推广链接产生的订单
- $oAna->data['referral_id_permanent'] = $orders['referral_id_permanent'];
- $redis = Redis::instance();
- if (empty($orders['resource_id'])) { // 非转移订单&非扣量订单
- model('referral')->update(['money' => ['exp', "`money`+{$orders['money']}"], 'orders_num' => ['exp', "`orders_num`+1"]],
- ['id' => $orders['referral_id_permanent']]);
- //当天充值金额
- $dayMTkey = "M-T:" . $orders['referral_id_permanent'] . ":" . date("d");
- if ($redis->exists($dayMTkey)) {
- $redis->incrBy($dayMTkey, intval($orders['money'] * 100));
- } else {
- $redis->set($dayMTkey,intval($orders['money'] * 100));
- $redis->expire($dayMTkey,86400);
- }
- //当天充值笔数
- $dayMTkey = "M-T-N:" . $orders['referral_id_permanent'] . ":" . date("d");
- if ($redis->exists($dayMTkey)) {
- $redis->incrBy($dayMTkey, 1);
- } else {
- $redis->set($dayMTkey,1);
- $redis->expire($dayMTkey,86400);
- }
- //更新每日数据
- ReferralService::instance()->updateDayData($orders['referral_id_permanent'], ['orders_num' => 1, 'recharge_money' => $orders['money']], $orders['createtime']);
- }
- }
- } catch (\Exception $exception) {
- Log::error('支付回调更新推广链接表出错'.json_encode(['errcode' => $exception->getCode(), 'errmsg' => $exception->getMessage()]));
- }
- /**
- * recharge表
- */
- try {
- // 充值书币/VIP
- $rechargeModel = model('Recharge');
- $data = [
- 'user_id' => $orders['user_id'],
- 'type' => $orders['type'],
- 'kandian' => $orders['kandian'],
- 'remain_kandian' => $orders['kandian'],
- 'free_kandian' => 0,
- 'remain_free_kandian' => 0,
- 'day' => $orders['day'],
- 'book_id' => $orders['book_id'],
- 'dd' => $orders['deduct'],
- 'createtime' => $time,
- 'updatetime' => $time,
- 'business_line' => $business,
- 'orders_id' => $orders['id'],
- ];
- //查询订单是不是消耗活动得订单 wud
- $orderExtendType = model('OrdersExtend')->where(['order_id'=>$orders['id']])->find();
- if( !empty($orderExtendType) ){
- $data['extend_type'] = $orderExtendType['type'];
- }
- if($orders['type'] == '2'){
- //VIP充值
- $data['vip_starttime'] = $rechargeModel->getVipStartTime($orders['user_id']);
- if($orders['deduct'] == '0'){
- $data['channel_vip_starttime'] = $rechargeModel->getChannelVipStartTime($orders['user_id']);
- }
- }
- $sqlRes = $rechargeModel->setConnect($orders['user_id'])->insertGetId($data);
- if(empty($sqlRes)){
- Log::info('充值书币sql执行失败--表:recharge--数据:'.json_encode($data).'用户id:'.$orders['user_id']);
- }
- FinancialService::instance()->getKandian($orders['user_id']);
- } catch (\Exception $exception) {
- Log::error('支付回调插入表出错:'.json_encode(['errcode' => $exception->getCode(), 'errmsg' => $exception->getMessage()]));
- }
- // 赠送书币(VIP无赠送)
- try {
- if ($orders['type'] == 1 && !empty($orders['free_kandian'])) {
- $data = [
- 'user_id' => $orders['user_id'],
- 'type' => $orders['type'],
- 'kandian' => 0,
- 'remain_kandian' => 0,
- 'free_kandian' => $orders['free_kandian'],
- 'remain_free_kandian' => $orders['free_kandian'],
- 'day' => 0,
- 'book_id' => $orders['book_id'],
- 'dd' => $orders['deduct'],
- 'createtime' => $time,
- 'updatetime' => $time,
- 'business_line' => $business,
- 'orders_id' => $orders['id'],
- ];
- if (!empty($orders['activity_id'])) {
- $activityId = $orders['activity_id'];
- $activityInfo = ActivityService::instance()->getActivityInfo($activityId);
- $data['free_endtime'] = $time + $activityInfo['free_day'] * 86400;
- } else {
- $data['free_endtime'] = $time + Config::get('site.kandian_free_day') * 86400;
- }
- $sqlRes = $rechargeModel->setConnect($orders['user_id'])->insertGetId($data);
- if(empty($sqlRes)){
- Log::info('充值书币sql执行失败--表:recharge--数据:'.json_encode($data).'用户id:'.$orders['user_id']);
- }
- FinancialService::instance()->getFreeKandian($orders['user_id']);
- }
- } catch (\Exception $exception) {
- Log::error('支付回调赠送书币出错:'.json_encode(['errcode' => $exception->getCode(), 'errmsg' => $exception->getMessage()]));
- }
- try {
- // user表 金额
- $userModel = model('User');
- $userInfo = $userModel->getUserInfo($orders['user_id']);
- $adminId = $orders['admin_id'];
- $group = model('AuthGroupAccess')->where('uid', $adminId)->find();
- $groupId = $group->group_id;
- //分成比例
- $adminExtend = model('AdminExtend')->where('admin_id', $adminId)->find();
- $agentID = 0;
- if ($groupId == 3) { //渠道商
- $channel_id = $adminId;
- } else {
- if ($adminExtend->distribute == '1') {
- $agentID = $adminId;
- }
- $channel_id = $adminExtend->create_by;
- $adminChannelExtend = model('AdminExtend')->where('admin_id', $channel_id)->find();
- $channelBenefit = $adminChannelExtend->benefit;
- }
- if ($userInfo) {
- $redis = Redis::instance();
- $userData = [];
- $userUpdate = new UserUpdate();
- $userUpdate->setId($orders['user_id']);
- $userKey = 'UN:' . $orders['user_id'];
- if (!$userInfo['is_pay']) {
- $userData['is_pay'] = 1;
- $userUpdate->setIsPay(1);
- $oAna->data['first_pay'] = 1;
- if (empty($orders['deduct'])) { //如果不是KL
- //渠道商OR配号代理商 统计付费用户
- $current_channel_id = empty($agentID) ? $channel_id : $agentID;
- //发送打点数据
- $dotData = new DotObject();
- $dotData->channel_id = $current_channel_id;
- $dotData->event_time = Request::instance()->server('REQUEST_TIME');
- $dotData->action_type = MqConstants::ROUTING_KEY_COLLECT_CHANNEL_PAY;
- $dotData->type = MqConstants::MSG_TYPE_PAY;
- MqService::instance()->sendMessage($dotData);
- }
- }
- if (empty($orders['deduct'])) { //如果不是KL
- //渠道每日新增用户充值总数
- $current_channel_id = empty($agentID) ? $channel_id : $agentID;
- if ($userInfo['createtime'] >= strtotime(date("Y-m-d"))) {
- $newsUserMoney = 0;
- $newsUserMoney += $orders['money'];
- //发送打点数据
- $dotData = new DotObject();
- $dotData->channel_id = $current_channel_id;
- $dotData->event_time = Request::instance()->server('REQUEST_TIME');
- $dotData->action_type = MqConstants::ROUTING_KEY_COLLECT_CHANNEL_PAY;
- $dotData->type = MqConstants::MSG_TYPE_NEW_USER_RECHARGE;
- $dotData->user_id = $orders['user_id'];
- $dotData->money = (float)$newsUserMoney;
- MqService::instance()->sendMessage($dotData);
- //写入充值的用户
- $date_time = date('Ymd');
- $key1 = "CNR_D:{$date_time}:{$channel_id}";
- $redis->pfAdd($key1, $orders['user_id']);
- $key2 = "CNR_D:{$date_time}:0";
- $redis->pfAdd($key2, $orders['user_id']);
- }
- }
- if ($orders['day']) {
- if ($userInfo['vip_endtime'] > $time) {
- $vipTime = $orders['day'] * 86400;
- $userData['vip_endtime'] = $userInfo['vip_endtime'] + $vipTime;
- } else {
- $vipTime = intval($time) + intval($orders['day'] * 86400);
- $userData['vip_endtime'] = $vipTime;
- //VIP 间隔续费时,维护vip_starttime
- UserVipExtendService::instance()->saveVipStartTime($orders['user_id'], intval($time));
- }
- $userUpdate->setAddvipday($orders['day'] * 86400);
- }
- if (ApiService::instance()->checkApiOn()) {
- \app\source\service\UserService::instance()->updateUser($userUpdate);
- } else {
- $userModel->setConnect($orders['user_id'])->update($userData, ['id' => $orders['user_id']]);
- //修改redis
- $redis->del($userKey);
- }
- }
- } catch (\Exception $exception) {
- Log::error('支付回调用户操作失败:'.json_encode(['errcode' => $exception->getCode(), 'errmsg' => $exception->getMessage()]));
- }
- //内推单页直接购买书籍
- try {
- SinglePushService::instance()->completeOrders($orders);
- }catch (\Exception $e){
- log::error('内推页直接购买书籍失败'.json_encode($orders));
- }
- //消耗活动标记
- $cSignKey = CampaignConstants::getUserClickCSignKey($userInfo['id']);
- $uOrderKey = CampaignConstants::getUserPayOrderKey($userInfo['id']);
- if (Redis::instance()->get($cSignKey)) {
- if (Redis::instance()->get($uOrderKey) === false) {
- Redis::instance()->set($uOrderKey, $orders['out_trade_no'], 86400);
- }
- }
- //添加渠道订单金额统计
- if ($orders['deduct']) {
- AdminKlService::instance($business)->addChannelOrderMoneyCache($orders['resource_id'], $orders['money'], $orders['out_trade_no'], true);
- AdminKlService::instance($business)->addChannelOrderMoneyCache($orders['resource_id'], $orders['money'], $orders['out_trade_no']);
- } else {
- AdminKlService::instance($business)->addChannelOrderMoneyCache($orders['admin_id'], $orders['money'], $orders['out_trade_no']);
- }
- // 用户画像打点
- $this->_saveUserDot($orders);
- if (intval($orders['deduct']) < 1 || $orders['createtime'] > 1577203200) { //如果不是KL
- /*
- * orders_collect表
- */
- //判断 充值vip(true) 还是 充值书币(false)
- $isVip = !empty($orders['day']);
- $isActivity = !empty($orders['activity_id']);
- //判断 引导充值(true) 还是 普通充值(false)
- $yd = !empty($orders['book_id']);
- $ordersCollect = model('OrdersCollect');
- $splitMoney = $this->splitMoney($orders);
- try {
- $adminId = $orders['admin_id'];
- $group = model('AuthGroupAccess')->where('uid', $adminId)->find();
- $groupId = $group->group_id;
- if ($groupId == 3) { //渠道商
- /**
- * 渠道商提现表维护
- */
- $adminMoneyModel = model('AdminMoney');
- $adminMoneyResult = $adminMoneyModel->where(['admin_id' => $adminId])->find();
- if ($adminMoneyResult) { //更新
- $moneyData = [];
- $moneyData['count_money'] = ['exp', "`count_money`+{$orders['money']}"]; //总收入金额
- $moneyData['split_money'] = ['exp', "`split_money`+{$splitMoney}"]; //总分账金额
- $moneyData['orders_count'] = ['exp', "`orders_count`+1"];
- $moneyData['updatetime'] = $time;
- $sqlRes = $adminMoneyModel->update($moneyData, ['id' => $adminMoneyResult->id]);
- if (empty($sqlRes)) {
- Log::info('提现sql执行失败--表:AdminMoney--数据:' . json_encode($moneyData) . 'where条件:' . json_encode(['id' => $adminMoneyResult->id]));
- }
- } else { //插入
- $moneyData = [];
- $moneyData['admin_id'] = $adminId;
- $moneyData['count_money'] = $orders['money']; //总收入金额
- $moneyData['split_money'] = $splitMoney; //总分账金额
- $moneyData['orders_count'] = 1;
- $moneyData['createtime'] = $time;
- $moneyData['updatetime'] = $time;
- $sqlRes = $adminMoneyModel->insert($moneyData);
- if (empty($sqlRes)) {
- Log::info('提现sql执行失败--表:AdminMoney--数据:' . json_encode($moneyData));
- }
- }
- /**
- * 渠道商 当天 自身
- */
- $channelDay = [
- 'admin_id' => $adminId,
- 'type' => 1,
- 'flag' => 1,
- 'createdate' => $today,
- 'business_line' => $business,
- ];
- $channelResDay = $ordersCollect->where($channelDay)->find();
- if ($channelResDay) {
- $user_count = OrderService::instance()->setOrderUserCountCache($orders['user_id'], $channelDay,
- $isVip)->data;
- $dayArr = [];
- $dayArr['recharge_money'] = ['exp', "`recharge_money`+{$orders['money']}"];
- $dayArr['recharge_money_benefit'] = [
- 'exp',
- "`recharge_money_benefit`+{$this_money_benefit}",
- ];
- if ($splitMoney) {
- $dayArr['split_money'] = [
- 'exp',
- "`split_money`+{$splitMoney}",
- ];
- }
- if ($isVip) {
- $dayArr['vip_recharge_user_suc_count'] = $user_count['user'];
- $dayArr['recharge_user_suc_count'] = $user_count['total'];
- $dayArr['vip_recharge_orders'] = ['exp', "`vip_recharge_orders`+1"];
- $dayArr['vip_recharge_money'] = [
- 'exp',
- "`vip_recharge_money`+{$orders['money']}",
- ];
- $dayArr['vip_recharge_money_benefit'] = [
- 'exp',
- "`vip_recharge_money_benefit`+{$this_money_benefit}",
- ];
- if ($yd) {
- $dayArr['vip_recharge_guide_orders'] = [
- 'exp',
- "`vip_recharge_guide_orders`+1",
- ];;
- $dayArr['vip_recharge_guide_money'] = [
- 'exp',
- "`vip_recharge_guide_money`+{$orders['money']}",
- ];
- $dayArr['vip_recharge_guide_money_benefit'] = [
- 'exp',
- "`vip_recharge_guide_money_benefit`+{$this_money_benefit}",
- ];
- }
- } else {
- $dayArr['normal_recharge_user_suc_count'] = $user_count['user'];
- $dayArr['recharge_user_suc_count'] = $user_count['total'];
- $dayArr['normal_recharge_orders'] = ['exp', "`normal_recharge_orders`+1"];
- $dayArr['normal_recharge_money'] = [
- 'exp',
- "`normal_recharge_money`+{$orders['money']}",
- ];
- $dayArr['normal_recharge_money_benefit'] = [
- 'exp',
- "`normal_recharge_money_benefit`+{$this_money_benefit}",
- ];
- if ($yd) {
- $dayArr['normal_recharge_guide_orders'] = [
- 'exp',
- "`normal_recharge_guide_orders`+1",
- ];
- $dayArr['noraml_recharge_guide_money'] = [
- 'exp',
- "`noraml_recharge_guide_money`+{$orders['money']}",
- ];
- $dayArr['noraml_recharge_guide_money_benefit'] = [
- 'exp',
- "`noraml_recharge_guide_money_benefit`+{$this_money_benefit}",
- ];
- }
- if (!$isActivity) {
- $dayArr['kandian_recharge_orders'] = ['exp', "`kandian_recharge_orders`+1"];
- }
- }
- $sqlRes = $ordersCollect->update($dayArr, ['id' => $channelResDay->id]);
- if (empty($sqlRes)) {
- Log::info('统计sql执行失败--表:ordersCollect--数据:' . json_encode($dayArr) . 'where条件:' . json_encode(['id' => $channelResDay->id]));
- }
- }
- /**
- * 渠道商 当天 全部
- */
- $channelAllDay = [
- 'admin_id' => $adminId,
- 'type' => 1,
- 'flag' => 3,
- 'createdate' => $today,
- 'business_line' => $business,
- ];
- $channelAllResDay = $ordersCollect->where($channelAllDay)->find();
- if ($channelAllResDay) {
- $user_count = OrderService::instance()->setOrderUserCountCache($orders['user_id'],
- $channelAllDay, $isVip)->data;
- $dayAllArr = [];
- $dayAllArr['recharge_money'] = ['exp', "`recharge_money`+{$orders['money']}"];
- $dayAllArr['recharge_money_benefit'] = [
- 'exp',
- "`recharge_money_benefit`+{$this_money_benefit}",
- ];
- if ($splitMoney) {
- $dayAllArr['split_money'] = [
- 'exp',
- "`split_money`+{$splitMoney}",
- ];
- }
- if ($isVip) {
- $dayAllArr['vip_recharge_user_suc_count'] = $user_count['user'];
- $dayAllArr['recharge_user_suc_count'] = $user_count['total'];
- $dayAllArr['vip_recharge_orders'] = ['exp', "`vip_recharge_orders`+1"];
- $dayAllArr['vip_recharge_money'] = [
- 'exp',
- "`vip_recharge_money`+{$orders['money']}",
- ];
- $dayAllArr['vip_recharge_money_benefit'] = [
- 'exp',
- "`vip_recharge_money_benefit`+{$this_money_benefit}",
- ];
- if ($yd) {
- $dayAllArr['vip_recharge_guide_orders'] = [
- 'exp',
- "`vip_recharge_guide_orders`+1",
- ];
- $dayAllArr['vip_recharge_guide_money'] = [
- 'exp',
- "`vip_recharge_guide_money`+{$orders['money']}",
- ];
- $dayAllArr['vip_recharge_guide_money_benefit'] = [
- 'exp',
- "`vip_recharge_guide_money_benefit`+{$this_money_benefit}",
- ];
- }
- } else {
- $dayAllArr['normal_recharge_user_suc_count'] = $user_count['user'];
- $dayAllArr['recharge_user_suc_count'] = $user_count['total'];
- $dayAllArr['normal_recharge_orders'] = ['exp', "`normal_recharge_orders`+1"];
- $dayAllArr['normal_recharge_money'] = [
- 'exp',
- "`normal_recharge_money`+{$orders['money']}",
- ];
- $dayAllArr['normal_recharge_money_benefit'] = [
- 'exp',
- "`normal_recharge_money_benefit`+{$this_money_benefit}",
- ];
- if ($yd) {
- $dayAllArr['normal_recharge_guide_orders'] = [
- 'exp',
- "`normal_recharge_guide_orders`+1",
- ];
- $dayAllArr['noraml_recharge_guide_money'] = [
- 'exp',
- "`noraml_recharge_guide_money`+{$orders['money']}",
- ];
- $dayAllArr['noraml_recharge_guide_money_benefit'] = [
- 'exp',
- "`noraml_recharge_guide_money_benefit`+{$this_money_benefit}",
- ];
- }
- if (!$isActivity) {
- $dayAllArr['kandian_recharge_orders'] = ['exp', "`kandian_recharge_orders`+1"];
- }
- }
- $sqlRes = $ordersCollect->update($dayAllArr, ['id' => $channelAllResDay->id]);
- if (empty($sqlRes)) {
- Log::info('统计sql执行失败--表:ordersCollect--数据:' . json_encode($dayAllArr) . 'where条件:' . json_encode(['id' => $channelAllResDay->id]));
- }
- }
- /**
- * 管理员 当天 属下
- */
- $managerDay = [
- 'admin_id' => 0,
- 'type' => 1,
- 'flag' => 2,
- 'createdate' => $today,
- 'business_line' => $business,
- ];
- $manageResDay = $ordersCollect->where($managerDay)->find();
- if ($manageResDay) {
- $user_count = OrderService::instance()->setOrderUserCountCache($orders['user_id'], $managerDay,
- $isVip)->data;
- $mDayArr = [];
- $mDayArr['recharge_money'] = ['exp', "`recharge_money`+{$orders['money']}"];
- $mDayArr['recharge_money_benefit'] = [
- 'exp',
- "`recharge_money_benefit`+{$this_money_benefit}",
- ];
- if ($isVip) {
- $mDayArr['vip_recharge_user_suc_count'] = $user_count['user'];
- $mDayArr['recharge_user_suc_count'] = $user_count['total'];
- $mDayArr['vip_recharge_orders'] = ['exp', "`vip_recharge_orders`+1"];
- $mDayArr['vip_recharge_money'] = ['exp', "`vip_recharge_money`+{$orders['money']}"];
- $mDayArr['vip_recharge_money_benefit'] = [
- 'exp',
- "`vip_recharge_money_benefit`+{$this_money_benefit}",
- ];
- if ($yd) {
- $mDayArr['vip_recharge_guide_orders'] = ['exp', "`vip_recharge_guide_orders`+1"];
- $mDayArr['vip_recharge_guide_money'] = [
- 'exp',
- "`vip_recharge_guide_money`+{$orders['money']}",
- ];
- $mDayArr['vip_recharge_guide_money_benefit'] = [
- 'exp',
- "`vip_recharge_guide_money_benefit`+{$this_money_benefit}",
- ];
- }
- } else {
- $mDayArr['normal_recharge_user_suc_count'] = $user_count['user'];
- $mDayArr['recharge_user_suc_count'] = $user_count['total'];
- $mDayArr['normal_recharge_orders'] = ['exp', "`normal_recharge_orders`+1"];
- $mDayArr['normal_recharge_money'] = [
- 'exp',
- "`normal_recharge_money`+{$orders['money']}",
- ];
- $mDayArr['normal_recharge_money_benefit'] = [
- 'exp',
- "`normal_recharge_money_benefit`+{$this_money_benefit}",
- ];
- if ($yd) {
- $mDayArr['normal_recharge_guide_orders'] = [
- 'exp',
- "`normal_recharge_guide_orders`+1",
- ];
- $mDayArr['noraml_recharge_guide_money'] = [
- 'exp',
- "`noraml_recharge_guide_money`+{$orders['money']}",
- ];
- $mDayArr['noraml_recharge_guide_money_benefit'] = [
- 'exp',
- "`noraml_recharge_guide_money_benefit`+{$this_money_benefit}",
- ];
- }
- if (!$isActivity) {
- $mDayArr['kandian_recharge_orders'] = ['exp', "`kandian_recharge_orders`+1"];
- }
- }
- $sqlRes = $ordersCollect->update($mDayArr, ['id' => $manageResDay->id]);
- if (empty($sqlRes)) {
- Log::info('统计sql执行失败--表:ordersCollect--数据:' . json_encode($mDayArr) . 'where条件:' . json_encode(['id' => $manageResDay->id]));
- }
- }
- }
- } catch (\Exception $exception) {
- Log::error('支付回调渠道商统计出错:' . json_encode([
- 'errcode' => $exception->getCode(),
- 'errmsg' => $exception->getMessage()
- ]));
- }
- if ($groupId == 4 && isset($channelBenefit)) { //代理商
- try {
- $cBenefitMoney = round($channelBenefit * $orders['money'], 2); //渠道商设置的分成收益
- $adminMoneyModel = model('AdminMoney');
- /**
- * 代理商 提现表 维护
- */
- $adminMoneyResult = $adminMoneyModel->where(['admin_id' => $adminId])->find();
- $moneyData = [];
- if ($adminMoneyResult) { //更新
- $moneyData['count_money'] = ['exp', "`count_money`+{$orders['money']}"]; //总收入金额
- $moneyData['orders_count'] = ['exp', "`orders_count`+1"]; //总收入金额
- $sqlRes = $adminMoneyModel->update($moneyData, ['id' => $adminMoneyResult->id]);
- if (empty($sqlRes)) {
- Log::info('统计sql执行失败--表:AdminMoney--数据:' . json_encode($moneyData) . 'where条件:' . json_encode(['id' => $adminMoneyResult->id]));
- }
- } else { //插入
- $moneyData['admin_id'] = $adminId;
- $moneyData['count_money'] = $orders['money']; //总收入金额
- $moneyData['orders_count'] = 1;
- $sqlRes = $adminMoneyModel->insert($moneyData);
- if (empty($sqlRes)) {
- Log::info('统计sql执行失败--表:AdminMoney--数据:' . json_encode($moneyData));
- }
- }
- /**
- * 渠道商 提现表 维护 $channel_id
- */
- $channelMcount = $adminMoneyModel->where(['admin_id' => $channel_id])->find();
- $chanData = [];
- if ($channelMcount) { //更新
- $chanData['count_money'] = ['exp', "`count_money`+{$orders['money']}"]; //总收入金额
- $chanData['split_money'] = ['exp', "`split_money`+{$splitMoney}"]; //总分账金额
- $chanData['orders_count'] = ['exp', "`orders_count`+1"]; //总收入金额
- $sqlRes = $adminMoneyModel->update($chanData, ['id' => $channelMcount->id]);
- if (empty($sqlRes)) {
- Log::info('统计sql执行失败--表:AdminMoney--数据:' . json_encode($chanData) . 'where条件:' . json_encode(['id' => $channelMcount->id]));
- }
- } else { //插入
- $chanData['admin_id'] = $channel_id;
- $chanData['count_money'] = $orders['money']; //总收入金额
- $chanData['split_money'] = $splitMoney; //总分账金额
- $chanData['orders_count'] = 1;
- $sqlRes = $adminMoneyModel->insert($chanData);
- if (empty($sqlRes)) {
- Log::info('统计sql执行失败--表:AdminMoney--数据:' . json_encode($chanData));
- }
- }
- /**
- * 代理商 当天 自身
- */
- $agentDay = [
- 'admin_id' => $adminId,
- 'type' => 1,
- 'flag' => 1,
- 'createdate' => $today,
- 'business_line' => $business,
- ];
- $agentResDay = $ordersCollect->where($agentDay)->find();
- if ($agentResDay) {
- $user_count = OrderService::instance()->setOrderUserCountCache($orders['user_id'], $agentDay,
- $isVip)->data;
- $adayArr = [];
- $adayArr['recharge_money'] = ['exp', "`recharge_money`+{$orders['money']}"];
- $adayArr['recharge_money_benefit'] = [
- 'exp',
- "`recharge_money_benefit`+{$this_money_benefit}",
- ];
- if ($isVip) {
- $adayArr['vip_recharge_user_suc_count'] = $user_count['user'];
- $adayArr['recharge_user_suc_count'] = $user_count['total'];
- $adayArr['vip_recharge_orders'] = ['exp', "`vip_recharge_orders`+1"];
- $adayArr['vip_recharge_money'] = ['exp', "`vip_recharge_money`+{$orders['money']}"];
- $adayArr['vip_recharge_money_benefit'] = [
- 'exp',
- "`vip_recharge_money_benefit`+{$this_money_benefit}",
- ];
- if ($yd) {
- $adayArr['vip_recharge_guide_orders'] = ['exp', "`vip_recharge_guide_orders`+1"];
- $adayArr['vip_recharge_guide_money'] = [
- 'exp',
- "`vip_recharge_guide_money`+{$orders['money']}",
- ];
- $adayArr['vip_recharge_guide_money_benefit'] = [
- 'exp',
- "`vip_recharge_guide_money_benefit`+{$this_money_benefit}",
- ];
- }
- } else {
- $adayArr['normal_recharge_user_suc_count'] = $user_count['user'];
- $adayArr['recharge_user_suc_count'] = $user_count['total'];
- $adayArr['normal_recharge_orders'] = ['exp', "`normal_recharge_orders`+1"];
- $adayArr['normal_recharge_money'] = [
- 'exp',
- "`normal_recharge_money`+{$orders['money']}",
- ];
- $adayArr['normal_recharge_money_benefit'] = [
- 'exp',
- "`normal_recharge_money_benefit`+{$this_money_benefit}",
- ];
- if ($yd) {
- $adayArr['normal_recharge_guide_orders'] = [
- 'exp',
- "`normal_recharge_guide_orders`+1",
- ];
- $adayArr['noraml_recharge_guide_money'] = [
- 'exp',
- "`noraml_recharge_guide_money`+{$orders['money']}",
- ];
- $adayArr['noraml_recharge_guide_money_benefit'] = [
- 'exp',
- "`noraml_recharge_guide_money_benefit`+{$this_money_benefit}",
- ];
- }
- if (!$isActivity) {
- $adayArr['kandian_recharge_orders'] = ['exp', "`kandian_recharge_orders`+1"];
- }
- }
- $sqlRes = $ordersCollect->update($adayArr, ['id' => $agentResDay->id]);
- if (empty($sqlRes)) {
- Log::info('统计sql执行失败--表:ordersCollect--数据:' . json_encode($adayArr) . 'where条件:' . json_encode(['id' => $agentResDay->id]));
- }
- }
- /**
- * 渠道商 当天 属下
- */
- $agentParentDay = [
- 'admin_id' => $channel_id,
- 'type' => 1,
- 'flag' => 2,
- 'createdate' => $today,
- 'business_line' => $business,
- ];
- $agentParentResDay = $ordersCollect->where($agentParentDay)->find();
- if ($agentParentResDay) {
- $user_count = OrderService::instance()->setOrderUserCountCache($orders['user_id'],
- $agentParentDay, $isVip)->data;
- $apDayArr = [];
- $apDayArr['recharge_money'] = ['exp', "`recharge_money`+{$orders['money']}"];
- $apDayArr['recharge_money_benefit'] = ['exp', "`recharge_money_benefit`+{$this_money_benefit}"];
- if ($isVip) {
- $apDayArr['vip_recharge_user_suc_count'] = $user_count['user'];
- $apDayArr['recharge_user_suc_count'] = $user_count['total'];
- $apDayArr['vip_recharge_orders'] = ['exp', "`vip_recharge_orders`+1"];
- $apDayArr['vip_recharge_money'] = ['exp', "`vip_recharge_money`+{$orders['money']}"];
- $apDayArr['vip_recharge_money_benefit'] = [
- 'exp',
- "`vip_recharge_money_benefit`+{$this_money_benefit}",
- ];
- if ($yd) {
- $apDayArr['vip_recharge_guide_orders'] = ['exp', "`vip_recharge_guide_orders`+1"];
- $apDayArr['vip_recharge_guide_money'] = [
- 'exp',
- "`vip_recharge_guide_money`+{$orders['money']}",
- ];
- $apDayArr['vip_recharge_guide_money_benefit'] = [
- 'exp',
- "`vip_recharge_guide_money_benefit`+{$this_money_benefit}",
- ];
- }
- } else {
- $apDayArr['normal_recharge_user_suc_count'] = $user_count['user'];
- $apDayArr['recharge_user_suc_count'] = $user_count['total'];
- $apDayArr['normal_recharge_orders'] = ['exp', "`normal_recharge_orders`+1"];
- $apDayArr['normal_recharge_money'] = [
- 'exp',
- "`normal_recharge_money`+{$orders['money']}",
- ];
- $apDayArr['normal_recharge_money_benefit'] = [
- 'exp',
- "`normal_recharge_money_benefit`+{$this_money_benefit}",
- ];
- if ($yd) {
- $apDayArr['normal_recharge_guide_orders'] = [
- 'exp',
- "`normal_recharge_guide_orders`+1",
- ];
- $apDayArr['noraml_recharge_guide_money'] = [
- 'exp',
- "`noraml_recharge_guide_money`+{$orders['money']}",
- ];
- $apDayArr['noraml_recharge_guide_money_benefit'] = [
- 'exp',
- "`noraml_recharge_guide_money_benefit`+{$this_money_benefit}",
- ];
- }
- if (!$isActivity) {
- $apDayArr['kandian_recharge_orders'] = ['exp', "`kandian_recharge_orders`+1"];
- }
- }
- $sqlRes = $ordersCollect->update($apDayArr, ['id' => $agentParentResDay->id]);
- if (empty($sqlRes)) {
- Log::info('统计sql执行失败--表:ordersCollect--数据:' . json_encode($apDayArr) . 'where条件:' . json_encode(['id' => $agentParentResDay->id]));
- }
- }
- /**
- * 渠道商 当天 全部
- */
- $agentParentAllDay = [
- 'admin_id' => $channel_id,
- 'type' => 1,
- 'flag' => 3,
- 'createdate' => $today,
- 'business_line' => $business,
- ];
- $agentAllParentResDay = $ordersCollect->where($agentParentAllDay)->find();
- if ($agentAllParentResDay) {
- $user_count = OrderService::instance()->setOrderUserCountCache($orders['user_id'],
- $agentParentAllDay, $isVip)->data;
- $aChannelAllDay = [];
- $aChannelAllDay['recharge_money'] = ['exp', "`recharge_money`+{$orders['money']}"];
- $aChannelAllDay['recharge_money_benefit'] = [
- 'exp',
- "`recharge_money_benefit`+{$cBenefitMoney}",
- ];
- if ($splitMoney) {
- $aChannelAllDay['split_money'] = [
- 'exp',
- "`split_money`+{$splitMoney}",
- ];
- }
- if ($isVip) {
- $aChannelAllDay['vip_recharge_user_suc_count'] = $user_count['user'];
- $aChannelAllDay['recharge_user_suc_count'] = $user_count['total'];
- $aChannelAllDay['vip_recharge_orders'] = ['exp', "`vip_recharge_orders`+1"];
- $aChannelAllDay['vip_recharge_money'] = [
- 'exp',
- "`vip_recharge_money`+{$orders['money']}",
- ];
- $aChannelAllDay['vip_recharge_money_benefit'] = [
- 'exp',
- "`vip_recharge_money_benefit`+{$cBenefitMoney}",
- ];
- if ($yd) {
- $aChannelAllDay['vip_recharge_guide_orders'] = [
- 'exp',
- "`vip_recharge_guide_orders`+1",
- ];
- $aChannelAllDay['vip_recharge_guide_money'] = [
- 'exp',
- "`vip_recharge_guide_money`+{$orders['money']}",
- ];
- $aChannelAllDay['vip_recharge_guide_money_benefit'] = [
- 'exp',
- "`vip_recharge_guide_money_benefit`+{$cBenefitMoney}",
- ];
- }
- } else {
- $aChannelAllDay['normal_recharge_user_suc_count'] = $user_count['user'];
- $aChannelAllDay['recharge_user_suc_count'] = $user_count['total'];
- $aChannelAllDay['normal_recharge_orders'] = ['exp', "`normal_recharge_orders`+1"];
- $aChannelAllDay['normal_recharge_money'] = [
- 'exp',
- "`normal_recharge_money`+{$orders['money']}",
- ];
- $aChannelAllDay['normal_recharge_money_benefit'] = [
- 'exp',
- "`normal_recharge_money_benefit`+{$cBenefitMoney}",
- ];
- if ($yd) {
- $aChannelAllDay['normal_recharge_guide_orders'] = [
- 'exp',
- "`normal_recharge_guide_orders`+1",
- ];
- $aChannelAllDay['noraml_recharge_guide_money'] = [
- 'exp',
- "`noraml_recharge_guide_money`+{$orders['money']}",
- ];
- $aChannelAllDay['noraml_recharge_guide_money_benefit'] = [
- 'exp',
- "`noraml_recharge_guide_money_benefit`+{$cBenefitMoney}",
- ];
- }
- if (!$isActivity) {
- $aChannelAllDay['kandian_recharge_orders'] = ['exp', "`kandian_recharge_orders`+1"];
- }
- }
- $sqlRes = $ordersCollect->update($aChannelAllDay, ['id' => $agentAllParentResDay->id]);
- if (empty($sqlRes)) {
- Log::info('统计sql执行失败--表:ordersCollect--数据:' . json_encode($aChannelAllDay) . 'where条件:' . json_encode(['id' => $agentAllParentResDay->id]));
- }
- }
- /**
- * 管理员 当天 属下
- */
- $managerDay = [
- 'admin_id' => 0,
- 'type' => 1,
- 'flag' => 2,
- 'createdate' => $today,
- 'business_line' => $business,
- ];
- $manageResDay = $ordersCollect->where($managerDay)->find();
- if ($manageResDay) {
- $user_count = OrderService::instance()->setOrderUserCountCache($orders['user_id'], $managerDay,
- $isVip)->data;
- $aManageDay = [];
- $aManageDay['recharge_money'] = ['exp', "`recharge_money`+{$orders['money']}"];
- $aManageDay['recharge_money_benefit'] = ['exp', "`recharge_money_benefit`+{$cBenefitMoney}"];
- if ($isVip) {
- $aManageDay['vip_recharge_user_suc_count'] = $user_count['user'];
- $aManageDay['recharge_user_suc_count'] = $user_count['total'];
- $aManageDay['vip_recharge_orders'] = ['exp', "`vip_recharge_orders`+1"];
- $aManageDay['vip_recharge_money'] = ['exp', "`vip_recharge_money`+{$orders['money']}"];
- $aManageDay['vip_recharge_money_benefit'] = [
- 'exp',
- "`vip_recharge_money_benefit`+{$cBenefitMoney}",
- ];
- if ($yd) {
- $aManageDay['vip_recharge_guide_orders'] = ['exp', "`vip_recharge_guide_orders`+1"];
- $aManageDay['vip_recharge_guide_money'] = [
- 'exp',
- "`vip_recharge_guide_money`+{$orders['money']}",
- ];
- $aManageDay['vip_recharge_guide_money_benefit'] = [
- 'exp',
- "`vip_recharge_guide_money_benefit`+{$cBenefitMoney}",
- ];
- }
- } else {
- $aManageDay['normal_recharge_user_suc_count'] = $user_count['user'];
- $aManageDay['recharge_user_suc_count'] = $user_count['total'];
- $aManageDay['normal_recharge_orders'] = ['exp', "`normal_recharge_orders`+1"];
- $aManageDay['normal_recharge_money'] = [
- 'exp',
- "`normal_recharge_money`+{$orders['money']}",
- ];
- $aManageDay['normal_recharge_money_benefit'] = [
- 'exp',
- "`normal_recharge_money_benefit`+{$cBenefitMoney}",
- ];
- if ($yd) {
- $aManageDay['normal_recharge_guide_orders'] = [
- 'exp',
- "`normal_recharge_guide_orders`+1",
- ];
- $aManageDay['noraml_recharge_guide_money'] = [
- 'exp',
- "`noraml_recharge_guide_money`+{$orders['money']}",
- ];
- $aManageDay['noraml_recharge_guide_money_benefit'] = [
- 'exp',
- "`noraml_recharge_guide_money_benefit`+{$cBenefitMoney}",
- ];
- }
- if (!$isActivity) {
- $aManageDay['kandian_recharge_orders'] = ['exp', "`kandian_recharge_orders`+1"];
- }
- }
- $sqlRes = $ordersCollect->update($aManageDay, ['id' => $manageResDay->id]);
- if (empty($sqlRes)) {
- Log::info('统计sql执行失败--表:ordersCollect--数据:' . json_encode($aManageDay) . 'where条件:' . json_encode(['id' => $manageResDay->id]));
- }
- }
- } catch (\Exception $exception) {
- Log::error('支付回调代理商统计出错:' . json_encode([
- 'errcode' => $exception->getCode(),
- 'errmsg' => $exception->getMessage()
- ]));
- }
- }
- /*
- * book_collect表
- */
- if (!empty($orders['book_id'])) {
- try {
- if ($business == PayConstants::BUSINESS_APP) {
- $dotData = new DotBookCollectObject();
- $dotData->channelId = $orders['admin_id'];
- $dotData->eventTime = Request::instance()->server('REQUEST_TIME');
- $dotData->bookId = $orders['book_id'];
- $dotData->rechargeMoney = $orders['money'];
- $dotData->businessLine = $business;
- $dot = BookDotService::instance()->generateBookData($dotData);
- BookDotService::instance()->dotBookInfo($dot);
- } else {
- //管理员书籍统计
- $this->bookConsumePayCollect(0, $orders['book_id'], $orders['money']);
- //渠道商/代理商书籍统计
- $this->bookConsumePayCollect($orders['admin_id'], $orders['book_id'], $orders['money']);
- }
- } catch (\Exception $exception) {
- Log::error('支付回调book_collect统计出错:' . json_encode([
- 'errcode' => $exception->getCode(),
- 'errmsg' => $exception->getMessage()
- ]));
- }
- }
- }
- if ($groupId == 4 && isset($channelBenefit) && intval($orders['deduct']) < 1) { //代理商
- $times = time();
- $trueToday = date('Ymd', $times);
- //赏金统计
- try {
- if (!empty($orders['reward_money'])) {
- $this_reward_money = round($orders['reward_money'], 2);
- $reward_admin_id = $orders['admin_id'];
- $rewardCollect = model('reward_collect');
- //被邀请人按天
- $reward_day = [
- 'admin_id' => $reward_admin_id,
- 'createdate' => $trueToday,
- 'type' => '1',
- 'flag' => '1',
- ];
- $reward_aDay_res = $rewardCollect->where($reward_day)->find();
- if (!empty($reward_aDay_res)) { //更新
- $rDay_res = [];
- $rDay_res['reward'] = ['exp', "`reward`+{$this_reward_money}"];
- $rDay_res['updatetime'] = $times;
- model('reward_collect')->update($rDay_res, ['id' => $reward_aDay_res->id]);
- } else { //插入
- $reward_day_1['reward'] = $this_reward_money;
- $reward_day_1['invite_id'] = $orders['reward_admin_id'];
- $resadd = array_merge($reward_day_1, $reward_day);
- $resadd['createtime'] = $times;
- $resadd['updatetime'] = $times;
- $rewardCollect->insert($resadd);
- }
- //被邀请人汇总
- $reward_all = [
- 'admin_id' => $reward_admin_id,
- 'type' => '2',
- 'flag' => '1',
- ];
- $reward_aAll_res = $rewardCollect->where($reward_all)->find();
- if (!empty($reward_aAll_res)) { //更新
- $rAll_res = [];
- $rAll_res['reward'] = ['exp', "`reward`+{$this_reward_money}"];
- $rAll_res['updatetime'] = $times;
- $rewardCollect->update($rAll_res, ['id' => $reward_aAll_res->id]);
- } else { //插入
- $reward_all['reward'] = $this_reward_money;
- $reward_all['invite_id'] = $orders['reward_admin_id'];
- $reward_all['createtime'] = $times;
- $reward_all['updatetime'] = $times;
- $rewardCollect->insert($reward_all);
- }
- //邀请人按天
- $reward_channel_day = [
- 'admin_id' => $orders['reward_admin_id'],
- 'invite_id' => 0,
- 'createdate' => $trueToday,
- 'type' => '1',
- 'flag' => '2',
- ];
- $reward_cDay_res = $rewardCollect->where($reward_channel_day)->find();
- if (!empty($reward_cDay_res)) { //更新
- $reward_c_day = [];
- $reward_c_day['reward'] = ['exp', "`reward`+{$this_reward_money}"];
- $reward_c_day['updatetime'] = $times;
- $rewardCollect->update($reward_c_day, ['id' => $reward_cDay_res->id]);
- } else { //新增
- $reward_channel_day['reward'] = $this_reward_money;
- $reward_channel_day['createtime'] = $times;
- $reward_channel_day['updatetime'] = $times;
- $rewardCollect->insert($reward_channel_day);
- }
- //邀请人汇总
- $reward_channel_all = [
- 'admin_id' => $orders['reward_admin_id'],
- 'invite_id' => 0,
- 'type' => '2',
- 'flag' => '2',
- ];
- $reward_cAll_res = $rewardCollect->where($reward_channel_all)->find();
- if (!empty($reward_cAll_res)) { //更新
- $reward_c_all = [];
- $reward_c_all['reward'] = ['exp', "`reward`+{$this_reward_money}"];
- $reward_c_all['updatetime'] = $times;
- $rewardCollect->update($reward_c_all, ['id' => $reward_cAll_res->id]);
- } else { //插入
- $reward_channel_all['reward'] = $this_reward_money;
- $reward_channel_all['createtime'] = $times;
- $reward_channel_all['updatetime'] = $times;
- $rewardCollect->insert($reward_channel_all);
- }
- //提现表维护
- $reward_money = model('RewardMoney')->where('admin_id', $orders['reward_admin_id'])->find();
- $rMoneyData = [];
- if (!empty($reward_money)) { //更新
- $rMoneyData['no_cash_money'] = ['exp', "`no_cash_money`+{$this_reward_money}"]; //未提现金额
- $rMoneyData['reward_count'] = ['exp', "`reward_count`+{$this_reward_money}"]; //总赏金金额
- $rMoneyData['updatetime'] = $times;
- model('RewardMoney')->update($rMoneyData, ['id' => $reward_money['id']]);
- } else { //插入
- $rMoneyData['admin_id'] = $orders['reward_admin_id'];
- $rMoneyData['no_cash_money'] = $this_reward_money;
- $rMoneyData['reward_count'] = $this_reward_money;
- $rMoneyData['createtime'] = $times;
- $rMoneyData['updatetime'] = $times;
- model('RewardMoney')->insert($rMoneyData);
- }
- }
- } catch (\Exception $exception) {
- Log::error('支付回调赏金统计出错');
- }
- //赏金统计结束
- }
- //打点
- if($orders['deduct'] != 1 || empty($orders['resource_id'])){
- //如果不是扣量或转移
- $ext_data = json_decode($orders['ext'], true);
- if (is_array($ext_data) && $ext_data && $business == PayConstants::BUSINESS_WECHAT) {
- $oAna->user_from['mark'] = $ext_data['mark'];
- $oAna->user_from['push_id'] = $ext_data['push_id'] ?? 0;
- $oAna->user_from['push_idx'] = $ext_data['push_idx'] ?? BigData::DEFAULT_PUSH_IDX;
- $oAna->user_from['push_time'] = $ext_data['push_time'] ?? time();
- $dotData = SmartPushDotService::instance()->generateDotData(
- $ext_data['mark'],
- $ext_data['push_id'] ?? 0,
- $ext_data['push_idx'] ?? BigData::DEFAULT_PUSH_IDX,
- $ext_data['push_time'] ?? time(),
- time(),
- array_merge(['money' => $orders['money'], 'type' => 2, 'out_trade_no' => $orders['out_trade_no'], 'business_line'=>$business, 'channel_id'=>$orders['admin_id'], 'user_id'=>$orders['user_id']], $ext_data)
- );
- SmartPushDotService::instance()->dotSmartPushInfo($dotData);
- }
- Log::info(sprintf('[ MQ ] [ DOT ] wechatpay_saveorders!wxpay_id:%s,channel_id:%s,money:%s,good_id:%s,out_trade_no:%s,ext:%s,transactionId:%s,pdorderid:%s'
- , $orders['wxpay_id'], $orders['admin_id'], $orders['money'], $orders['goods_id'],
- $orders['out_trade_no'], $orders['ext'], $transactionId, $pdorderid));
- }
- //如果是消耗活动充值,直接进行报名
- if (isset($orderExtendType['type']) && $orderExtendType['type'] == 1 ){
- $matchInfo = json_decode( $orderExtendType['json'], true );
- CampaignService::instance()->autoCheckIn($userInfo,$matchInfo);
- }
- //订阅活动报名
- if (isset($orderExtendType['type']) && $orderExtendType['type'] == 2 ){
- $act = json_decode($orderExtendType['json'],true);
- $actId = $act['act_id']??0;
- SubscripService::instance()->insertActUser($userInfo,$actId,$orders);
- }
- //充值成功 发送活动推送
- MqUserPaySuccessService::instance()->sendActiveToUser($orders,$userInfo);
- $adminConfig = AdminService::instance()->getAdminConfigModel()->getAdminInfoAll($channel_id);
- //非扣量
- if (intval($orders['deduct']) < 1) {
- KafkaDotService::instance()->sendMsg($oOrder->user_id, $oAna);
- $toutType = $adminConfig['callback_time_tout'] ?? AdminConstants::CALLBACK_TIME_ONCE_24;
- LogService::info('toutpaytype:' . $toutType . ':' . $userInfo['id']);
- $check = ToutiaoNotifyService::instance()->checkCallbackTime($userInfo['subscribe_time'], $toutType)->data;
- $sToutChuanKey = CacheConstants::getCallbackLimitTout($orders['user_id']);
- $sToutChuanKeyOnce = CacheConstants::getCallbackLimitToutOnce($orders['user_id']);
- if (in_array($toutType, [AdminConstants::CALLBACK_TIME_ONCE_24, AdminConstants::CALLBACK_TIME_ONCE_DAY])) {
- //已经回传过的
- if (Redis::instance()->get($sToutChuanKeyOnce)) {
- Redis::instance()->set($sToutChuanKey, $orders['id'], 86400);
- }
- } else {
- Redis::instance()->del($sToutChuanKey);
- }
- //头条回传
- if ($check && !Redis::instance()->get($sToutChuanKey)) {
- $toutKl = ReportKlService::instance()->getKlConfig($orders['admin_id'], PostbackConstants::TYPE_TOUTIAO, $orders['referral_id'])->data;
- $ifNotKl = ReportKlService::instance()->checkNotKl($orders['admin_id'], $toutKl, $orders['referral_id'], $orders['money'])->data;
- if ($ifNotKl) {
- $type = ToutiaoNotifyService::instance()::ORANGE_EVENT_TYPE_PAY;
- $oUser = (new UserObject())->bind($userInfo);
- //橘子建站回传支持
- ToutiaoNotifyService::instance()->OrangeNotify($adminConfig, $oUser, $type, $oOrder);
- if ($link = Redis::instance()->get(CacheConstants::getGuideWxPay($orders['user_id']))) {
- ToutiaoNotifyService::instance()->notify($link, $orders['user_id'], ToutiaoNotifyService::EVENT_TYPE_PAY, $orders['money']);
- Redis::instance()->set($sToutChuanKeyOnce, $orders['id'], 86400);
- LogService::info('toutpayback:' . $orders['out_trade_no'] . ':' . $userInfo['id'] . ':' . $link);
- if (in_array($toutType, [AdminConstants::CALLBACK_TIME_ONCE_24, AdminConstants::CALLBACK_TIME_ONCE_DAY])) {
- LogService::info('toutpaybackonce:' . $toutType . ':' . $userInfo['id'] . ':' . $link);
- Redis::instance()->set($sToutChuanKey, $orders['id'], 86400);
- }
- }
- }
- }
- //uc回传
- $ucType = $adminConfig['callback_time_uc'] ?? AdminConstants::CALLBACK_TIME_ONCE_24;
- LogService::info('ucpaytype:' . $ucType . ':' . $userInfo['id']);
- $check = ToutiaoNotifyService::instance()->checkCallbackTime($userInfo['subscribe_time'], $ucType)->data;
- $sUcChuanKey = CacheConstants::getCallbackLimitUc($orders['user_id']);
- $sUcChuanKeyOnce = CacheConstants::getCallbackLimitUcOnce($orders['user_id']);
- if (in_array($ucType, [AdminConstants::CALLBACK_TIME_ONCE_24, AdminConstants::CALLBACK_TIME_ONCE_DAY])) {
- //已经回传过的
- if (Redis::instance()->get($sUcChuanKeyOnce)) {
- Redis::instance()->set($sUcChuanKey, $orders['id'], 86400);
- }
- } else {
- Redis::instance()->del($sUcChuanKey);
- }
- if ($check && !Redis::instance()->get($sUcChuanKey)) {
- if ($link = Redis::instance()->get(UcCacheConstants::getGuideWxPay($orders['user_id']))) {
- $ucKl = ReportKlService::instance()->getKlConfig($orders['admin_id'], PostbackConstants::TYPE_UC, $orders['referral_id'])->data;
- $ifNotKl = ReportKlService::instance()->checkNotKl($orders['admin_id'], $ucKl, $orders['referral_id'], $orders['money'])->data;
- if ($ifNotKl) {
- UcNotifyService::instance()->notify($userInfo, $link, UcNotifyService::EVENT_TYPE_PAY, $orders['money']);
- Redis::instance()->set($sUcChuanKeyOnce, $orders['id'], 86400);
- LogService::info('ucpayback:' . $orders['out_trade_no'] . ':' . $userInfo['id'] . ':' . $link);
- if (in_array($ucType, [AdminConstants::CALLBACK_TIME_ONCE_24, AdminConstants::CALLBACK_TIME_ONCE_DAY])) {
- LogService::info('ucpaybackonce:' . $ucType . ':' . $userInfo['id'] . ':' . $link);
- Redis::instance()->set($sUcChuanKey, $orders['id'], 86400);
- }
- }
- }
- }
- $channel_id = $userInfo['channel_id'];
- $chan_id = $userInfo['channel_id'];
- if ($orders['activity_id']) {
- $url = "/index/recharge/activity?aid={$orders['activity_id']}&user_id={$orders['user_id']}";
- } else {
- if ($orders['book_id']) {
- $chan_id = Config::get('site.tdc_bookinfo_url_channel') ?: $channel_id;
- $url = '/index/book/info?book_id='.$orders['book_id'];
- } else {
- $url = "/index/recharge/pay?id={$orders['goods_id']}&user_id={$orders['user_id']}&book_id={$orders['book_id']}";
- }
- }
- $url = getCurrentDomain($chan_id,$url);
- $productName = '';
- if(empty($orders['book_id'])){
- $orders['book_id'] = (int)0;
- }
- if ($orders['book_id']) {
- $theme = \think\Config::get('site.theme');
- if ($theme == null) {
- //库里拉取
- $site = model("Config")->getConfigSiteArr();
- $theme = $site['theme'];
- }
- if($theme == 'yg') {
- $platformName = "阳光";
- } else if ($theme == 'px') {
- $platformName = "点看";
- } else if ($theme == 'sf') {
- $platformName = "沙发";
- } else if ($theme == 'qy') {
- $platformName = "袋鼠";
- } else {
- $platformName = "西瓜";
- }
- $bookInfo = BookService::instance()->getBookModel()->BookInfo($orders['book_id']);
- $productName = $bookInfo['name'] . '-' . $platformName;
- }
- //mp回传
- $mpType = $adminConfig['callback_time_mp'] ?? AdminConstants::CALLBACK_TIME_ONCE_24;
- LogService::info('mppaytype:' . $mpType . ':' . $userInfo['id']);
- $check = ToutiaoNotifyService::instance()->checkCallbackTime($userInfo['subscribe_time'], $mpType)->data;
- $sMpChuanKey = CacheConstants::getCallbackLimitMp($orders['user_id']);
- $sMpChuanKeyOnce = CacheConstants::getCallbackLimitMpOnce($orders['user_id']);
- if (in_array($mpType, [AdminConstants::CALLBACK_TIME_ONCE_24, AdminConstants::CALLBACK_TIME_ONCE_DAY])) {
- //已经回传过的
- if (Redis::instance()->get($sMpChuanKeyOnce)) {
- Redis::instance()->set($sMpChuanKey, $orders['id'], 86400);
- }
- } else {
- Redis::instance()->del($sMpChuanKey);
- }
- LogService::info('订阅活动-是否首充'.$userInfo['is_pay']);
- SubscripService::instance()->insertOldLog($userInfo);
- if ($check && !Redis::instance()->get($sMpChuanKey)) {
- //当天仅回传一次
- $guangdtKl = ReportKlService::instance()->getKlConfig($orders['admin_id'], PostbackConstants::TYPE_GUANGDIANTONG, $orders['referral_id'])->data;
- $ifNotKl = ReportKlService::instance()->checkNotKl($orders['admin_id'], $guangdtKl, $orders['referral_id'], $orders['money'])->data;
- if ($ifNotKl) {
- if (in_array($mpType, [AdminConstants::CALLBACK_TIME_ONCE_24, AdminConstants::CALLBACK_TIME_ONCE_DAY])) {
- //首次充值回传写入缓存
- Redis::instance()->set($sMpChuanKey, $orders['id'], 86400);
- }
- Redis::instance()->set($sMpChuanKeyOnce, $orders['id'], 86400);
- //微信AD数据源上报
- WeChatAdService::instance()->SendWxAdSource($channel_id,['url'=>$url, 'open_id'=>$userInfo['openid'], 'money'=>$orders['money'], 'product_name'=>$productName, 'product_id'=>$orders['book_id'], 'action_type'=>'COMPLETE_ORDER']);
- WeChatAdService::instance()->SendWxAdSource($channel_id,['url'=>$url, 'open_id'=>$userInfo['openid'], 'money'=>$orders['money'], 'product_name'=>$productName, 'product_id'=>$orders['book_id'], 'action_type'=>'PURCHASE']);
- // WeChatAdService::instance()->SendWxAdSource($channel_id,$url,$userInfo['openid'], $orders['money'], $productName);
- // WeChatAdService::instance()->SendWxAdSource($channel_id,$url,$userInfo['openid'], $orders['money'], $productName, 'PURCHASE');
- //回传总金额
- $orderReportKey = "CORDS:".$channel_id.":".date("Ymd");
- Redis::instance()->sAdd($orderReportKey, $orders['out_trade_no']);
- Redis::instance()->expire($orderReportKey, 86400*7);
- //Ab号回源
- if (!empty($orders['referral_id']) && $business == PayConstants::BUSINESS_WECHAT) {
- ReferralService::instance()->sendReferralAdData($orders['referral_id'], ['admin_id' => $channel_id, 'url' => $url, 'orders' => ['money' =>$orders['money'], 'productName' => $productName], 'openid' => $userInfo['openid'], 'action_type' => 'COMPLETE_ORDER', 'product_id'=>$orders['book_id']]);
- ReferralService::instance()->sendReferralAdData($orders['referral_id'], ['admin_id' => $channel_id, 'url' => $url, 'orders' => ['money' =>$orders['money'], 'productName' => $productName], 'openid' => $userInfo['openid'], 'action_type' => 'PURCHASE', 'product_id'=>$orders['book_id']]);
- }
- }
- }
- //gdt回传
- if (isset($adminConfig['gdt_mp_report_state']) && $adminConfig['gdt_mp_report_state'] == 1) {
- //回传设置走mp的
- $mpType = $adminConfig['callback_time_mp'] ?? AdminConstants::CALLBACK_TIME_ONCE_24;
- LogService::info('mppaytype:' . $mpType . ':' . $userInfo['id']);
- $check = ToutiaoNotifyService::instance()->checkCallbackTime($userInfo['subscribe_time'], $mpType)->data;
- $sGdtChuanKey = CacheConstants::getCallbackLimitGdt($orders['user_id']);
- $sGdtChuanKeyOnce = CacheConstants::getCallbackLimitGdtOnce($orders['user_id']);
- if (in_array($mpType, [AdminConstants::CALLBACK_TIME_ONCE_24, AdminConstants::CALLBACK_TIME_ONCE_DAY])) {
- //已经回传过的
- if (Redis::instance()->get($sGdtChuanKeyOnce)) {
- Redis::instance()->set($sGdtChuanKey, $orders['id'], 86400);
- }
- } else {
- Redis::instance()->del($sGdtChuanKey);
- }
- if ($check && !Redis::instance()->get($sGdtChuanKey)) {
- //当天仅回传一次
- $gdtKl = ReportKlService::instance()->getKlConfig($orders['admin_id'], PostbackConstants::TYPE_GDT, $orders['referral_id'])->data;
- $ifNotKl = ReportKlService::instance()->checkNotKl($orders['admin_id'], $gdtKl, $orders['referral_id'], $orders['money'])->data;
- if ($ifNotKl) {
- if (in_array($mpType, [AdminConstants::CALLBACK_TIME_ONCE_24, AdminConstants::CALLBACK_TIME_ONCE_DAY])) {
- //首次充值回传写入缓存
- Redis::instance()->set($sGdtChuanKey, $orders['id'], 86400);
- }
- Redis::instance()->set($sGdtChuanKeyOnce, $orders['id'], 86400);
- //数据源上报
- GdtMpApiService::instance()->completeOrder($adminConfig, ['action_type' => 'COMPLETE_ORDER', 'url' => $url, 'product_name' => $productName, 'money' => $orders['money'], 'appid' => $adminConfig['appid'], 'openid' => $userInfo['openid'], 'product_id'=>$orders['book_id']]);
- GdtMpApiService::instance()->completeOrder($adminConfig, ['action_type' => 'PURCHASE', 'url' => $url, 'product_name' => $productName, 'money' => $orders['money'], 'appid' => $adminConfig['appid'], 'openid' => $userInfo['openid'], 'product_id'=>$orders['book_id']]);
- //回传总金额
- $orderReportKey = "CORDS:G:".$channel_id.":".date("Ymd");
- Redis::instance()->sAdd($orderReportKey, $orders['out_trade_no']);
- Redis::instance()->expire($orderReportKey, 86400*7);
- }
- }
- }
- }
- if ($float_id = Redis::instance()->get(CacheConstants::getFloatTipsOrderId($orders['id']))) {
- FloatTipsService::instance()->updateFloatOrder($float_id, $orders['user_id'], $orders['money']);
- }
- $export = ExportFansService::instance()->checkFansLead($channel_id, $orders['user_id'])->data;
- if ($export) {
- $unrechargeKey = CacheConstants::getFansUnrecharge($orders['user_id']);
- Redis::instance()->del($unrechargeKey);
- }
- KuaifenService::instance()->reportOrders($oOrder);
- }
- private function _saveUserDot(Orders $orders)
- {
- // getUserInfo($orders['user_id'], true) 直接走数据库,缓存哩vip_endtime 不及时
- $user_info = model('User')->getUserInfo($orders['user_id'], true);
- $ip_redis_key = CacheConstants::USER_IP_PREFIX . $orders['user_id'];
- $ip_arr = json_decode(Redis::instance()->get($ip_redis_key), true, 1024);
- // region 用户画像打点到Nginx
- try{
- $dotdata = [
- 'ctime' => time(),
- 'uid' => $user_info['id'],
- 'openid' => $user_info['openid'],
- 'unionid' => '',
- 'ip' => $ip_arr['ip'] ?? '',
- 'country' => $ip_arr['country'] ?? '',
- 'province' => $ip_arr['province'] ?? '',
- 'city' => $ip_arr['city'] ?? '',
- 'pline' => empty(Config::get('site.theme')) ? 'xg' : Config::get('site.theme'),
- 'agent_id' => $user_info['agent_id'] ?? '',
- 'chid' => $user_info['channel_id'] ?? '',
- 'ua' => $ip_arr['ua'],
- 'cookie' => '',
- 'type' => 'pay',
- 'user' => [
- 'gender' => $user_info['sex'],
- 'is_subscribe' => $user_info['is_subscribe'],
- 'vip_endtime' => $user_info['vip_endtime'],
- 'subscribe_time' => $user_info['subscribe_time'],
- 'is_pay' => $user_info['is_pay'],
- 'referral_id' => $user_info['referral_id'],
- 'ext' => $user_info['ext'] ? json_decode($user_info['ext'], true) : [],
- ],
- 'content' => [
- 'order_id' => $orders['id'], // 订单ID
- 'discount' => $orders['money'],// 订单金额,单位 元
- ]
- ];
- curl_user_dot($dotdata);
- }catch (\Exception $exception){
- LogService::error("save_orders:_saveUserDot:".$exception->getMessage());
- }
- // endregion
- }
- /**
- * 书籍计费统计
- * @param $channel_id
- * @param $book_id
- * @param $recharge_money
- * @throws \Exception
- */
- private function bookConsumePayCollect($channel_id,$book_id,$recharge_money){
- $redis = Redis::instance();
- //设置渠道籍列表
- $collect_list_key = "BC-CL:".date("Ymd");
- $redis->sadd($collect_list_key,$channel_id);
- $redis->expire($collect_list_key,86400*2);
- //设置渠道商书籍列表
- $collect_channel_book_key = "BC-BL:{$channel_id}:".date("Ymd");
- $redis->sadd($collect_channel_book_key,$book_id);
- $redis->expire($collect_channel_book_key,86400*2);
- //设置渠道商对应书籍数据
- $collect_key = "BC:{$book_id}:{$channel_id}:".date("Ymd");
- if($data = json_decode($redis->get($collect_key),true)){
- $data['recharge_num'] = intval($data['recharge_num'] ?? 0)+1;
- $data['recharge_money'] = intval($data['recharge_money'] ?? 0) + intval($recharge_money * 100);
- $redis->setex($collect_key,86400*2,json_encode($data));
- }else{
- $data['recharge_num'] = intval($data['recharge_num'] ?? 0)+1;
- $data['recharge_money'] = intval($data['recharge_money'] ?? 0) + intval($recharge_money * 100);
- $redis->setex($collect_key,86400*2,json_encode($data));
- }
- }
- /**
- * 分账金额
- * @param $orderInfo
- * @return int
- * @throws \think\exception\DbException
- */
- public function splitMoney($orderInfo)
- {
- $splitMoney = 0;
- if ($orderInfo['deduct']) {
- return $splitMoney;
- }
- if ($orderInfo['payment_method'] == ApiConstants::PAYMENT_METHOD_PALM) {
- //四分支付
- $payInfo = model('Wxpay')->getInfoById($orderInfo['wxpay_id']);
- if ($payInfo && $payInfo['quartet_is_split'] == ApiConstants::QUARTET_IS_SPLIT) {
- //开启分账 查找分账订单
- $splitRow = PalmpaySplitAccountLog::get(['order_id' => $orderInfo['out_trade_no']]);
- if ($splitRow && $splitRow['channel_amount']) {
- $splitMoney = $splitRow['channel_amount'];
- }
- }
- }
- return $splitMoney;
- }
- }
|