Wechat.php 119 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304
  1. <?php
  2. namespace app\api\controller;
  3. use app\admin\model\PalmpaySplitAccountLog;
  4. use app\common\constants\BigData;
  5. use app\common\controller\Api;
  6. use app\common\library\Redis;
  7. use app\common\library\WeChatObject;
  8. use app\common\model\Orders;
  9. use app\common\service\CampaignService;
  10. use app\common\service\KuaifenService;
  11. use app\common\service\UserVipExtendService;
  12. use app\common\utility\WhiteList;
  13. use app\main\constants\AdminConstants;
  14. use app\main\constants\ApiConstants;
  15. use app\main\constants\CacheConstants;
  16. use app\main\constants\CampaignConstants;
  17. use app\main\constants\ErrorCodeConstants;
  18. use app\main\constants\KafkaDotConstants;
  19. use app\main\constants\MqConstants;
  20. use app\main\constants\OpenPlatformConstants;
  21. use app\main\constants\OrderContents;
  22. use app\main\constants\PayConstants;
  23. use app\main\constants\PostbackConstants;
  24. use app\main\constants\UcCacheConstants;
  25. use app\main\model\object\AnalysisObject;
  26. use app\main\model\object\DotBookCollectObject;
  27. use app\main\model\object\DotObject;
  28. use app\main\model\object\OrderObject;
  29. use app\main\model\object\UserObject;
  30. use app\main\service\ActivityService;
  31. use app\main\service\AdminKlService;
  32. use app\main\service\AdminService;
  33. use app\main\service\AliH5PayService;
  34. use app\main\service\ApiService;
  35. use app\main\service\BookDotService;
  36. use app\main\service\BookService;
  37. use app\main\service\BuyMoreService;
  38. use app\main\service\ExportFansService;
  39. use app\main\service\FinancialService;
  40. use app\main\service\FloatTipsService;
  41. use app\main\service\GdtMpApiService;
  42. use app\main\service\GdtService;
  43. use app\main\service\IpaynowPayService;
  44. use app\main\service\KafkaDotService;
  45. use app\main\service\LogService;
  46. use app\main\service\MihuaPayService;
  47. use app\main\service\MqService;
  48. use app\main\service\MqUserPaySuccessService;
  49. use app\main\service\OfficialAccountsEventService;
  50. use app\main\service\OfficialAccountsService;
  51. use app\main\service\OpenPlatformService;
  52. use app\main\service\OrderService;
  53. use app\main\service\ReferralService;
  54. use app\main\service\ReportKlService;
  55. use app\main\service\SinglePushService;
  56. use app\main\service\SmartPushDotService;
  57. use app\main\service\SubscripService;
  58. use app\main\service\ToutiaoNotifyService;
  59. use app\main\service\UcNotifyService;
  60. use app\main\service\UnsPayService;
  61. use app\main\service\UrlService;
  62. use app\main\service\UserService;
  63. use app\main\service\WeChatAdService;
  64. use app\main\service\WechatH5Payservice;
  65. use app\source\model\UserUpdate;
  66. use EasyWeChat\Factory;
  67. use EasyWeChat\Kernel\Support\XML;
  68. use EasyWeChat\OpenPlatform\Server\Guard;
  69. use Symfony\Component\Cache\Simple\RedisCache;
  70. use think\Config;
  71. use think\Log;
  72. use think\Request;
  73. class Wechat extends Api
  74. {
  75. /**
  76. * 检测权限
  77. * @param $authUser
  78. * @throws \Exception
  79. */
  80. private function checkWeChatAuth($authUser)
  81. {
  82. if (!isset($authUser['authorizer_info']['service_type_info']['id'])) {
  83. throw new \Exception('获取授权信息失败,请重新扫码授权');
  84. }
  85. if ($authUser['authorizer_info']['service_type_info']['id'] != 2) {
  86. throw new \Exception('当前授权公众号类型非服务号,请使用服务号进行扫码');
  87. }
  88. if ($authUser['authorizer_info']['verify_type_info']['id'] == -1) {
  89. throw new \Exception('当前授权服务号未认证,请使用认证服务号进行扫码');
  90. }
  91. $authList = array_column(array_column($authUser['authorization_info']['func_info'], 'funcscope_category'), 'id');
  92. if (empty($authList)) {
  93. throw new \Exception('获取授权信息失败');
  94. }
  95. if (!in_array(1, $authList)) {
  96. throw new \Exception('必须授予-消息管理权限');
  97. }
  98. if (!in_array(15, $authList)) {
  99. throw new \Exception('必须授予-自定义菜单权限');
  100. }
  101. if (!in_array(4, $authList)) {
  102. throw new \Exception('必须授予-网页服务权限');
  103. }
  104. if (!in_array(2, $authList)) {
  105. throw new \Exception('必须授予-用户管理权限');
  106. }
  107. if (!in_array(3, $authList)) {
  108. throw new \Exception('必须授予-帐号服务权限');
  109. }
  110. if (!in_array(11, $authList)) {
  111. throw new \Exception('必须授予-素材管理权限');
  112. }
  113. if(!in_array(23,$authList)){
  114. throw new \Exception('必须授予-广告管理权限');
  115. }
  116. }
  117. /**
  118. * 接收open开放平台事件通知
  119. */
  120. public function opticket()
  121. {
  122. Log::info('[ WeChat ] [ OPEN ] [ Ticket ] GET: ' . json_encode(var_export($this->request->get(), true),
  123. JSON_UNESCAPED_UNICODE));
  124. Log::info('[ WeChat ] [ OPEN ] [ Ticket ] INPUT: ' . json_encode(var_export($this->request->getInput(), true),
  125. JSON_UNESCAPED_UNICODE));
  126. $request = XML::parse($this->request->getInput());
  127. $result = OpenPlatformService::instance()->initPlatformByAppId($request['AppId']);
  128. if($result->code != ErrorCodeConstants::SUCCESS){
  129. $this->error($result->msg);
  130. }
  131. $openPlatform = OpenPlatformService::instance()->getOpenPlatform();
  132. $openPlatform['cache'] = new RedisCache(Redis::instanceCache());
  133. $server = $openPlatform->server;
  134. Log::info('[ WeChat ] [ OPEN ] [ Ticket ] Message: ' . json_encode(var_export($server->getMessage(), true),
  135. JSON_UNESCAPED_UNICODE));
  136. // 处理授权成功事件 //callback中已处理
  137. // $server->push(function ($message) {
  138. // }, Guard::EVENT_AUTHORIZED);
  139. // 处理授权更新事件
  140. $server->push(function ($message) use ($openPlatform) {
  141. try {
  142. $appid = $message['AuthorizerAppid'];
  143. $platformAppid = $message['AppId'];
  144. $authCode = $message['AuthorizationCode'];
  145. $auth = $openPlatform->handleAuthorize($authCode); // 使用授权码换取接口调用凭据和授权信息
  146. $mp = $openPlatform->getAuthorizer($appid); // 获取授权方的帐号基本信息
  147. //检测权限
  148. $this->checkWeChatAuth($mp);
  149. $data = [
  150. 'refresh_token' => $auth['authorization_info']['authorizer_refresh_token'],
  151. 'json' => $mp,
  152. 'is_auth' => 1,
  153. ];
  154. model('AdminConfig')->update($data, ['appid' => $appid]);
  155. //维护Ptoken信息
  156. if ($adminConfig = model('AdminConfig')->getAdminInfoByAppId($appid)) {
  157. if ($platform = model('Platform')->where(['appid' => $platformAppid])->find()) {
  158. $map = ['admin_id' => $adminConfig['admin_id'], 'platform_id' => $platform['id']];
  159. if (model('Ptoken')->where($map)->find()) {
  160. model('Ptoken')->where($map)->update(['refresh_token' => $auth['authorization_info']['authorizer_refresh_token'], 'updatetime' => time()]);
  161. } else {
  162. model('Ptoken')->insert(array_merge($map, ['refresh_token' => $auth['authorization_info']['authorizer_refresh_token'], 'createtime' => time(), 'updatetime' => time()]));
  163. }
  164. }
  165. }
  166. } catch (\Exception $e) {
  167. Log::info("API 授权更新回调错误,Error:" . $e->getMessage());
  168. }
  169. }, Guard::EVENT_UPDATE_AUTHORIZED);
  170. // 处理授权取消事件
  171. $server->push(function ($message) {
  172. try{
  173. $appid = $message['AuthorizerAppid'];
  174. $platformAppid = $message['AppId'];
  175. if ($appid != 'wx570bc396a51b8ff8') {
  176. $data = [
  177. 'is_auth' => 0,
  178. 'wx_ad_source_id' => 0,
  179. 'wx_ad_state' => 0
  180. ];
  181. model('AdminConfig')->update($data, ['appid' => $appid]);
  182. //维护Ptoken信息
  183. if ($adminConfig = model('AdminConfig')->getAdminInfoByAppId($appid)) {
  184. if ($platform = model('Platform')->where(['appid' => $platformAppid])->find()) {
  185. $map = ['admin_id' => $adminConfig['admin_id'], 'platform_id' => $platform['id']];
  186. if (model('Ptoken')->where($map)->find()) {
  187. model('Ptoken')->where($map)->delete();
  188. }
  189. }
  190. }
  191. }
  192. }catch (\Exception $e) {
  193. Log::info("API 取消授权回调错误,Error:" . $e->getMessage());
  194. }
  195. }, Guard::EVENT_UNAUTHORIZED);
  196. $server->serve()->send();
  197. LogService::info("REQUEST_TIME_END:".microtime(true));
  198. }
  199. /**
  200. * 初始化平台参数
  201. */
  202. public function initPlatform()
  203. {
  204. $mOphost = OfficialAccountsService::instance()->getOphostModel();
  205. $hosts = $mOphost->getHosts();
  206. $host = UrlService::instance()->getSourceDomain();
  207. if (in_array($host, $hosts) && $ophost = $mOphost->getInfoByHost($host)) {
  208. $result = OpenPlatformService::instance()->initPlatformById($ophost['platform_id']);
  209. if($result->code != ErrorCodeConstants::SUCCESS){
  210. $this->error($result->msg);
  211. }
  212. } else {
  213. LogService::info('API_LOG 未匹配到域名信息:' . $host . ':' . json_encode($hosts));
  214. }
  215. }
  216. /**
  217. * 接收mp公众平台消息与事件
  218. */
  219. public function mpapi($appid)
  220. {
  221. LogService::info('[ WeChat ] [ MP ] [ API ] GET: ' . json_encode(var_export($this->request->get(), true),
  222. JSON_UNESCAPED_UNICODE));
  223. LogService::info('[ WeChat ] [ MP ] [ API ] INPUT: ' . json_encode(var_export($this->request->getInput(), true),
  224. JSON_UNESCAPED_UNICODE));
  225. $this->initPlatform();
  226. try {
  227. if (in_array($appid, OpenPlatformConstants::$app_id_for_all)) { //全网发布处理
  228. OfficialAccountsEventService::instance()->eventForAllNet($appid);
  229. } else { //正常业务处理
  230. $result = OfficialAccountsEventService::instance()->eventForNormal($appid);
  231. if($result->msg){
  232. return;
  233. }
  234. }
  235. } catch (\Exception $e) {
  236. LogService::exception($e);
  237. }
  238. LogService::info("REQUEST_TIME_END:".microtime(true));
  239. OfficialAccountsEventService::instance()->processCallbackUserInfo($appid);
  240. }
  241. /**
  242. * 根据 admin_id 获取 appid,token
  243. */
  244. public function getToken()
  245. {
  246. $admin_id = $this->request->param('admin_id');
  247. $data = [];
  248. $errMsg = '';
  249. try {
  250. if (!$admin_id) {
  251. $this->error('缺少参数');
  252. }
  253. $adminConfig = model('AdminConfig')->getAdminInfoAll($admin_id);
  254. if (!$adminConfig) {
  255. $this->error('无此数据');
  256. }
  257. $wechat = new WeChatObject($adminConfig);
  258. $officialAccount = $wechat->getOfficialAccount();
  259. $token = $officialAccount->access_token->getToken();
  260. if (!is_array($token) || !array_key_exists('authorizer_access_token', $token)) {
  261. $errMsg = '获取token失败';
  262. } else {
  263. $proxy = OpenPlatformService::instance()->getProxyconfigByChannel($admin_id, null, 'job_proxy_config',true);
  264. $data = [
  265. 'appid' => $adminConfig['appid'],
  266. 'token' => $token['authorizer_access_token'],
  267. 'proxy_config' => $proxy ?: [],
  268. ];
  269. }
  270. } catch (\Exception $exception) {
  271. Log::info('API getToken触发异常!admin_id:' . $admin_id . ' message:' . $exception->getMessage());
  272. $this->error('获取异常'.json_encode(['errcode' => $exception->getCode(), 'errmsg' => $exception->getMessage()]));
  273. }
  274. if (!empty($data)) {
  275. exit(json_encode(['code' => 1, 'msg' => 'success', 'time' => time(), 'data' => $data], JSON_UNESCAPED_SLASHES));
  276. //$this->success('success', $data);
  277. } else {
  278. $this->error($errMsg);
  279. }
  280. }
  281. /**
  282. * 根据 admin_id 获取业务域名
  283. */
  284. public function getUrl()
  285. {
  286. $admin_id = $this->request->param('admin_id');
  287. $data = [];
  288. $errMsg = '';
  289. try {
  290. if (!$admin_id) {
  291. $this->error('缺少参数');
  292. }
  293. $info = model('AdminConfig')->getAdminInfoAll($admin_id);
  294. if (!empty($info) && $info['ophost_host']) {
  295. $data = [
  296. 'url' => $info['ophost_host'],
  297. ];
  298. } else {
  299. $errMsg = '获取业务域名失败!';
  300. }
  301. } catch (\Exception $exception) {
  302. Log::error('API getUrl触发异常!admin_id:' . $admin_id . ' message:' . $exception->getMessage());
  303. $this->error('获取异常'.json_encode(['errcode' => $exception->getCode(), 'errmsg' => $exception->getMessage()]));
  304. }
  305. if (!empty($data)) {
  306. $this->success('success', $data);
  307. } else {
  308. $this->error($errMsg);
  309. }
  310. }
  311. /**
  312. * 微信支付回调
  313. */
  314. public function pay()
  315. {
  316. Log::info('[ WeChat ] [ PAY ] [ CALLBACK ] GET: ' . json_encode(var_export($this->request->get(), true),
  317. JSON_UNESCAPED_UNICODE));
  318. Log::info('[ WeChat ] [ PAY ] [ CALLBACK ] INPUT: ' . json_encode(var_export($this->request->getInput(), true),
  319. JSON_UNESCAPED_UNICODE));
  320. $paymentApplication = Factory::payment(Config::get('wechat'));
  321. $paymentApplication['cache'] = new RedisCache(Redis::instanceCache());
  322. $parent_point = $this;
  323. $response = $paymentApplication->handlePaidNotify(function ($message, $fail) use ($parent_point) {
  324. Log::info('[ WeChat ] [ PAY ] [ CALLBACK ] Message: ' . json_encode(var_export($message, true),
  325. JSON_UNESCAPED_UNICODE));
  326. if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态,不代表支付状态
  327. if (isset($message['result_code']) && $message['result_code'] === 'SUCCESS') { // 用户是否支付成功
  328. $orders = model('Orders')->get(['out_trade_no' => $message['out_trade_no']]);
  329. if ($orders['state'] == 1) { // 已支付
  330. return true;
  331. }
  332. $parent_point->saveOrder($orders, $message['transaction_id'], '');
  333. Log::info(sprintf('wechatpay_callback_success!wxpay_id:%s,channel_id:%s,money:%s,good_id:%s,out_trade_no:%s'
  334. , $orders['wxpay_id'], $orders['admin_id'], $orders['money'], $orders['goods_id'],
  335. $orders['out_trade_no']));
  336. return true;
  337. } elseif (!isset($message['result_code']) || $message['result_code'] === 'FAIL') { // 用户支付失败
  338. return true;
  339. } else {
  340. return $fail('参数错误,请稍后再通知我');
  341. }
  342. } else {
  343. return $fail('通信失败,请稍后再通知我');
  344. }
  345. });
  346. $response->send();
  347. }
  348. /**
  349. * 四方支付回调
  350. */
  351. public function palmpay()
  352. {
  353. Log::info('[ palmpay ] [ PAY ] [ CALLBACK ] GET: ' . json_encode(var_export($this->request->get(), true),
  354. JSON_UNESCAPED_UNICODE));
  355. Log::info('[ palmpay ] [ PAY ] [ CALLBACK ] INPUT: ' . json_encode(var_export($this->request->getInput(), true),
  356. JSON_UNESCAPED_UNICODE));
  357. $params = $this->request->post();
  358. if (isset($params['status']) && $params['status'] === 'success') {
  359. $order = model('Orders')->get(['out_trade_no' => $params['outTradeNo']]);
  360. if ($order['state'] == 1) {
  361. Log::info('订单已经支付,out_trade_no:' . $params['outTradeNo']);
  362. return 'success';
  363. }
  364. $payInfo = model('Wxpay')->getInfoByHost($this->currentPayHost);
  365. if (empty($payInfo['quartet_app_key'])) {
  366. Log::error('quartet_app_key不存在');
  367. return 'quartet_app_key不存在';
  368. }
  369. $appKey = $payInfo['quartet_app_key'];
  370. if (!$this->_checkSign($params, $appKey)) {
  371. Log::error('sign校验失败');
  372. return 'sign校验失败';
  373. }
  374. Log::info(sprintf('palmpay_callback_success!wxpay_id:%s,channel_id:%s,money:%s,good_id:%s,out_trade_no:%s'
  375. , $order['wxpay_id'], $order['admin_id'], $order['money'], $order['goods_id'],
  376. $order['out_trade_no']));
  377. $this->saveOrder($order, $params['chorderid'], $params['pdorderid']);
  378. Log::info('订单支付回调成功,pdorderid:' . $params['pdorderid']);
  379. return 'success';
  380. } else {
  381. $status = empty($params['status']) ? -1 : $params['status'];
  382. Log::error('充值不成功,status:' . $status);
  383. return $status;
  384. }
  385. }
  386. /**
  387. * 汇聚支付回调
  388. */
  389. public function joinpay()
  390. {
  391. Log::info('[ joinpay ] [ PAY ] [ CALLBACK ] GET: ' . json_encode(var_export($this->request->get(), true),
  392. JSON_UNESCAPED_UNICODE));
  393. Log::info('[ joinpay ] [ PAY ] [ CALLBACK ] INPUT: ' . json_encode(var_export($this->request->getInput(), true),
  394. JSON_UNESCAPED_UNICODE));
  395. $params = $this->request->get();
  396. if (isset($params['r6_Status']) && $params['r6_Status'] == 100) {
  397. $order = model('Orders')->get(['out_trade_no' => $params['r2_OrderNo']]);
  398. if ($order['state'] == 1) {
  399. Log::info('订单已经支付,out_trade_no:' . $params['r2_OrderNo']);
  400. return 'success';
  401. }
  402. Log::info(sprintf('joinpay_callback_success!wxpay_id:%s,channel_id:%s,money:%s,good_id:%s,out_trade_no:%s'
  403. , $order['wxpay_id'], $order['admin_id'], $order['money'], $order['goods_id'],
  404. $order['out_trade_no']));
  405. $this->saveOrder($order, $params['r7_TrxNo'], '');
  406. Log::info('订单支付回调成功,transaction_id:' . $params['r7_TrxNo']);
  407. return 'success';
  408. } else {
  409. $status = empty($params['r6_Status']) ? -1 : $params['r6_Status'];
  410. Log::error('充值不成功,status:' . $status);
  411. return $status;
  412. }
  413. }
  414. public function mihuapay()
  415. {
  416. Config::set('app_trace', false);
  417. Log::info('[ mihuapay ] [ PAY ] [ CALLBACK ] GET: ' . json_encode(var_export($this->request->get(), true),
  418. JSON_UNESCAPED_UNICODE));
  419. Log::info('[ mihuapay ] [ PAY ] [ CALLBACK ] INPUT: ' . json_encode(var_export($this->request->getInput(),
  420. true),
  421. JSON_UNESCAPED_UNICODE));
  422. $params = $this->request->get();
  423. $pureHost = UrlService::instance()->getSourceDomain();
  424. $payInfo = model('Wxpay')->getInfoByHost($pureHost);
  425. if (empty($payInfo)) {
  426. Log::error('回调域名对应的支付信息不存在。host:' . $pureHost);
  427. return '';
  428. }
  429. $data = $params['data'];
  430. $mihuaService = MihuaPayService::instance($payInfo['quartet_app_key'],
  431. $payInfo['quartet_app_public_key']);
  432. $jsonStr = $mihuaService->decrypt($data);
  433. Log::info(sprintf('支付回调返回值明文:%s', $jsonStr));
  434. $result = json_decode($jsonStr, true);
  435. if ($mihuaService->checkSign($result)) {
  436. if ($result['orderStatus'] == 'SUCCESS') {
  437. $order = model('Orders')->get(['out_trade_no' => $result['orderId']]);
  438. if ($order['state'] == 1) {
  439. Log::info('订单已经支付,out_trade_no:' . $result['orderId']);
  440. return 'SUCCESS';
  441. }
  442. Log::info(sprintf('mihuapay_callback_success!wxpay_id:%s,channel_id:%s,money:%s,good_id:%s,out_trade_no:%s'
  443. , $order['wxpay_id'], $order['admin_id'], $order['money'], $order['goods_id'],
  444. $order['out_trade_no']));
  445. $transactionId = empty($result['bankOrderNo']) ? $result['mbOrderId'] : $result['bankOrderNo'];
  446. $this->saveOrder($order, $transactionId, '');
  447. Log::info('订单支付回调成功,transaction_id:' . $transactionId);
  448. return 'SUCCESS';
  449. } else {
  450. Log::error('米花支付回调失败,msg:' . $jsonStr);
  451. return '';
  452. }
  453. } else {
  454. Log::error('公钥验证签名出错,msg:' . $jsonStr);
  455. return '';
  456. }
  457. }
  458. public function unspay()
  459. {
  460. Config::set('app_trace', false);
  461. Log::info('[ unsapay ] [ PAY ] [ CALLBACK ] POST: ' . json_encode(var_export($this->request->post(), true),
  462. JSON_UNESCAPED_UNICODE));
  463. Log::info('[ unsapay ] [ PAY ] [ CALLBACK ] INPUT: ' . json_encode(var_export($this->request->getInput(),
  464. true),
  465. JSON_UNESCAPED_UNICODE));
  466. $params = $this->request->post();
  467. $pureHost = UrlService::instance()->getSourceDomain();
  468. $payInfo = model('Wxpay')->getInfoByHost($pureHost);
  469. if (empty($payInfo)) {
  470. Log::error('回调域名对应的支付信息不存在。host:' . $pureHost);
  471. return '';
  472. }
  473. $params['accountId'] = $payInfo['quartet_app_id'];
  474. $verifyResponseResult = UnsPayService::instance($payInfo['quartet_app_key'])->verifyCallbackMacParams($params);
  475. if (isset($params['result_code']) && $params['result_code'] == '0000' && $verifyResponseResult) {
  476. $order = model('Orders')->get(['out_trade_no' => $params['orderId']]);
  477. if ($order['state'] == 1) {
  478. Log::info('订单已经支付,out_trade_no:' . $params['r2_OrderNo']);
  479. $aResult = [
  480. 'result_code' => "000000",
  481. 'channel_refund_trade_no' => $order['transaction_id'],
  482. ];
  483. return json_encode($aResult);
  484. }
  485. Log::info(sprintf('unspay_callback_success!wxpay_id:%s,channel_id:%s,money:%s,good_id:%s,out_trade_no:%s'
  486. , $order['wxpay_id'], $order['admin_id'], $order['money'], $order['goods_id'],
  487. $order['out_trade_no']));
  488. $this->saveOrder($order, $params['channel_refund_trade_no']);
  489. Log::info('订单支付回调成功,transaction_id:' . $params['channel_refund_trade_no']);
  490. $aResult = [
  491. 'result_code' => "000000",
  492. 'channel_refund_trade_no' => $params['channel_refund_trade_no'],
  493. ];
  494. return json_encode($aResult);
  495. } else {
  496. Log::error('充值不成功,result_code:' . $params['result_code']);
  497. return $params['result_code'];
  498. }
  499. }
  500. public function ipaynowpay()
  501. {
  502. Config::set('app_trace', false);
  503. Log::info('[ ipaynowpay ] [ PAY ] [ CALLBACK ] POST: ' . json_encode(var_export($this->request->post(), true),
  504. JSON_UNESCAPED_UNICODE));
  505. Log::info('[ ipaynowpay ] [ PAY ] [ CALLBACK ] INPUT: ' . json_encode(var_export($this->request->getInput(),
  506. true), JSON_UNESCAPED_UNICODE));
  507. $strParams = $this->request->getInput();
  508. parse_str($strParams, $params);
  509. $payInfo = model('Wxpay')->getInfoByHost($this->currentPayHost);
  510. $verifyResult = IpaynowPayService::instance($payInfo['quartet_app_private_no'])->verifySign($params);
  511. if (isset($params['transStatus']) && $params['transStatus'] === 'A001' && $verifyResult) {
  512. $order = model('Orders')->get(['out_trade_no' => $params['mhtOrderNo']]);
  513. if ($order['state'] == 1) {
  514. Log::info('订单已经支付,out_trade_no:' . $params['mhtOrderNo']);
  515. return 'success=Y';
  516. }
  517. Log::info(sprintf('ipaynow_callback_success!wxpay_id:%s,channel_id:%s,money:%s,good_id:%s,out_trade_no:%s'
  518. , $order['wxpay_id'], $order['admin_id'], $order['money'], $order['goods_id'],
  519. $order['out_trade_no']));
  520. $this->saveOrder($order, $params['channelOrderNo'], $params['nowPayOrderNo']);
  521. Log::info('订单支付回调成功,mhtOrderNo:' . $params['mhtOrderNo']);
  522. return 'success=Y';
  523. } else {
  524. $status = empty($params['transStatus']) ? -1 : $params['transStatus'];
  525. Log::error('充值不成功,status:' . $status);
  526. return 'success=N';
  527. }
  528. }
  529. /**
  530. * 支付宝h5支付
  531. */
  532. public function alih5pay()
  533. {
  534. Log::info('[ WECHAT ] [ PAY ] [ CALLBACK ] GET: ' . json_encode(var_export($this->request->get(), true)));
  535. try {
  536. $alipay = AliH5PayService::instance()->init(ApiConstants::PAYMENT_METHOD_ALIPAYH5)->initPay();
  537. $data = $alipay->verify();
  538. LogService::debug('Alipay notify' . $data->toJson());
  539. $out_trade_no = $data->get("out_trade_no");
  540. $orders = model('Orders')->get(['out_trade_no' => $out_trade_no]);
  541. if ($orders['state'] != OrderContents::ORDER_STATE_PAID) { // 已支付
  542. $this->saveOrder($orders, $data->get('trade_no'));
  543. Log::info(sprintf('alih5pay_callback_success!wxpay_id:%s,channel_id:%s,money:%s,good_id:%s,out_trade_no:%s'
  544. , $orders['wxpay_id'], $orders['admin_id'], $orders['money'], $orders['goods_id'],
  545. $orders['out_trade_no']));
  546. }
  547. return $alipay->success()->send();
  548. } catch (\Exception $e) {
  549. LogService::exception($e);
  550. }
  551. }
  552. /**
  553. * 微信支付回调
  554. */
  555. public function wxh5pay()
  556. {
  557. Log::info('[ WeChat ] [ PAY ] [ CALLBACK ] GET: ' . json_encode(var_export($this->request->get(), true),
  558. JSON_UNESCAPED_UNICODE));
  559. Log::info('[ WeChat ] [ PAY ] [ CALLBACK ] INPUT: ' . json_encode(var_export($this->request->getInput(), true),
  560. JSON_UNESCAPED_UNICODE));
  561. try {
  562. $wxPay = WechatH5Payservice::instance()->init(ApiConstants::PAYMENT_METHOD_WECHATH5)->initPay();
  563. $data = $wxPay->verify();
  564. LogService::debug('wxPay notify' . $data->toJson());
  565. $out_trade_no = $data->get("out_trade_no");
  566. $orders = model('Orders')->get(['out_trade_no' => $out_trade_no]);
  567. if ($orders['state'] != OrderContents::ORDER_STATE_PAID) { // 已支付
  568. $this->saveOrder($orders, $data->get('trade_no'));
  569. Log::info(sprintf('alih5pay_callback_success!wxpay_id:%s,channel_id:%s,money:%s,good_id:%s,out_trade_no:%s'
  570. , $orders['wxpay_id'], $orders['admin_id'], $orders['money'], $orders['goods_id'],
  571. $orders['out_trade_no']));
  572. }
  573. return $wxPay->success()->send();
  574. } catch (\Exception $e) {
  575. LogService::exception($e);
  576. }
  577. }
  578. /**
  579. * 校验回调签名
  580. * @param $params post参数
  581. * @param $appKey
  582. * @return bool
  583. */
  584. private function _checkSign($params, $appKey)
  585. {
  586. if (!isset($params['sign'])) {
  587. Log::error('sign不存在');
  588. return false;
  589. }
  590. $arrSign = [];
  591. ksort($params);
  592. $originalSign = $params['sign'];
  593. foreach ($params as $k => $param) {
  594. if ($k == 'sign') {
  595. continue;
  596. }
  597. $strTmp = trim($k) . '=' . trim($param);
  598. $arrSign[] = $strTmp;
  599. }
  600. $arrSign[] = 'key=' . $appKey;
  601. $strSign = implode('&', $arrSign);
  602. $sign = md5($strSign);
  603. return $originalSign == $sign;
  604. }
  605. /**
  606. * 保存订单信息,并保存统计信息
  607. * @param $orders
  608. * @param string $transactionId 微信支付订单号
  609. * @param string $pdorderid 四方支付订单号
  610. */
  611. private function saveOrder(Orders $orders, $transactionId = '', $pdorderid = '')
  612. {
  613. $time = Request::instance()->server('REQUEST_TIME');
  614. $business = $orders->business_line??'0';
  615. $oOrder = (new OrderObject())->bind($orders->getData());
  616. $cacheKey = OrderService::instance()->getOrderCacheKey($oOrder)->data;
  617. LogService::debug("清除缓存:" . $cacheKey);
  618. Redis::instance()->delete($cacheKey);
  619. if (!OrderService::instance()->getOrderModel()->update([
  620. 'transaction_id' => $transactionId,
  621. 'pdorderid' => $pdorderid,
  622. 'state' => OrderContents::ORDER_STATE_PAID,
  623. 'finishtime' => $time,
  624. 'updatetime' => $time,
  625. ], ['id' => $orders['id'], 'state' => OrderContents::ORDER_STATE_TO_PAY])) {
  626. LogService::error('订单未更新');
  627. return;
  628. }
  629. BuyMoreService::instance()->checkOrderBuyMore($orders['user_id'], $orders['out_trade_no'], $orders['id']);
  630. //如果为复粉支付号,加入用户缓存
  631. $wxpay = OfficialAccountsService::instance()->getWxpayModel()->getInfoById($oOrder->wxpay_id);
  632. if ($wxpay['fufen']) {
  633. $cache = CacheConstants::getWxpayFunfen($oOrder->user_id);
  634. Redis::instance()->sAdd($cache, $oOrder->wxpay_id);
  635. }
  636. //记录用户充值完成时间
  637. WhiteList::addUserPayTime($orders['user_id']);
  638. //处理取消充值redis标志位
  639. $redis = Redis::instance();
  640. $payCancelKey = "O-C:{$orders['user_id']}:{$orders['goods_id']}";
  641. if ($redis->exists($payCancelKey)) {
  642. //redis标记设置
  643. $redis->setex($payCancelKey, 600, 2); // (600秒)10分钟 状态改为2
  644. }
  645. //取消充值ssdb首充标志位
  646. $userInfo = model('User')->getUserInfo($orders['user_id']);
  647. //起充人数
  648. $cid = AdminService::instance()->getAdminExtendModel()->getChannelId($userInfo['channel_id']);
  649. $cacheKey = CacheConstants::getPayUserLimitCacheKey($cid);
  650. Redis::instance()->pfAdd($cacheKey, $userInfo['id']);
  651. Redis::instance()->expire($cacheKey, 86400);
  652. if (Config::get('site.smallpay_goods_id') == $orders['goods_id']) {
  653. $cacheKey = CacheConstants::getSmallPayCache($orders['user_id']);
  654. Redis::instance()->set($cacheKey, 1);
  655. }
  656. $cacheOrderCount = CacheConstants::getUserOrderCompletedCountCacheKey($orders['user_id']);
  657. if ($count = Redis::instance()->get($cacheOrderCount)) {
  658. Redis::instance()->incr($cacheOrderCount);
  659. } else {
  660. $count = OrderService::instance()->getOrderModel()
  661. ->where('user_id', $orders['user_id'])
  662. ->where('state', OrderContents::ORDER_STATE_PAID)
  663. ->count();
  664. Redis::instance()->set($cacheOrderCount, $count + 1);
  665. }
  666. //未设置的,都按已激活算
  667. $isPay = $userInfo['first_cancel_pay'] ?? 1;
  668. if($isPay){
  669. // $is_update = model('User')
  670. // ->setConnect($orders['user_id'])
  671. // ->where('id',$orders['user_id'])
  672. // ->update(['first_cancel_pay'=>0]);
  673. $is_update = UserService::instance()->update(['first_cancel_pay' => 0], ['id' => $orders['user_id']]);
  674. if($is_update === false){
  675. Log::error("支付回调: UserId:{$orders['user_id']} first_cancel_pay:0 更新用户首冲标志位失败");
  676. }
  677. $redis->del("UN:{$orders['user_id']}");
  678. }
  679. $this_money_benefit = round($orders['money_benefit'], 2);
  680. //写统计数据
  681. //今天
  682. $today = date('Ymd', $orders['createtime']);
  683. //本月
  684. // //统计活动充值
  685. $oAna = new AnalysisObject();
  686. $oAna->event_time = $oOrder->createtime;
  687. $oAna->type = KafkaDotConstants::TYPE_ORDER_COMPLETE;
  688. $oAna->data = [
  689. 'orders_type' => $orders['type'],
  690. 'money' => $orders['money'],
  691. 'user_collect' => 1,
  692. ];
  693. if ($orders['book_id']) {
  694. $oAna->data['book_id'] = $orders['book_id'];
  695. }
  696. try {
  697. //活动且非扣量,进行数据统计
  698. if ($oOrder->activity_id && !$oOrder->resource_id) {
  699. // $oAna->user_from['activity_id'] = $oOrder->activity_id;
  700. $oActivityAna = new AnalysisObject();
  701. $oActivityAna->type = KafkaDotConstants::TYPE_ACTIVITY;
  702. $oActivityAna->user_from = [
  703. 'activity_id' => $oOrder->admin_id
  704. ];
  705. $oActivityAna->data = [
  706. 'stage' => 'end'
  707. ];
  708. KafkaDotService::instance()->sendMsg($oOrder->user_id, $oActivityAna);
  709. //如果是渠道自定义活动在处理
  710. if(model('Activity')->checkIsChannelActivity($orders->activity_id)){
  711. $pay_count_key = "ATPU:{$orders['activity_id']}";
  712. $activity_config = Config::get('site.activity_config');
  713. $redis->hIncrBy($pay_count_key,$orders['user_id'],1);
  714. $redis->expire($pay_count_key,(intval($activity_config['time_interval'])*86400)*2);
  715. }
  716. $activityCollect = model('ActivityCollect');
  717. $activityCollectAll = model('ActivityCollectAll');
  718. $dayFindArr = ['aid' => $orders->activity_id, 'admin_id' => $orders->admin_id, 'createdate' => $today, 'business_line'=>$business];
  719. $allFindArr = ['aid' => $orders->activity_id, 'admin_id' => $orders->admin_id, 'business_line'=>$business];
  720. //管理员条件
  721. $managerDayFindArr = ['aid' => $orders->activity_id, 'admin_id' => 0, 'createdate' => $today, 'business_line'=>$business];
  722. $managerAllFindArr = ['aid' => $orders->activity_id, 'admin_id' => 0, 'business_line'=>$business];
  723. $dayRes = $activityCollect->where($dayFindArr)->find();
  724. $allRes = $activityCollectAll->where($allFindArr)->find();
  725. $manageDayRes = $activityCollect->where($managerDayFindArr)->find();
  726. $manageAllRes = $activityCollectAll->where($managerAllFindArr)->find();
  727. //按日统计
  728. if ($dayRes) { //更新
  729. //渠道商代理商
  730. $dayArrAc['money'] = ['exp', "`money`+{$orders['money']}"];
  731. $dayArrAc['recharge_count'] = ['exp', "`recharge_count`+1"];
  732. $dayArrAc['updatetime'] = time();
  733. $sqlRes = $activityCollect->update($dayArrAc, $dayFindArr);
  734. if(empty($sqlRes)){
  735. Log::info('统计sql执行失败--表:activityCollect--数据:'.json_encode($dayArrAc).'where条件:'.json_encode($dayFindArr));
  736. }
  737. } else { //插入
  738. $dayFindArr['money'] = $orders['money'];
  739. $dayFindArr['recharge_count'] = 1;
  740. $dayFindArr['createtime'] = time();
  741. $dayFindArr['updatetime'] = time();
  742. $sqlRes = $activityCollect->insert($dayFindArr);
  743. if(empty($sqlRes)){
  744. Log::info('统计sql执行失败--表:activityCollect--数据:'.json_encode($dayFindArr));
  745. }
  746. }
  747. //管理员按日统计
  748. if ($manageDayRes) { //更新
  749. //渠道商代理商
  750. $mdayArrAc['money'] = ['exp', "`money`+{$orders['money']}"];
  751. $mdayArrAc['recharge_count'] = ['exp', "`recharge_count`+1"];
  752. $mdayArrAc['updatetime'] = time();
  753. $sqlRes = $activityCollect->update($mdayArrAc, $managerDayFindArr);
  754. if(empty($sqlRes)){
  755. Log::info('统计sql执行失败--表:activityCollect--数据:'.json_encode($mdayArrAc).'where条件:'.json_encode($managerDayFindArr));
  756. }
  757. } else { //插入
  758. $managerDayFindArr['money'] = $orders['money'];
  759. $managerDayFindArr['recharge_count'] = 1;
  760. $managerDayFindArr['createtime'] = time();
  761. $managerDayFindArr['updatetime'] = time();
  762. $sqlRes = $activityCollect->insert($managerDayFindArr);
  763. if(empty($sqlRes)){
  764. Log::info('统计sql执行失败--表:activityCollect--数据:'.json_encode($managerDayFindArr));
  765. }
  766. }
  767. //汇总统计
  768. if ($allRes) { //更新
  769. $allArrAc['money'] = ['exp', "`money`+{$orders['money']}"];
  770. $allArrAc['recharge_count'] = ['exp', "`recharge_count`+1"];
  771. $allArrAc['updatetime'] = time();
  772. $sqlRes = $activityCollectAll->update($allArrAc, $allFindArr);
  773. if(empty($sqlRes)){
  774. Log::info('统计sql执行失败--表:activityCollect--数据:'.json_encode($allArrAc).'where条件:'.json_encode($allFindArr));
  775. }
  776. } else { //插入
  777. $allFindArr['money'] = $orders['money'];
  778. $allFindArr['recharge_count'] = 1;
  779. $allFindArr['createtime'] = time();
  780. $allFindArr['updatetime'] = time();
  781. $sqlRes = $activityCollectAll->insert($allFindArr);
  782. if(empty($sqlRes)){
  783. Log::info('统计sql执行失败--表:activityCollect--数据:'.json_encode($allFindArr));
  784. }
  785. }
  786. //管理员汇总统计
  787. if ($manageAllRes) { //更新
  788. $mallArrAc['money'] = ['exp', "`money`+{$orders['money']}"];
  789. $mallArrAc['recharge_count'] = ['exp', "`recharge_count`+1"];
  790. $mallArrAc['updatetime'] = time();
  791. $sqlRes = $activityCollectAll->update($mallArrAc, $managerAllFindArr);
  792. if(empty($sqlRes)){
  793. Log::info('统计sql执行失败--表:activityCollect--数据:'.json_encode($mallArrAc).'where条件:'.json_encode($managerAllFindArr));
  794. }
  795. } else { //插入
  796. $managerAllFindArr['money'] = $orders['money'];
  797. $managerAllFindArr['recharge_count'] = 1;
  798. $managerAllFindArr['createtime'] = time();
  799. $managerAllFindArr['updatetime'] = time();
  800. $sqlRes = $activityCollectAll->insert($managerAllFindArr);
  801. if(empty($sqlRes)){
  802. Log::info('统计sql执行失败--表:activityCollect--数据:'.json_encode($managerAllFindArr));
  803. }
  804. }
  805. }
  806. } catch (\Exception $exception) {
  807. Log::error('支付回调插入活动表出错'.json_encode(['errcode' => $exception->getCode(), 'errmsg' => $exception->getMessage()]));
  808. }
  809. try {
  810. /**
  811. * referral 推广表
  812. */
  813. if (!empty($orders['referral_id']) && $business == PayConstants::BUSINESS_WECHAT) { // 是推广链接产生的订单
  814. $oAna->user_from['referral_id'] = $orders['referral_id'];
  815. $redis = Redis::instance();
  816. if (empty($orders['resource_id'])) { // 非转移订单&非扣量订单
  817. model('referral')->update(['money' => ['exp', "`money`+{$orders['money']}"], 'orders_num' => ['exp', "`orders_num`+1"]],
  818. ['id' => $orders['referral_id']]);
  819. //当天充值金额
  820. $dayMTkey = "M-T:" . $orders['referral_id'] . ":" . date("d");
  821. if ($redis->exists($dayMTkey)) {
  822. $redis->incrBy($dayMTkey, intval($orders['money'] * 100));
  823. } else {
  824. $redis->set($dayMTkey,intval($orders['money'] * 100));
  825. $redis->expire($dayMTkey,86400);
  826. }
  827. //当天充值笔数
  828. $dayMTkey = "M-T-N:" . $orders['referral_id'] . ":" . date("d");
  829. if ($redis->exists($dayMTkey)) {
  830. $redis->incrBy($dayMTkey, 1);
  831. } else {
  832. $redis->set($dayMTkey,1);
  833. $redis->expire($dayMTkey,86400);
  834. }
  835. //更新每日数据
  836. ReferralService::instance()->updateDayData($orders['referral_id'], ['orders_num' => 1, 'recharge_money' => $orders['money']], $orders['createtime']);
  837. }
  838. }
  839. /**
  840. * referral 推广表
  841. */
  842. if (!empty($orders['referral_id_permanent']) && $orders['referral_id_permanent'] != $orders['referral_id'] && $business == PayConstants::BUSINESS_WECHAT) { // 是推广链接产生的订单
  843. $oAna->data['referral_id_permanent'] = $orders['referral_id_permanent'];
  844. $redis = Redis::instance();
  845. if (empty($orders['resource_id'])) { // 非转移订单&非扣量订单
  846. model('referral')->update(['money' => ['exp', "`money`+{$orders['money']}"], 'orders_num' => ['exp', "`orders_num`+1"]],
  847. ['id' => $orders['referral_id_permanent']]);
  848. //当天充值金额
  849. $dayMTkey = "M-T:" . $orders['referral_id_permanent'] . ":" . date("d");
  850. if ($redis->exists($dayMTkey)) {
  851. $redis->incrBy($dayMTkey, intval($orders['money'] * 100));
  852. } else {
  853. $redis->set($dayMTkey,intval($orders['money'] * 100));
  854. $redis->expire($dayMTkey,86400);
  855. }
  856. //当天充值笔数
  857. $dayMTkey = "M-T-N:" . $orders['referral_id_permanent'] . ":" . date("d");
  858. if ($redis->exists($dayMTkey)) {
  859. $redis->incrBy($dayMTkey, 1);
  860. } else {
  861. $redis->set($dayMTkey,1);
  862. $redis->expire($dayMTkey,86400);
  863. }
  864. //更新每日数据
  865. ReferralService::instance()->updateDayData($orders['referral_id_permanent'], ['orders_num' => 1, 'recharge_money' => $orders['money']], $orders['createtime']);
  866. }
  867. }
  868. } catch (\Exception $exception) {
  869. Log::error('支付回调更新推广链接表出错'.json_encode(['errcode' => $exception->getCode(), 'errmsg' => $exception->getMessage()]));
  870. }
  871. /**
  872. * recharge表
  873. */
  874. try {
  875. // 充值书币/VIP
  876. $rechargeModel = model('Recharge');
  877. $data = [
  878. 'user_id' => $orders['user_id'],
  879. 'type' => $orders['type'],
  880. 'kandian' => $orders['kandian'],
  881. 'remain_kandian' => $orders['kandian'],
  882. 'free_kandian' => 0,
  883. 'remain_free_kandian' => 0,
  884. 'day' => $orders['day'],
  885. 'book_id' => $orders['book_id'],
  886. 'dd' => $orders['deduct'],
  887. 'createtime' => $time,
  888. 'updatetime' => $time,
  889. 'business_line' => $business,
  890. 'orders_id' => $orders['id'],
  891. ];
  892. //查询订单是不是消耗活动得订单 wud
  893. $orderExtendType = model('OrdersExtend')->where(['order_id'=>$orders['id']])->find();
  894. if( !empty($orderExtendType) ){
  895. $data['extend_type'] = $orderExtendType['type'];
  896. }
  897. if($orders['type'] == '2'){
  898. //VIP充值
  899. $data['vip_starttime'] = $rechargeModel->getVipStartTime($orders['user_id']);
  900. if($orders['deduct'] == '0'){
  901. $data['channel_vip_starttime'] = $rechargeModel->getChannelVipStartTime($orders['user_id']);
  902. }
  903. }
  904. $sqlRes = $rechargeModel->setConnect($orders['user_id'])->insertGetId($data);
  905. if(empty($sqlRes)){
  906. Log::info('充值书币sql执行失败--表:recharge--数据:'.json_encode($data).'用户id:'.$orders['user_id']);
  907. }
  908. FinancialService::instance()->getKandian($orders['user_id']);
  909. } catch (\Exception $exception) {
  910. Log::error('支付回调插入表出错:'.json_encode(['errcode' => $exception->getCode(), 'errmsg' => $exception->getMessage()]));
  911. }
  912. // 赠送书币(VIP无赠送)
  913. try {
  914. if ($orders['type'] == 1 && !empty($orders['free_kandian'])) {
  915. $data = [
  916. 'user_id' => $orders['user_id'],
  917. 'type' => $orders['type'],
  918. 'kandian' => 0,
  919. 'remain_kandian' => 0,
  920. 'free_kandian' => $orders['free_kandian'],
  921. 'remain_free_kandian' => $orders['free_kandian'],
  922. 'day' => 0,
  923. 'book_id' => $orders['book_id'],
  924. 'dd' => $orders['deduct'],
  925. 'createtime' => $time,
  926. 'updatetime' => $time,
  927. 'business_line' => $business,
  928. 'orders_id' => $orders['id'],
  929. ];
  930. if (!empty($orders['activity_id'])) {
  931. $activityId = $orders['activity_id'];
  932. $activityInfo = ActivityService::instance()->getActivityInfo($activityId);
  933. $data['free_endtime'] = $time + $activityInfo['free_day'] * 86400;
  934. } else {
  935. $data['free_endtime'] = $time + Config::get('site.kandian_free_day') * 86400;
  936. }
  937. $sqlRes = $rechargeModel->setConnect($orders['user_id'])->insertGetId($data);
  938. if(empty($sqlRes)){
  939. Log::info('充值书币sql执行失败--表:recharge--数据:'.json_encode($data).'用户id:'.$orders['user_id']);
  940. }
  941. FinancialService::instance()->getFreeKandian($orders['user_id']);
  942. }
  943. } catch (\Exception $exception) {
  944. Log::error('支付回调赠送书币出错:'.json_encode(['errcode' => $exception->getCode(), 'errmsg' => $exception->getMessage()]));
  945. }
  946. try {
  947. // user表 金额
  948. $userModel = model('User');
  949. $userInfo = $userModel->getUserInfo($orders['user_id']);
  950. $adminId = $orders['admin_id'];
  951. $group = model('AuthGroupAccess')->where('uid', $adminId)->find();
  952. $groupId = $group->group_id;
  953. //分成比例
  954. $adminExtend = model('AdminExtend')->where('admin_id', $adminId)->find();
  955. $agentID = 0;
  956. if ($groupId == 3) { //渠道商
  957. $channel_id = $adminId;
  958. } else {
  959. if ($adminExtend->distribute == '1') {
  960. $agentID = $adminId;
  961. }
  962. $channel_id = $adminExtend->create_by;
  963. $adminChannelExtend = model('AdminExtend')->where('admin_id', $channel_id)->find();
  964. $channelBenefit = $adminChannelExtend->benefit;
  965. }
  966. if ($userInfo) {
  967. $redis = Redis::instance();
  968. $userData = [];
  969. $userUpdate = new UserUpdate();
  970. $userUpdate->setId($orders['user_id']);
  971. $userKey = 'UN:' . $orders['user_id'];
  972. if (!$userInfo['is_pay']) {
  973. $userData['is_pay'] = 1;
  974. $userUpdate->setIsPay(1);
  975. $oAna->data['first_pay'] = 1;
  976. if (empty($orders['deduct'])) { //如果不是KL
  977. //渠道商OR配号代理商 统计付费用户
  978. $current_channel_id = empty($agentID) ? $channel_id : $agentID;
  979. //发送打点数据
  980. $dotData = new DotObject();
  981. $dotData->channel_id = $current_channel_id;
  982. $dotData->event_time = Request::instance()->server('REQUEST_TIME');
  983. $dotData->action_type = MqConstants::ROUTING_KEY_COLLECT_CHANNEL_PAY;
  984. $dotData->type = MqConstants::MSG_TYPE_PAY;
  985. MqService::instance()->sendMessage($dotData);
  986. }
  987. }
  988. if (empty($orders['deduct'])) { //如果不是KL
  989. //渠道每日新增用户充值总数
  990. $current_channel_id = empty($agentID) ? $channel_id : $agentID;
  991. if ($userInfo['createtime'] >= strtotime(date("Y-m-d"))) {
  992. $newsUserMoney = 0;
  993. $newsUserMoney += $orders['money'];
  994. //发送打点数据
  995. $dotData = new DotObject();
  996. $dotData->channel_id = $current_channel_id;
  997. $dotData->event_time = Request::instance()->server('REQUEST_TIME');
  998. $dotData->action_type = MqConstants::ROUTING_KEY_COLLECT_CHANNEL_PAY;
  999. $dotData->type = MqConstants::MSG_TYPE_NEW_USER_RECHARGE;
  1000. $dotData->user_id = $orders['user_id'];
  1001. $dotData->money = (float)$newsUserMoney;
  1002. MqService::instance()->sendMessage($dotData);
  1003. //写入充值的用户
  1004. $date_time = date('Ymd');
  1005. $key1 = "CNR_D:{$date_time}:{$channel_id}";
  1006. $redis->pfAdd($key1, $orders['user_id']);
  1007. $key2 = "CNR_D:{$date_time}:0";
  1008. $redis->pfAdd($key2, $orders['user_id']);
  1009. }
  1010. }
  1011. if ($orders['day']) {
  1012. if ($userInfo['vip_endtime'] > $time) {
  1013. $vipTime = $orders['day'] * 86400;
  1014. $userData['vip_endtime'] = $userInfo['vip_endtime'] + $vipTime;
  1015. } else {
  1016. $vipTime = intval($time) + intval($orders['day'] * 86400);
  1017. $userData['vip_endtime'] = $vipTime;
  1018. //VIP 间隔续费时,维护vip_starttime
  1019. UserVipExtendService::instance()->saveVipStartTime($orders['user_id'], intval($time));
  1020. }
  1021. $userUpdate->setAddvipday($orders['day'] * 86400);
  1022. }
  1023. if (ApiService::instance()->checkApiOn()) {
  1024. \app\source\service\UserService::instance()->updateUser($userUpdate);
  1025. } else {
  1026. $userModel->setConnect($orders['user_id'])->update($userData, ['id' => $orders['user_id']]);
  1027. //修改redis
  1028. $redis->del($userKey);
  1029. }
  1030. }
  1031. } catch (\Exception $exception) {
  1032. Log::error('支付回调用户操作失败:'.json_encode(['errcode' => $exception->getCode(), 'errmsg' => $exception->getMessage()]));
  1033. }
  1034. //内推单页直接购买书籍
  1035. try {
  1036. SinglePushService::instance()->completeOrders($orders);
  1037. }catch (\Exception $e){
  1038. log::error('内推页直接购买书籍失败'.json_encode($orders));
  1039. }
  1040. //消耗活动标记
  1041. $cSignKey = CampaignConstants::getUserClickCSignKey($userInfo['id']);
  1042. $uOrderKey = CampaignConstants::getUserPayOrderKey($userInfo['id']);
  1043. if (Redis::instance()->get($cSignKey)) {
  1044. if (Redis::instance()->get($uOrderKey) === false) {
  1045. Redis::instance()->set($uOrderKey, $orders['out_trade_no'], 86400);
  1046. }
  1047. }
  1048. //添加渠道订单金额统计
  1049. if ($orders['deduct']) {
  1050. AdminKlService::instance($business)->addChannelOrderMoneyCache($orders['resource_id'], $orders['money'], $orders['out_trade_no'], true);
  1051. AdminKlService::instance($business)->addChannelOrderMoneyCache($orders['resource_id'], $orders['money'], $orders['out_trade_no']);
  1052. } else {
  1053. AdminKlService::instance($business)->addChannelOrderMoneyCache($orders['admin_id'], $orders['money'], $orders['out_trade_no']);
  1054. }
  1055. // 用户画像打点
  1056. $this->_saveUserDot($orders);
  1057. if (intval($orders['deduct']) < 1 || $orders['createtime'] > 1577203200) { //如果不是KL
  1058. /*
  1059. * orders_collect表
  1060. */
  1061. //判断 充值vip(true) 还是 充值书币(false)
  1062. $isVip = !empty($orders['day']);
  1063. $isActivity = !empty($orders['activity_id']);
  1064. //判断 引导充值(true) 还是 普通充值(false)
  1065. $yd = !empty($orders['book_id']);
  1066. $ordersCollect = model('OrdersCollect');
  1067. $splitMoney = $this->splitMoney($orders);
  1068. try {
  1069. $adminId = $orders['admin_id'];
  1070. $group = model('AuthGroupAccess')->where('uid', $adminId)->find();
  1071. $groupId = $group->group_id;
  1072. if ($groupId == 3) { //渠道商
  1073. /**
  1074. * 渠道商提现表维护
  1075. */
  1076. $adminMoneyModel = model('AdminMoney');
  1077. $adminMoneyResult = $adminMoneyModel->where(['admin_id' => $adminId])->find();
  1078. if ($adminMoneyResult) { //更新
  1079. $moneyData = [];
  1080. $moneyData['count_money'] = ['exp', "`count_money`+{$orders['money']}"]; //总收入金额
  1081. $moneyData['split_money'] = ['exp', "`split_money`+{$splitMoney}"]; //总分账金额
  1082. $moneyData['orders_count'] = ['exp', "`orders_count`+1"];
  1083. $moneyData['updatetime'] = $time;
  1084. $sqlRes = $adminMoneyModel->update($moneyData, ['id' => $adminMoneyResult->id]);
  1085. if (empty($sqlRes)) {
  1086. Log::info('提现sql执行失败--表:AdminMoney--数据:' . json_encode($moneyData) . 'where条件:' . json_encode(['id' => $adminMoneyResult->id]));
  1087. }
  1088. } else { //插入
  1089. $moneyData = [];
  1090. $moneyData['admin_id'] = $adminId;
  1091. $moneyData['count_money'] = $orders['money']; //总收入金额
  1092. $moneyData['split_money'] = $splitMoney; //总分账金额
  1093. $moneyData['orders_count'] = 1;
  1094. $moneyData['createtime'] = $time;
  1095. $moneyData['updatetime'] = $time;
  1096. $sqlRes = $adminMoneyModel->insert($moneyData);
  1097. if (empty($sqlRes)) {
  1098. Log::info('提现sql执行失败--表:AdminMoney--数据:' . json_encode($moneyData));
  1099. }
  1100. }
  1101. /**
  1102. * 渠道商 当天 自身
  1103. */
  1104. $channelDay = [
  1105. 'admin_id' => $adminId,
  1106. 'type' => 1,
  1107. 'flag' => 1,
  1108. 'createdate' => $today,
  1109. 'business_line' => $business,
  1110. ];
  1111. $channelResDay = $ordersCollect->where($channelDay)->find();
  1112. if ($channelResDay) {
  1113. $user_count = OrderService::instance()->setOrderUserCountCache($orders['user_id'], $channelDay,
  1114. $isVip)->data;
  1115. $dayArr = [];
  1116. $dayArr['recharge_money'] = ['exp', "`recharge_money`+{$orders['money']}"];
  1117. $dayArr['recharge_money_benefit'] = [
  1118. 'exp',
  1119. "`recharge_money_benefit`+{$this_money_benefit}",
  1120. ];
  1121. if ($splitMoney) {
  1122. $dayArr['split_money'] = [
  1123. 'exp',
  1124. "`split_money`+{$splitMoney}",
  1125. ];
  1126. }
  1127. if ($isVip) {
  1128. $dayArr['vip_recharge_user_suc_count'] = $user_count['user'];
  1129. $dayArr['recharge_user_suc_count'] = $user_count['total'];
  1130. $dayArr['vip_recharge_orders'] = ['exp', "`vip_recharge_orders`+1"];
  1131. $dayArr['vip_recharge_money'] = [
  1132. 'exp',
  1133. "`vip_recharge_money`+{$orders['money']}",
  1134. ];
  1135. $dayArr['vip_recharge_money_benefit'] = [
  1136. 'exp',
  1137. "`vip_recharge_money_benefit`+{$this_money_benefit}",
  1138. ];
  1139. if ($yd) {
  1140. $dayArr['vip_recharge_guide_orders'] = [
  1141. 'exp',
  1142. "`vip_recharge_guide_orders`+1",
  1143. ];;
  1144. $dayArr['vip_recharge_guide_money'] = [
  1145. 'exp',
  1146. "`vip_recharge_guide_money`+{$orders['money']}",
  1147. ];
  1148. $dayArr['vip_recharge_guide_money_benefit'] = [
  1149. 'exp',
  1150. "`vip_recharge_guide_money_benefit`+{$this_money_benefit}",
  1151. ];
  1152. }
  1153. } else {
  1154. $dayArr['normal_recharge_user_suc_count'] = $user_count['user'];
  1155. $dayArr['recharge_user_suc_count'] = $user_count['total'];
  1156. $dayArr['normal_recharge_orders'] = ['exp', "`normal_recharge_orders`+1"];
  1157. $dayArr['normal_recharge_money'] = [
  1158. 'exp',
  1159. "`normal_recharge_money`+{$orders['money']}",
  1160. ];
  1161. $dayArr['normal_recharge_money_benefit'] = [
  1162. 'exp',
  1163. "`normal_recharge_money_benefit`+{$this_money_benefit}",
  1164. ];
  1165. if ($yd) {
  1166. $dayArr['normal_recharge_guide_orders'] = [
  1167. 'exp',
  1168. "`normal_recharge_guide_orders`+1",
  1169. ];
  1170. $dayArr['noraml_recharge_guide_money'] = [
  1171. 'exp',
  1172. "`noraml_recharge_guide_money`+{$orders['money']}",
  1173. ];
  1174. $dayArr['noraml_recharge_guide_money_benefit'] = [
  1175. 'exp',
  1176. "`noraml_recharge_guide_money_benefit`+{$this_money_benefit}",
  1177. ];
  1178. }
  1179. if (!$isActivity) {
  1180. $dayArr['kandian_recharge_orders'] = ['exp', "`kandian_recharge_orders`+1"];
  1181. }
  1182. }
  1183. $sqlRes = $ordersCollect->update($dayArr, ['id' => $channelResDay->id]);
  1184. if (empty($sqlRes)) {
  1185. Log::info('统计sql执行失败--表:ordersCollect--数据:' . json_encode($dayArr) . 'where条件:' . json_encode(['id' => $channelResDay->id]));
  1186. }
  1187. }
  1188. /**
  1189. * 渠道商 当天 全部
  1190. */
  1191. $channelAllDay = [
  1192. 'admin_id' => $adminId,
  1193. 'type' => 1,
  1194. 'flag' => 3,
  1195. 'createdate' => $today,
  1196. 'business_line' => $business,
  1197. ];
  1198. $channelAllResDay = $ordersCollect->where($channelAllDay)->find();
  1199. if ($channelAllResDay) {
  1200. $user_count = OrderService::instance()->setOrderUserCountCache($orders['user_id'],
  1201. $channelAllDay, $isVip)->data;
  1202. $dayAllArr = [];
  1203. $dayAllArr['recharge_money'] = ['exp', "`recharge_money`+{$orders['money']}"];
  1204. $dayAllArr['recharge_money_benefit'] = [
  1205. 'exp',
  1206. "`recharge_money_benefit`+{$this_money_benefit}",
  1207. ];
  1208. if ($splitMoney) {
  1209. $dayAllArr['split_money'] = [
  1210. 'exp',
  1211. "`split_money`+{$splitMoney}",
  1212. ];
  1213. }
  1214. if ($isVip) {
  1215. $dayAllArr['vip_recharge_user_suc_count'] = $user_count['user'];
  1216. $dayAllArr['recharge_user_suc_count'] = $user_count['total'];
  1217. $dayAllArr['vip_recharge_orders'] = ['exp', "`vip_recharge_orders`+1"];
  1218. $dayAllArr['vip_recharge_money'] = [
  1219. 'exp',
  1220. "`vip_recharge_money`+{$orders['money']}",
  1221. ];
  1222. $dayAllArr['vip_recharge_money_benefit'] = [
  1223. 'exp',
  1224. "`vip_recharge_money_benefit`+{$this_money_benefit}",
  1225. ];
  1226. if ($yd) {
  1227. $dayAllArr['vip_recharge_guide_orders'] = [
  1228. 'exp',
  1229. "`vip_recharge_guide_orders`+1",
  1230. ];
  1231. $dayAllArr['vip_recharge_guide_money'] = [
  1232. 'exp',
  1233. "`vip_recharge_guide_money`+{$orders['money']}",
  1234. ];
  1235. $dayAllArr['vip_recharge_guide_money_benefit'] = [
  1236. 'exp',
  1237. "`vip_recharge_guide_money_benefit`+{$this_money_benefit}",
  1238. ];
  1239. }
  1240. } else {
  1241. $dayAllArr['normal_recharge_user_suc_count'] = $user_count['user'];
  1242. $dayAllArr['recharge_user_suc_count'] = $user_count['total'];
  1243. $dayAllArr['normal_recharge_orders'] = ['exp', "`normal_recharge_orders`+1"];
  1244. $dayAllArr['normal_recharge_money'] = [
  1245. 'exp',
  1246. "`normal_recharge_money`+{$orders['money']}",
  1247. ];
  1248. $dayAllArr['normal_recharge_money_benefit'] = [
  1249. 'exp',
  1250. "`normal_recharge_money_benefit`+{$this_money_benefit}",
  1251. ];
  1252. if ($yd) {
  1253. $dayAllArr['normal_recharge_guide_orders'] = [
  1254. 'exp',
  1255. "`normal_recharge_guide_orders`+1",
  1256. ];
  1257. $dayAllArr['noraml_recharge_guide_money'] = [
  1258. 'exp',
  1259. "`noraml_recharge_guide_money`+{$orders['money']}",
  1260. ];
  1261. $dayAllArr['noraml_recharge_guide_money_benefit'] = [
  1262. 'exp',
  1263. "`noraml_recharge_guide_money_benefit`+{$this_money_benefit}",
  1264. ];
  1265. }
  1266. if (!$isActivity) {
  1267. $dayAllArr['kandian_recharge_orders'] = ['exp', "`kandian_recharge_orders`+1"];
  1268. }
  1269. }
  1270. $sqlRes = $ordersCollect->update($dayAllArr, ['id' => $channelAllResDay->id]);
  1271. if (empty($sqlRes)) {
  1272. Log::info('统计sql执行失败--表:ordersCollect--数据:' . json_encode($dayAllArr) . 'where条件:' . json_encode(['id' => $channelAllResDay->id]));
  1273. }
  1274. }
  1275. /**
  1276. * 管理员 当天 属下
  1277. */
  1278. $managerDay = [
  1279. 'admin_id' => 0,
  1280. 'type' => 1,
  1281. 'flag' => 2,
  1282. 'createdate' => $today,
  1283. 'business_line' => $business,
  1284. ];
  1285. $manageResDay = $ordersCollect->where($managerDay)->find();
  1286. if ($manageResDay) {
  1287. $user_count = OrderService::instance()->setOrderUserCountCache($orders['user_id'], $managerDay,
  1288. $isVip)->data;
  1289. $mDayArr = [];
  1290. $mDayArr['recharge_money'] = ['exp', "`recharge_money`+{$orders['money']}"];
  1291. $mDayArr['recharge_money_benefit'] = [
  1292. 'exp',
  1293. "`recharge_money_benefit`+{$this_money_benefit}",
  1294. ];
  1295. if ($isVip) {
  1296. $mDayArr['vip_recharge_user_suc_count'] = $user_count['user'];
  1297. $mDayArr['recharge_user_suc_count'] = $user_count['total'];
  1298. $mDayArr['vip_recharge_orders'] = ['exp', "`vip_recharge_orders`+1"];
  1299. $mDayArr['vip_recharge_money'] = ['exp', "`vip_recharge_money`+{$orders['money']}"];
  1300. $mDayArr['vip_recharge_money_benefit'] = [
  1301. 'exp',
  1302. "`vip_recharge_money_benefit`+{$this_money_benefit}",
  1303. ];
  1304. if ($yd) {
  1305. $mDayArr['vip_recharge_guide_orders'] = ['exp', "`vip_recharge_guide_orders`+1"];
  1306. $mDayArr['vip_recharge_guide_money'] = [
  1307. 'exp',
  1308. "`vip_recharge_guide_money`+{$orders['money']}",
  1309. ];
  1310. $mDayArr['vip_recharge_guide_money_benefit'] = [
  1311. 'exp',
  1312. "`vip_recharge_guide_money_benefit`+{$this_money_benefit}",
  1313. ];
  1314. }
  1315. } else {
  1316. $mDayArr['normal_recharge_user_suc_count'] = $user_count['user'];
  1317. $mDayArr['recharge_user_suc_count'] = $user_count['total'];
  1318. $mDayArr['normal_recharge_orders'] = ['exp', "`normal_recharge_orders`+1"];
  1319. $mDayArr['normal_recharge_money'] = [
  1320. 'exp',
  1321. "`normal_recharge_money`+{$orders['money']}",
  1322. ];
  1323. $mDayArr['normal_recharge_money_benefit'] = [
  1324. 'exp',
  1325. "`normal_recharge_money_benefit`+{$this_money_benefit}",
  1326. ];
  1327. if ($yd) {
  1328. $mDayArr['normal_recharge_guide_orders'] = [
  1329. 'exp',
  1330. "`normal_recharge_guide_orders`+1",
  1331. ];
  1332. $mDayArr['noraml_recharge_guide_money'] = [
  1333. 'exp',
  1334. "`noraml_recharge_guide_money`+{$orders['money']}",
  1335. ];
  1336. $mDayArr['noraml_recharge_guide_money_benefit'] = [
  1337. 'exp',
  1338. "`noraml_recharge_guide_money_benefit`+{$this_money_benefit}",
  1339. ];
  1340. }
  1341. if (!$isActivity) {
  1342. $mDayArr['kandian_recharge_orders'] = ['exp', "`kandian_recharge_orders`+1"];
  1343. }
  1344. }
  1345. $sqlRes = $ordersCollect->update($mDayArr, ['id' => $manageResDay->id]);
  1346. if (empty($sqlRes)) {
  1347. Log::info('统计sql执行失败--表:ordersCollect--数据:' . json_encode($mDayArr) . 'where条件:' . json_encode(['id' => $manageResDay->id]));
  1348. }
  1349. }
  1350. }
  1351. } catch (\Exception $exception) {
  1352. Log::error('支付回调渠道商统计出错:' . json_encode([
  1353. 'errcode' => $exception->getCode(),
  1354. 'errmsg' => $exception->getMessage()
  1355. ]));
  1356. }
  1357. if ($groupId == 4 && isset($channelBenefit)) { //代理商
  1358. try {
  1359. $cBenefitMoney = round($channelBenefit * $orders['money'], 2); //渠道商设置的分成收益
  1360. $adminMoneyModel = model('AdminMoney');
  1361. /**
  1362. * 代理商 提现表 维护
  1363. */
  1364. $adminMoneyResult = $adminMoneyModel->where(['admin_id' => $adminId])->find();
  1365. $moneyData = [];
  1366. if ($adminMoneyResult) { //更新
  1367. $moneyData['count_money'] = ['exp', "`count_money`+{$orders['money']}"]; //总收入金额
  1368. $moneyData['orders_count'] = ['exp', "`orders_count`+1"]; //总收入金额
  1369. $sqlRes = $adminMoneyModel->update($moneyData, ['id' => $adminMoneyResult->id]);
  1370. if (empty($sqlRes)) {
  1371. Log::info('统计sql执行失败--表:AdminMoney--数据:' . json_encode($moneyData) . 'where条件:' . json_encode(['id' => $adminMoneyResult->id]));
  1372. }
  1373. } else { //插入
  1374. $moneyData['admin_id'] = $adminId;
  1375. $moneyData['count_money'] = $orders['money']; //总收入金额
  1376. $moneyData['orders_count'] = 1;
  1377. $sqlRes = $adminMoneyModel->insert($moneyData);
  1378. if (empty($sqlRes)) {
  1379. Log::info('统计sql执行失败--表:AdminMoney--数据:' . json_encode($moneyData));
  1380. }
  1381. }
  1382. /**
  1383. * 渠道商 提现表 维护 $channel_id
  1384. */
  1385. $channelMcount = $adminMoneyModel->where(['admin_id' => $channel_id])->find();
  1386. $chanData = [];
  1387. if ($channelMcount) { //更新
  1388. $chanData['count_money'] = ['exp', "`count_money`+{$orders['money']}"]; //总收入金额
  1389. $chanData['split_money'] = ['exp', "`split_money`+{$splitMoney}"]; //总分账金额
  1390. $chanData['orders_count'] = ['exp', "`orders_count`+1"]; //总收入金额
  1391. $sqlRes = $adminMoneyModel->update($chanData, ['id' => $channelMcount->id]);
  1392. if (empty($sqlRes)) {
  1393. Log::info('统计sql执行失败--表:AdminMoney--数据:' . json_encode($chanData) . 'where条件:' . json_encode(['id' => $channelMcount->id]));
  1394. }
  1395. } else { //插入
  1396. $chanData['admin_id'] = $channel_id;
  1397. $chanData['count_money'] = $orders['money']; //总收入金额
  1398. $chanData['split_money'] = $splitMoney; //总分账金额
  1399. $chanData['orders_count'] = 1;
  1400. $sqlRes = $adminMoneyModel->insert($chanData);
  1401. if (empty($sqlRes)) {
  1402. Log::info('统计sql执行失败--表:AdminMoney--数据:' . json_encode($chanData));
  1403. }
  1404. }
  1405. /**
  1406. * 代理商 当天 自身
  1407. */
  1408. $agentDay = [
  1409. 'admin_id' => $adminId,
  1410. 'type' => 1,
  1411. 'flag' => 1,
  1412. 'createdate' => $today,
  1413. 'business_line' => $business,
  1414. ];
  1415. $agentResDay = $ordersCollect->where($agentDay)->find();
  1416. if ($agentResDay) {
  1417. $user_count = OrderService::instance()->setOrderUserCountCache($orders['user_id'], $agentDay,
  1418. $isVip)->data;
  1419. $adayArr = [];
  1420. $adayArr['recharge_money'] = ['exp', "`recharge_money`+{$orders['money']}"];
  1421. $adayArr['recharge_money_benefit'] = [
  1422. 'exp',
  1423. "`recharge_money_benefit`+{$this_money_benefit}",
  1424. ];
  1425. if ($isVip) {
  1426. $adayArr['vip_recharge_user_suc_count'] = $user_count['user'];
  1427. $adayArr['recharge_user_suc_count'] = $user_count['total'];
  1428. $adayArr['vip_recharge_orders'] = ['exp', "`vip_recharge_orders`+1"];
  1429. $adayArr['vip_recharge_money'] = ['exp', "`vip_recharge_money`+{$orders['money']}"];
  1430. $adayArr['vip_recharge_money_benefit'] = [
  1431. 'exp',
  1432. "`vip_recharge_money_benefit`+{$this_money_benefit}",
  1433. ];
  1434. if ($yd) {
  1435. $adayArr['vip_recharge_guide_orders'] = ['exp', "`vip_recharge_guide_orders`+1"];
  1436. $adayArr['vip_recharge_guide_money'] = [
  1437. 'exp',
  1438. "`vip_recharge_guide_money`+{$orders['money']}",
  1439. ];
  1440. $adayArr['vip_recharge_guide_money_benefit'] = [
  1441. 'exp',
  1442. "`vip_recharge_guide_money_benefit`+{$this_money_benefit}",
  1443. ];
  1444. }
  1445. } else {
  1446. $adayArr['normal_recharge_user_suc_count'] = $user_count['user'];
  1447. $adayArr['recharge_user_suc_count'] = $user_count['total'];
  1448. $adayArr['normal_recharge_orders'] = ['exp', "`normal_recharge_orders`+1"];
  1449. $adayArr['normal_recharge_money'] = [
  1450. 'exp',
  1451. "`normal_recharge_money`+{$orders['money']}",
  1452. ];
  1453. $adayArr['normal_recharge_money_benefit'] = [
  1454. 'exp',
  1455. "`normal_recharge_money_benefit`+{$this_money_benefit}",
  1456. ];
  1457. if ($yd) {
  1458. $adayArr['normal_recharge_guide_orders'] = [
  1459. 'exp',
  1460. "`normal_recharge_guide_orders`+1",
  1461. ];
  1462. $adayArr['noraml_recharge_guide_money'] = [
  1463. 'exp',
  1464. "`noraml_recharge_guide_money`+{$orders['money']}",
  1465. ];
  1466. $adayArr['noraml_recharge_guide_money_benefit'] = [
  1467. 'exp',
  1468. "`noraml_recharge_guide_money_benefit`+{$this_money_benefit}",
  1469. ];
  1470. }
  1471. if (!$isActivity) {
  1472. $adayArr['kandian_recharge_orders'] = ['exp', "`kandian_recharge_orders`+1"];
  1473. }
  1474. }
  1475. $sqlRes = $ordersCollect->update($adayArr, ['id' => $agentResDay->id]);
  1476. if (empty($sqlRes)) {
  1477. Log::info('统计sql执行失败--表:ordersCollect--数据:' . json_encode($adayArr) . 'where条件:' . json_encode(['id' => $agentResDay->id]));
  1478. }
  1479. }
  1480. /**
  1481. * 渠道商 当天 属下
  1482. */
  1483. $agentParentDay = [
  1484. 'admin_id' => $channel_id,
  1485. 'type' => 1,
  1486. 'flag' => 2,
  1487. 'createdate' => $today,
  1488. 'business_line' => $business,
  1489. ];
  1490. $agentParentResDay = $ordersCollect->where($agentParentDay)->find();
  1491. if ($agentParentResDay) {
  1492. $user_count = OrderService::instance()->setOrderUserCountCache($orders['user_id'],
  1493. $agentParentDay, $isVip)->data;
  1494. $apDayArr = [];
  1495. $apDayArr['recharge_money'] = ['exp', "`recharge_money`+{$orders['money']}"];
  1496. $apDayArr['recharge_money_benefit'] = ['exp', "`recharge_money_benefit`+{$this_money_benefit}"];
  1497. if ($isVip) {
  1498. $apDayArr['vip_recharge_user_suc_count'] = $user_count['user'];
  1499. $apDayArr['recharge_user_suc_count'] = $user_count['total'];
  1500. $apDayArr['vip_recharge_orders'] = ['exp', "`vip_recharge_orders`+1"];
  1501. $apDayArr['vip_recharge_money'] = ['exp', "`vip_recharge_money`+{$orders['money']}"];
  1502. $apDayArr['vip_recharge_money_benefit'] = [
  1503. 'exp',
  1504. "`vip_recharge_money_benefit`+{$this_money_benefit}",
  1505. ];
  1506. if ($yd) {
  1507. $apDayArr['vip_recharge_guide_orders'] = ['exp', "`vip_recharge_guide_orders`+1"];
  1508. $apDayArr['vip_recharge_guide_money'] = [
  1509. 'exp',
  1510. "`vip_recharge_guide_money`+{$orders['money']}",
  1511. ];
  1512. $apDayArr['vip_recharge_guide_money_benefit'] = [
  1513. 'exp',
  1514. "`vip_recharge_guide_money_benefit`+{$this_money_benefit}",
  1515. ];
  1516. }
  1517. } else {
  1518. $apDayArr['normal_recharge_user_suc_count'] = $user_count['user'];
  1519. $apDayArr['recharge_user_suc_count'] = $user_count['total'];
  1520. $apDayArr['normal_recharge_orders'] = ['exp', "`normal_recharge_orders`+1"];
  1521. $apDayArr['normal_recharge_money'] = [
  1522. 'exp',
  1523. "`normal_recharge_money`+{$orders['money']}",
  1524. ];
  1525. $apDayArr['normal_recharge_money_benefit'] = [
  1526. 'exp',
  1527. "`normal_recharge_money_benefit`+{$this_money_benefit}",
  1528. ];
  1529. if ($yd) {
  1530. $apDayArr['normal_recharge_guide_orders'] = [
  1531. 'exp',
  1532. "`normal_recharge_guide_orders`+1",
  1533. ];
  1534. $apDayArr['noraml_recharge_guide_money'] = [
  1535. 'exp',
  1536. "`noraml_recharge_guide_money`+{$orders['money']}",
  1537. ];
  1538. $apDayArr['noraml_recharge_guide_money_benefit'] = [
  1539. 'exp',
  1540. "`noraml_recharge_guide_money_benefit`+{$this_money_benefit}",
  1541. ];
  1542. }
  1543. if (!$isActivity) {
  1544. $apDayArr['kandian_recharge_orders'] = ['exp', "`kandian_recharge_orders`+1"];
  1545. }
  1546. }
  1547. $sqlRes = $ordersCollect->update($apDayArr, ['id' => $agentParentResDay->id]);
  1548. if (empty($sqlRes)) {
  1549. Log::info('统计sql执行失败--表:ordersCollect--数据:' . json_encode($apDayArr) . 'where条件:' . json_encode(['id' => $agentParentResDay->id]));
  1550. }
  1551. }
  1552. /**
  1553. * 渠道商 当天 全部
  1554. */
  1555. $agentParentAllDay = [
  1556. 'admin_id' => $channel_id,
  1557. 'type' => 1,
  1558. 'flag' => 3,
  1559. 'createdate' => $today,
  1560. 'business_line' => $business,
  1561. ];
  1562. $agentAllParentResDay = $ordersCollect->where($agentParentAllDay)->find();
  1563. if ($agentAllParentResDay) {
  1564. $user_count = OrderService::instance()->setOrderUserCountCache($orders['user_id'],
  1565. $agentParentAllDay, $isVip)->data;
  1566. $aChannelAllDay = [];
  1567. $aChannelAllDay['recharge_money'] = ['exp', "`recharge_money`+{$orders['money']}"];
  1568. $aChannelAllDay['recharge_money_benefit'] = [
  1569. 'exp',
  1570. "`recharge_money_benefit`+{$cBenefitMoney}",
  1571. ];
  1572. if ($splitMoney) {
  1573. $aChannelAllDay['split_money'] = [
  1574. 'exp',
  1575. "`split_money`+{$splitMoney}",
  1576. ];
  1577. }
  1578. if ($isVip) {
  1579. $aChannelAllDay['vip_recharge_user_suc_count'] = $user_count['user'];
  1580. $aChannelAllDay['recharge_user_suc_count'] = $user_count['total'];
  1581. $aChannelAllDay['vip_recharge_orders'] = ['exp', "`vip_recharge_orders`+1"];
  1582. $aChannelAllDay['vip_recharge_money'] = [
  1583. 'exp',
  1584. "`vip_recharge_money`+{$orders['money']}",
  1585. ];
  1586. $aChannelAllDay['vip_recharge_money_benefit'] = [
  1587. 'exp',
  1588. "`vip_recharge_money_benefit`+{$cBenefitMoney}",
  1589. ];
  1590. if ($yd) {
  1591. $aChannelAllDay['vip_recharge_guide_orders'] = [
  1592. 'exp',
  1593. "`vip_recharge_guide_orders`+1",
  1594. ];
  1595. $aChannelAllDay['vip_recharge_guide_money'] = [
  1596. 'exp',
  1597. "`vip_recharge_guide_money`+{$orders['money']}",
  1598. ];
  1599. $aChannelAllDay['vip_recharge_guide_money_benefit'] = [
  1600. 'exp',
  1601. "`vip_recharge_guide_money_benefit`+{$cBenefitMoney}",
  1602. ];
  1603. }
  1604. } else {
  1605. $aChannelAllDay['normal_recharge_user_suc_count'] = $user_count['user'];
  1606. $aChannelAllDay['recharge_user_suc_count'] = $user_count['total'];
  1607. $aChannelAllDay['normal_recharge_orders'] = ['exp', "`normal_recharge_orders`+1"];
  1608. $aChannelAllDay['normal_recharge_money'] = [
  1609. 'exp',
  1610. "`normal_recharge_money`+{$orders['money']}",
  1611. ];
  1612. $aChannelAllDay['normal_recharge_money_benefit'] = [
  1613. 'exp',
  1614. "`normal_recharge_money_benefit`+{$cBenefitMoney}",
  1615. ];
  1616. if ($yd) {
  1617. $aChannelAllDay['normal_recharge_guide_orders'] = [
  1618. 'exp',
  1619. "`normal_recharge_guide_orders`+1",
  1620. ];
  1621. $aChannelAllDay['noraml_recharge_guide_money'] = [
  1622. 'exp',
  1623. "`noraml_recharge_guide_money`+{$orders['money']}",
  1624. ];
  1625. $aChannelAllDay['noraml_recharge_guide_money_benefit'] = [
  1626. 'exp',
  1627. "`noraml_recharge_guide_money_benefit`+{$cBenefitMoney}",
  1628. ];
  1629. }
  1630. if (!$isActivity) {
  1631. $aChannelAllDay['kandian_recharge_orders'] = ['exp', "`kandian_recharge_orders`+1"];
  1632. }
  1633. }
  1634. $sqlRes = $ordersCollect->update($aChannelAllDay, ['id' => $agentAllParentResDay->id]);
  1635. if (empty($sqlRes)) {
  1636. Log::info('统计sql执行失败--表:ordersCollect--数据:' . json_encode($aChannelAllDay) . 'where条件:' . json_encode(['id' => $agentAllParentResDay->id]));
  1637. }
  1638. }
  1639. /**
  1640. * 管理员 当天 属下
  1641. */
  1642. $managerDay = [
  1643. 'admin_id' => 0,
  1644. 'type' => 1,
  1645. 'flag' => 2,
  1646. 'createdate' => $today,
  1647. 'business_line' => $business,
  1648. ];
  1649. $manageResDay = $ordersCollect->where($managerDay)->find();
  1650. if ($manageResDay) {
  1651. $user_count = OrderService::instance()->setOrderUserCountCache($orders['user_id'], $managerDay,
  1652. $isVip)->data;
  1653. $aManageDay = [];
  1654. $aManageDay['recharge_money'] = ['exp', "`recharge_money`+{$orders['money']}"];
  1655. $aManageDay['recharge_money_benefit'] = ['exp', "`recharge_money_benefit`+{$cBenefitMoney}"];
  1656. if ($isVip) {
  1657. $aManageDay['vip_recharge_user_suc_count'] = $user_count['user'];
  1658. $aManageDay['recharge_user_suc_count'] = $user_count['total'];
  1659. $aManageDay['vip_recharge_orders'] = ['exp', "`vip_recharge_orders`+1"];
  1660. $aManageDay['vip_recharge_money'] = ['exp', "`vip_recharge_money`+{$orders['money']}"];
  1661. $aManageDay['vip_recharge_money_benefit'] = [
  1662. 'exp',
  1663. "`vip_recharge_money_benefit`+{$cBenefitMoney}",
  1664. ];
  1665. if ($yd) {
  1666. $aManageDay['vip_recharge_guide_orders'] = ['exp', "`vip_recharge_guide_orders`+1"];
  1667. $aManageDay['vip_recharge_guide_money'] = [
  1668. 'exp',
  1669. "`vip_recharge_guide_money`+{$orders['money']}",
  1670. ];
  1671. $aManageDay['vip_recharge_guide_money_benefit'] = [
  1672. 'exp',
  1673. "`vip_recharge_guide_money_benefit`+{$cBenefitMoney}",
  1674. ];
  1675. }
  1676. } else {
  1677. $aManageDay['normal_recharge_user_suc_count'] = $user_count['user'];
  1678. $aManageDay['recharge_user_suc_count'] = $user_count['total'];
  1679. $aManageDay['normal_recharge_orders'] = ['exp', "`normal_recharge_orders`+1"];
  1680. $aManageDay['normal_recharge_money'] = [
  1681. 'exp',
  1682. "`normal_recharge_money`+{$orders['money']}",
  1683. ];
  1684. $aManageDay['normal_recharge_money_benefit'] = [
  1685. 'exp',
  1686. "`normal_recharge_money_benefit`+{$cBenefitMoney}",
  1687. ];
  1688. if ($yd) {
  1689. $aManageDay['normal_recharge_guide_orders'] = [
  1690. 'exp',
  1691. "`normal_recharge_guide_orders`+1",
  1692. ];
  1693. $aManageDay['noraml_recharge_guide_money'] = [
  1694. 'exp',
  1695. "`noraml_recharge_guide_money`+{$orders['money']}",
  1696. ];
  1697. $aManageDay['noraml_recharge_guide_money_benefit'] = [
  1698. 'exp',
  1699. "`noraml_recharge_guide_money_benefit`+{$cBenefitMoney}",
  1700. ];
  1701. }
  1702. if (!$isActivity) {
  1703. $aManageDay['kandian_recharge_orders'] = ['exp', "`kandian_recharge_orders`+1"];
  1704. }
  1705. }
  1706. $sqlRes = $ordersCollect->update($aManageDay, ['id' => $manageResDay->id]);
  1707. if (empty($sqlRes)) {
  1708. Log::info('统计sql执行失败--表:ordersCollect--数据:' . json_encode($aManageDay) . 'where条件:' . json_encode(['id' => $manageResDay->id]));
  1709. }
  1710. }
  1711. } catch (\Exception $exception) {
  1712. Log::error('支付回调代理商统计出错:' . json_encode([
  1713. 'errcode' => $exception->getCode(),
  1714. 'errmsg' => $exception->getMessage()
  1715. ]));
  1716. }
  1717. }
  1718. /*
  1719. * book_collect表
  1720. */
  1721. if (!empty($orders['book_id'])) {
  1722. try {
  1723. if ($business == PayConstants::BUSINESS_APP) {
  1724. $dotData = new DotBookCollectObject();
  1725. $dotData->channelId = $orders['admin_id'];
  1726. $dotData->eventTime = Request::instance()->server('REQUEST_TIME');
  1727. $dotData->bookId = $orders['book_id'];
  1728. $dotData->rechargeMoney = $orders['money'];
  1729. $dotData->businessLine = $business;
  1730. $dot = BookDotService::instance()->generateBookData($dotData);
  1731. BookDotService::instance()->dotBookInfo($dot);
  1732. } else {
  1733. //管理员书籍统计
  1734. $this->bookConsumePayCollect(0, $orders['book_id'], $orders['money']);
  1735. //渠道商/代理商书籍统计
  1736. $this->bookConsumePayCollect($orders['admin_id'], $orders['book_id'], $orders['money']);
  1737. }
  1738. } catch (\Exception $exception) {
  1739. Log::error('支付回调book_collect统计出错:' . json_encode([
  1740. 'errcode' => $exception->getCode(),
  1741. 'errmsg' => $exception->getMessage()
  1742. ]));
  1743. }
  1744. }
  1745. }
  1746. if ($groupId == 4 && isset($channelBenefit) && intval($orders['deduct']) < 1) { //代理商
  1747. $times = time();
  1748. $trueToday = date('Ymd', $times);
  1749. //赏金统计
  1750. try {
  1751. if (!empty($orders['reward_money'])) {
  1752. $this_reward_money = round($orders['reward_money'], 2);
  1753. $reward_admin_id = $orders['admin_id'];
  1754. $rewardCollect = model('reward_collect');
  1755. //被邀请人按天
  1756. $reward_day = [
  1757. 'admin_id' => $reward_admin_id,
  1758. 'createdate' => $trueToday,
  1759. 'type' => '1',
  1760. 'flag' => '1',
  1761. ];
  1762. $reward_aDay_res = $rewardCollect->where($reward_day)->find();
  1763. if (!empty($reward_aDay_res)) { //更新
  1764. $rDay_res = [];
  1765. $rDay_res['reward'] = ['exp', "`reward`+{$this_reward_money}"];
  1766. $rDay_res['updatetime'] = $times;
  1767. model('reward_collect')->update($rDay_res, ['id' => $reward_aDay_res->id]);
  1768. } else { //插入
  1769. $reward_day_1['reward'] = $this_reward_money;
  1770. $reward_day_1['invite_id'] = $orders['reward_admin_id'];
  1771. $resadd = array_merge($reward_day_1, $reward_day);
  1772. $resadd['createtime'] = $times;
  1773. $resadd['updatetime'] = $times;
  1774. $rewardCollect->insert($resadd);
  1775. }
  1776. //被邀请人汇总
  1777. $reward_all = [
  1778. 'admin_id' => $reward_admin_id,
  1779. 'type' => '2',
  1780. 'flag' => '1',
  1781. ];
  1782. $reward_aAll_res = $rewardCollect->where($reward_all)->find();
  1783. if (!empty($reward_aAll_res)) { //更新
  1784. $rAll_res = [];
  1785. $rAll_res['reward'] = ['exp', "`reward`+{$this_reward_money}"];
  1786. $rAll_res['updatetime'] = $times;
  1787. $rewardCollect->update($rAll_res, ['id' => $reward_aAll_res->id]);
  1788. } else { //插入
  1789. $reward_all['reward'] = $this_reward_money;
  1790. $reward_all['invite_id'] = $orders['reward_admin_id'];
  1791. $reward_all['createtime'] = $times;
  1792. $reward_all['updatetime'] = $times;
  1793. $rewardCollect->insert($reward_all);
  1794. }
  1795. //邀请人按天
  1796. $reward_channel_day = [
  1797. 'admin_id' => $orders['reward_admin_id'],
  1798. 'invite_id' => 0,
  1799. 'createdate' => $trueToday,
  1800. 'type' => '1',
  1801. 'flag' => '2',
  1802. ];
  1803. $reward_cDay_res = $rewardCollect->where($reward_channel_day)->find();
  1804. if (!empty($reward_cDay_res)) { //更新
  1805. $reward_c_day = [];
  1806. $reward_c_day['reward'] = ['exp', "`reward`+{$this_reward_money}"];
  1807. $reward_c_day['updatetime'] = $times;
  1808. $rewardCollect->update($reward_c_day, ['id' => $reward_cDay_res->id]);
  1809. } else { //新增
  1810. $reward_channel_day['reward'] = $this_reward_money;
  1811. $reward_channel_day['createtime'] = $times;
  1812. $reward_channel_day['updatetime'] = $times;
  1813. $rewardCollect->insert($reward_channel_day);
  1814. }
  1815. //邀请人汇总
  1816. $reward_channel_all = [
  1817. 'admin_id' => $orders['reward_admin_id'],
  1818. 'invite_id' => 0,
  1819. 'type' => '2',
  1820. 'flag' => '2',
  1821. ];
  1822. $reward_cAll_res = $rewardCollect->where($reward_channel_all)->find();
  1823. if (!empty($reward_cAll_res)) { //更新
  1824. $reward_c_all = [];
  1825. $reward_c_all['reward'] = ['exp', "`reward`+{$this_reward_money}"];
  1826. $reward_c_all['updatetime'] = $times;
  1827. $rewardCollect->update($reward_c_all, ['id' => $reward_cAll_res->id]);
  1828. } else { //插入
  1829. $reward_channel_all['reward'] = $this_reward_money;
  1830. $reward_channel_all['createtime'] = $times;
  1831. $reward_channel_all['updatetime'] = $times;
  1832. $rewardCollect->insert($reward_channel_all);
  1833. }
  1834. //提现表维护
  1835. $reward_money = model('RewardMoney')->where('admin_id', $orders['reward_admin_id'])->find();
  1836. $rMoneyData = [];
  1837. if (!empty($reward_money)) { //更新
  1838. $rMoneyData['no_cash_money'] = ['exp', "`no_cash_money`+{$this_reward_money}"]; //未提现金额
  1839. $rMoneyData['reward_count'] = ['exp', "`reward_count`+{$this_reward_money}"]; //总赏金金额
  1840. $rMoneyData['updatetime'] = $times;
  1841. model('RewardMoney')->update($rMoneyData, ['id' => $reward_money['id']]);
  1842. } else { //插入
  1843. $rMoneyData['admin_id'] = $orders['reward_admin_id'];
  1844. $rMoneyData['no_cash_money'] = $this_reward_money;
  1845. $rMoneyData['reward_count'] = $this_reward_money;
  1846. $rMoneyData['createtime'] = $times;
  1847. $rMoneyData['updatetime'] = $times;
  1848. model('RewardMoney')->insert($rMoneyData);
  1849. }
  1850. }
  1851. } catch (\Exception $exception) {
  1852. Log::error('支付回调赏金统计出错');
  1853. }
  1854. //赏金统计结束
  1855. }
  1856. //打点
  1857. if($orders['deduct'] != 1 || empty($orders['resource_id'])){
  1858. //如果不是扣量或转移
  1859. $ext_data = json_decode($orders['ext'], true);
  1860. if (is_array($ext_data) && $ext_data && $business == PayConstants::BUSINESS_WECHAT) {
  1861. $oAna->user_from['mark'] = $ext_data['mark'];
  1862. $oAna->user_from['push_id'] = $ext_data['push_id'] ?? 0;
  1863. $oAna->user_from['push_idx'] = $ext_data['push_idx'] ?? BigData::DEFAULT_PUSH_IDX;
  1864. $oAna->user_from['push_time'] = $ext_data['push_time'] ?? time();
  1865. $dotData = SmartPushDotService::instance()->generateDotData(
  1866. $ext_data['mark'],
  1867. $ext_data['push_id'] ?? 0,
  1868. $ext_data['push_idx'] ?? BigData::DEFAULT_PUSH_IDX,
  1869. $ext_data['push_time'] ?? time(),
  1870. time(),
  1871. 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)
  1872. );
  1873. SmartPushDotService::instance()->dotSmartPushInfo($dotData);
  1874. }
  1875. 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'
  1876. , $orders['wxpay_id'], $orders['admin_id'], $orders['money'], $orders['goods_id'],
  1877. $orders['out_trade_no'], $orders['ext'], $transactionId, $pdorderid));
  1878. }
  1879. //如果是消耗活动充值,直接进行报名
  1880. if (isset($orderExtendType['type']) && $orderExtendType['type'] == 1 ){
  1881. $matchInfo = json_decode( $orderExtendType['json'], true );
  1882. CampaignService::instance()->autoCheckIn($userInfo,$matchInfo);
  1883. }
  1884. //订阅活动报名
  1885. if (isset($orderExtendType['type']) && $orderExtendType['type'] == 2 ){
  1886. $act = json_decode($orderExtendType['json'],true);
  1887. $actId = $act['act_id']??0;
  1888. SubscripService::instance()->insertActUser($userInfo,$actId,$orders);
  1889. }
  1890. //充值成功 发送活动推送
  1891. MqUserPaySuccessService::instance()->sendActiveToUser($orders,$userInfo);
  1892. $adminConfig = AdminService::instance()->getAdminConfigModel()->getAdminInfoAll($channel_id);
  1893. //非扣量
  1894. if (intval($orders['deduct']) < 1) {
  1895. KafkaDotService::instance()->sendMsg($oOrder->user_id, $oAna);
  1896. $toutType = $adminConfig['callback_time_tout'] ?? AdminConstants::CALLBACK_TIME_ONCE_24;
  1897. LogService::info('toutpaytype:' . $toutType . ':' . $userInfo['id']);
  1898. $check = ToutiaoNotifyService::instance()->checkCallbackTime($userInfo['subscribe_time'], $toutType)->data;
  1899. $sToutChuanKey = CacheConstants::getCallbackLimitTout($orders['user_id']);
  1900. $sToutChuanKeyOnce = CacheConstants::getCallbackLimitToutOnce($orders['user_id']);
  1901. if (in_array($toutType, [AdminConstants::CALLBACK_TIME_ONCE_24, AdminConstants::CALLBACK_TIME_ONCE_DAY])) {
  1902. //已经回传过的
  1903. if (Redis::instance()->get($sToutChuanKeyOnce)) {
  1904. Redis::instance()->set($sToutChuanKey, $orders['id'], 86400);
  1905. }
  1906. } else {
  1907. Redis::instance()->del($sToutChuanKey);
  1908. }
  1909. //头条回传
  1910. if ($check && !Redis::instance()->get($sToutChuanKey)) {
  1911. $toutKl = ReportKlService::instance()->getKlConfig($orders['admin_id'], PostbackConstants::TYPE_TOUTIAO, $orders['referral_id'])->data;
  1912. $ifNotKl = ReportKlService::instance()->checkNotKl($orders['admin_id'], $toutKl, $orders['referral_id'], $orders['money'])->data;
  1913. if ($ifNotKl) {
  1914. $type = ToutiaoNotifyService::instance()::ORANGE_EVENT_TYPE_PAY;
  1915. $oUser = (new UserObject())->bind($userInfo);
  1916. //橘子建站回传支持
  1917. ToutiaoNotifyService::instance()->OrangeNotify($adminConfig, $oUser, $type, $oOrder);
  1918. if ($link = Redis::instance()->get(CacheConstants::getGuideWxPay($orders['user_id']))) {
  1919. ToutiaoNotifyService::instance()->notify($link, $orders['user_id'], ToutiaoNotifyService::EVENT_TYPE_PAY, $orders['money']);
  1920. Redis::instance()->set($sToutChuanKeyOnce, $orders['id'], 86400);
  1921. LogService::info('toutpayback:' . $orders['out_trade_no'] . ':' . $userInfo['id'] . ':' . $link);
  1922. if (in_array($toutType, [AdminConstants::CALLBACK_TIME_ONCE_24, AdminConstants::CALLBACK_TIME_ONCE_DAY])) {
  1923. LogService::info('toutpaybackonce:' . $toutType . ':' . $userInfo['id'] . ':' . $link);
  1924. Redis::instance()->set($sToutChuanKey, $orders['id'], 86400);
  1925. }
  1926. }
  1927. }
  1928. }
  1929. //uc回传
  1930. $ucType = $adminConfig['callback_time_uc'] ?? AdminConstants::CALLBACK_TIME_ONCE_24;
  1931. LogService::info('ucpaytype:' . $ucType . ':' . $userInfo['id']);
  1932. $check = ToutiaoNotifyService::instance()->checkCallbackTime($userInfo['subscribe_time'], $ucType)->data;
  1933. $sUcChuanKey = CacheConstants::getCallbackLimitUc($orders['user_id']);
  1934. $sUcChuanKeyOnce = CacheConstants::getCallbackLimitUcOnce($orders['user_id']);
  1935. if (in_array($ucType, [AdminConstants::CALLBACK_TIME_ONCE_24, AdminConstants::CALLBACK_TIME_ONCE_DAY])) {
  1936. //已经回传过的
  1937. if (Redis::instance()->get($sUcChuanKeyOnce)) {
  1938. Redis::instance()->set($sUcChuanKey, $orders['id'], 86400);
  1939. }
  1940. } else {
  1941. Redis::instance()->del($sUcChuanKey);
  1942. }
  1943. if ($check && !Redis::instance()->get($sUcChuanKey)) {
  1944. if ($link = Redis::instance()->get(UcCacheConstants::getGuideWxPay($orders['user_id']))) {
  1945. $ucKl = ReportKlService::instance()->getKlConfig($orders['admin_id'], PostbackConstants::TYPE_UC, $orders['referral_id'])->data;
  1946. $ifNotKl = ReportKlService::instance()->checkNotKl($orders['admin_id'], $ucKl, $orders['referral_id'], $orders['money'])->data;
  1947. if ($ifNotKl) {
  1948. UcNotifyService::instance()->notify($userInfo, $link, UcNotifyService::EVENT_TYPE_PAY, $orders['money']);
  1949. Redis::instance()->set($sUcChuanKeyOnce, $orders['id'], 86400);
  1950. LogService::info('ucpayback:' . $orders['out_trade_no'] . ':' . $userInfo['id'] . ':' . $link);
  1951. if (in_array($ucType, [AdminConstants::CALLBACK_TIME_ONCE_24, AdminConstants::CALLBACK_TIME_ONCE_DAY])) {
  1952. LogService::info('ucpaybackonce:' . $ucType . ':' . $userInfo['id'] . ':' . $link);
  1953. Redis::instance()->set($sUcChuanKey, $orders['id'], 86400);
  1954. }
  1955. }
  1956. }
  1957. }
  1958. $channel_id = $userInfo['channel_id'];
  1959. $chan_id = $userInfo['channel_id'];
  1960. if ($orders['activity_id']) {
  1961. $url = "/index/recharge/activity?aid={$orders['activity_id']}&user_id={$orders['user_id']}";
  1962. } else {
  1963. if ($orders['book_id']) {
  1964. $chan_id = Config::get('site.tdc_bookinfo_url_channel') ?: $channel_id;
  1965. $url = '/index/book/info?book_id='.$orders['book_id'];
  1966. } else {
  1967. $url = "/index/recharge/pay?id={$orders['goods_id']}&user_id={$orders['user_id']}&book_id={$orders['book_id']}";
  1968. }
  1969. }
  1970. $url = getCurrentDomain($chan_id,$url);
  1971. $productName = '';
  1972. if(empty($orders['book_id'])){
  1973. $orders['book_id'] = (int)0;
  1974. }
  1975. if ($orders['book_id']) {
  1976. $theme = \think\Config::get('site.theme');
  1977. if ($theme == null) {
  1978. //库里拉取
  1979. $site = model("Config")->getConfigSiteArr();
  1980. $theme = $site['theme'];
  1981. }
  1982. if($theme == 'yg') {
  1983. $platformName = "阳光";
  1984. } else if ($theme == 'px') {
  1985. $platformName = "点看";
  1986. } else if ($theme == 'sf') {
  1987. $platformName = "沙发";
  1988. } else if ($theme == 'qy') {
  1989. $platformName = "袋鼠";
  1990. } else {
  1991. $platformName = "西瓜";
  1992. }
  1993. $bookInfo = BookService::instance()->getBookModel()->BookInfo($orders['book_id']);
  1994. $productName = $bookInfo['name'] . '-' . $platformName;
  1995. }
  1996. //mp回传
  1997. $mpType = $adminConfig['callback_time_mp'] ?? AdminConstants::CALLBACK_TIME_ONCE_24;
  1998. LogService::info('mppaytype:' . $mpType . ':' . $userInfo['id']);
  1999. $check = ToutiaoNotifyService::instance()->checkCallbackTime($userInfo['subscribe_time'], $mpType)->data;
  2000. $sMpChuanKey = CacheConstants::getCallbackLimitMp($orders['user_id']);
  2001. $sMpChuanKeyOnce = CacheConstants::getCallbackLimitMpOnce($orders['user_id']);
  2002. if (in_array($mpType, [AdminConstants::CALLBACK_TIME_ONCE_24, AdminConstants::CALLBACK_TIME_ONCE_DAY])) {
  2003. //已经回传过的
  2004. if (Redis::instance()->get($sMpChuanKeyOnce)) {
  2005. Redis::instance()->set($sMpChuanKey, $orders['id'], 86400);
  2006. }
  2007. } else {
  2008. Redis::instance()->del($sMpChuanKey);
  2009. }
  2010. LogService::info('订阅活动-是否首充'.$userInfo['is_pay']);
  2011. SubscripService::instance()->insertOldLog($userInfo);
  2012. if ($check && !Redis::instance()->get($sMpChuanKey)) {
  2013. //当天仅回传一次
  2014. $guangdtKl = ReportKlService::instance()->getKlConfig($orders['admin_id'], PostbackConstants::TYPE_GUANGDIANTONG, $orders['referral_id'])->data;
  2015. $ifNotKl = ReportKlService::instance()->checkNotKl($orders['admin_id'], $guangdtKl, $orders['referral_id'], $orders['money'])->data;
  2016. if ($ifNotKl) {
  2017. if (in_array($mpType, [AdminConstants::CALLBACK_TIME_ONCE_24, AdminConstants::CALLBACK_TIME_ONCE_DAY])) {
  2018. //首次充值回传写入缓存
  2019. Redis::instance()->set($sMpChuanKey, $orders['id'], 86400);
  2020. }
  2021. Redis::instance()->set($sMpChuanKeyOnce, $orders['id'], 86400);
  2022. //微信AD数据源上报
  2023. 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']);
  2024. 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']);
  2025. // WeChatAdService::instance()->SendWxAdSource($channel_id,$url,$userInfo['openid'], $orders['money'], $productName);
  2026. // WeChatAdService::instance()->SendWxAdSource($channel_id,$url,$userInfo['openid'], $orders['money'], $productName, 'PURCHASE');
  2027. //回传总金额
  2028. $orderReportKey = "CORDS:".$channel_id.":".date("Ymd");
  2029. Redis::instance()->sAdd($orderReportKey, $orders['out_trade_no']);
  2030. Redis::instance()->expire($orderReportKey, 86400*7);
  2031. //Ab号回源
  2032. if (!empty($orders['referral_id']) && $business == PayConstants::BUSINESS_WECHAT) {
  2033. 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']]);
  2034. 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']]);
  2035. }
  2036. }
  2037. }
  2038. //gdt回传
  2039. if (isset($adminConfig['gdt_mp_report_state']) && $adminConfig['gdt_mp_report_state'] == 1) {
  2040. //回传设置走mp的
  2041. $mpType = $adminConfig['callback_time_mp'] ?? AdminConstants::CALLBACK_TIME_ONCE_24;
  2042. LogService::info('mppaytype:' . $mpType . ':' . $userInfo['id']);
  2043. $check = ToutiaoNotifyService::instance()->checkCallbackTime($userInfo['subscribe_time'], $mpType)->data;
  2044. $sGdtChuanKey = CacheConstants::getCallbackLimitGdt($orders['user_id']);
  2045. $sGdtChuanKeyOnce = CacheConstants::getCallbackLimitGdtOnce($orders['user_id']);
  2046. if (in_array($mpType, [AdminConstants::CALLBACK_TIME_ONCE_24, AdminConstants::CALLBACK_TIME_ONCE_DAY])) {
  2047. //已经回传过的
  2048. if (Redis::instance()->get($sGdtChuanKeyOnce)) {
  2049. Redis::instance()->set($sGdtChuanKey, $orders['id'], 86400);
  2050. }
  2051. } else {
  2052. Redis::instance()->del($sGdtChuanKey);
  2053. }
  2054. if ($check && !Redis::instance()->get($sGdtChuanKey)) {
  2055. //当天仅回传一次
  2056. $gdtKl = ReportKlService::instance()->getKlConfig($orders['admin_id'], PostbackConstants::TYPE_GDT, $orders['referral_id'])->data;
  2057. $ifNotKl = ReportKlService::instance()->checkNotKl($orders['admin_id'], $gdtKl, $orders['referral_id'], $orders['money'])->data;
  2058. if ($ifNotKl) {
  2059. if (in_array($mpType, [AdminConstants::CALLBACK_TIME_ONCE_24, AdminConstants::CALLBACK_TIME_ONCE_DAY])) {
  2060. //首次充值回传写入缓存
  2061. Redis::instance()->set($sGdtChuanKey, $orders['id'], 86400);
  2062. }
  2063. Redis::instance()->set($sGdtChuanKeyOnce, $orders['id'], 86400);
  2064. //数据源上报
  2065. 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']]);
  2066. 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']]);
  2067. //回传总金额
  2068. $orderReportKey = "CORDS:G:".$channel_id.":".date("Ymd");
  2069. Redis::instance()->sAdd($orderReportKey, $orders['out_trade_no']);
  2070. Redis::instance()->expire($orderReportKey, 86400*7);
  2071. }
  2072. }
  2073. }
  2074. }
  2075. if ($float_id = Redis::instance()->get(CacheConstants::getFloatTipsOrderId($orders['id']))) {
  2076. FloatTipsService::instance()->updateFloatOrder($float_id, $orders['user_id'], $orders['money']);
  2077. }
  2078. $export = ExportFansService::instance()->checkFansLead($channel_id, $orders['user_id'])->data;
  2079. if ($export) {
  2080. $unrechargeKey = CacheConstants::getFansUnrecharge($orders['user_id']);
  2081. Redis::instance()->del($unrechargeKey);
  2082. }
  2083. KuaifenService::instance()->reportOrders($oOrder);
  2084. }
  2085. private function _saveUserDot(Orders $orders)
  2086. {
  2087. // getUserInfo($orders['user_id'], true) 直接走数据库,缓存哩vip_endtime 不及时
  2088. $user_info = model('User')->getUserInfo($orders['user_id'], true);
  2089. $ip_redis_key = CacheConstants::USER_IP_PREFIX . $orders['user_id'];
  2090. $ip_arr = json_decode(Redis::instance()->get($ip_redis_key), true, 1024);
  2091. // region 用户画像打点到Nginx
  2092. try{
  2093. $dotdata = [
  2094. 'ctime' => time(),
  2095. 'uid' => $user_info['id'],
  2096. 'openid' => $user_info['openid'],
  2097. 'unionid' => '',
  2098. 'ip' => $ip_arr['ip'] ?? '',
  2099. 'country' => $ip_arr['country'] ?? '',
  2100. 'province' => $ip_arr['province'] ?? '',
  2101. 'city' => $ip_arr['city'] ?? '',
  2102. 'pline' => empty(Config::get('site.theme')) ? 'xg' : Config::get('site.theme'),
  2103. 'agent_id' => $user_info['agent_id'] ?? '',
  2104. 'chid' => $user_info['channel_id'] ?? '',
  2105. 'ua' => $ip_arr['ua'],
  2106. 'cookie' => '',
  2107. 'type' => 'pay',
  2108. 'user' => [
  2109. 'gender' => $user_info['sex'],
  2110. 'is_subscribe' => $user_info['is_subscribe'],
  2111. 'vip_endtime' => $user_info['vip_endtime'],
  2112. 'subscribe_time' => $user_info['subscribe_time'],
  2113. 'is_pay' => $user_info['is_pay'],
  2114. 'referral_id' => $user_info['referral_id'],
  2115. 'ext' => $user_info['ext'] ? json_decode($user_info['ext'], true) : [],
  2116. ],
  2117. 'content' => [
  2118. 'order_id' => $orders['id'], // 订单ID
  2119. 'discount' => $orders['money'],// 订单金额,单位 元
  2120. ]
  2121. ];
  2122. curl_user_dot($dotdata);
  2123. }catch (\Exception $exception){
  2124. LogService::error("save_orders:_saveUserDot:".$exception->getMessage());
  2125. }
  2126. // endregion
  2127. }
  2128. /**
  2129. * 书籍计费统计
  2130. * @param $channel_id
  2131. * @param $book_id
  2132. * @param $recharge_money
  2133. * @throws \Exception
  2134. */
  2135. private function bookConsumePayCollect($channel_id,$book_id,$recharge_money){
  2136. $redis = Redis::instance();
  2137. //设置渠道籍列表
  2138. $collect_list_key = "BC-CL:".date("Ymd");
  2139. $redis->sadd($collect_list_key,$channel_id);
  2140. $redis->expire($collect_list_key,86400*2);
  2141. //设置渠道商书籍列表
  2142. $collect_channel_book_key = "BC-BL:{$channel_id}:".date("Ymd");
  2143. $redis->sadd($collect_channel_book_key,$book_id);
  2144. $redis->expire($collect_channel_book_key,86400*2);
  2145. //设置渠道商对应书籍数据
  2146. $collect_key = "BC:{$book_id}:{$channel_id}:".date("Ymd");
  2147. if($data = json_decode($redis->get($collect_key),true)){
  2148. $data['recharge_num'] = intval($data['recharge_num'] ?? 0)+1;
  2149. $data['recharge_money'] = intval($data['recharge_money'] ?? 0) + intval($recharge_money * 100);
  2150. $redis->setex($collect_key,86400*2,json_encode($data));
  2151. }else{
  2152. $data['recharge_num'] = intval($data['recharge_num'] ?? 0)+1;
  2153. $data['recharge_money'] = intval($data['recharge_money'] ?? 0) + intval($recharge_money * 100);
  2154. $redis->setex($collect_key,86400*2,json_encode($data));
  2155. }
  2156. }
  2157. /**
  2158. * 分账金额
  2159. * @param $orderInfo
  2160. * @return int
  2161. * @throws \think\exception\DbException
  2162. */
  2163. public function splitMoney($orderInfo)
  2164. {
  2165. $splitMoney = 0;
  2166. if ($orderInfo['deduct']) {
  2167. return $splitMoney;
  2168. }
  2169. if ($orderInfo['payment_method'] == ApiConstants::PAYMENT_METHOD_PALM) {
  2170. //四分支付
  2171. $payInfo = model('Wxpay')->getInfoById($orderInfo['wxpay_id']);
  2172. if ($payInfo && $payInfo['quartet_is_split'] == ApiConstants::QUARTET_IS_SPLIT) {
  2173. //开启分账 查找分账订单
  2174. $splitRow = PalmpaySplitAccountLog::get(['order_id' => $orderInfo['out_trade_no']]);
  2175. if ($splitRow && $splitRow['channel_amount']) {
  2176. $splitMoney = $splitRow['channel_amount'];
  2177. }
  2178. }
  2179. }
  2180. return $splitMoney;
  2181. }
  2182. }