AdReport.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  1. <?php
  2. namespace App\Console\Commands\Wechat;
  3. use GuzzleHttp\Client;
  4. use Illuminate\Console\Command;
  5. use App\Http\Controllers\WechatController;
  6. use Exception;
  7. use Log;
  8. use DB;
  9. use Redis;
  10. class AdReport extends Command
  11. {
  12. /**
  13. * The name and signature of the console command.
  14. *
  15. * @var string
  16. */
  17. protected $signature = 'Wechat:WeixinAdReport';
  18. /**
  19. * The console command description.
  20. *
  21. * @var string
  22. */
  23. protected $description = 'Command description';
  24. /**
  25. * Create a new command instance.
  26. *
  27. * @return void
  28. */
  29. public function __construct()
  30. {
  31. parent::__construct();
  32. }
  33. private $user_action_set_id = [];
  34. private $assess_token = [];
  35. private $error_msg;
  36. /**
  37. * Execute the console command.
  38. *
  39. * @return mixed
  40. */
  41. public function handle()
  42. {
  43. $this->start();
  44. }
  45. private function start(){
  46. $data = $this->getDataFromDB();
  47. if($data){
  48. $this->getDataAndReport($data);
  49. }
  50. }
  51. private function getDataFromDB(){
  52. $data = [];
  53. $start = date('Y-m-d');
  54. if(date('H:i:s') < '02:00:00'){
  55. $start = date('Y-m-d H:i:s',time()-3*3600);
  56. }
  57. $result = DB::connection('api_mysql')->table('distribution_channel_weixin_ad_report_orders')
  58. ->where('report_status',0)
  59. ->where('created_at','>=',$start)
  60. ->select('order_id','appid','openid','price','report_status','created_at','report_type')
  61. ->get();
  62. if($result){
  63. foreach ($result as $item){
  64. $order_status = DB::connection('api_mysql')->table('orders')->where('id',$item->order_id)->select('status')->first();
  65. if($order_status->status == 'UNPAID')continue;
  66. $report_info = DB::table('wechat_advertise_report_record')->where('product_id',$item->order_id)->where('result_status','SUCCESS')->count();
  67. if($report_info) {
  68. try{
  69. DB::connection('api_mysql')->table('distribution_channel_weixin_ad_report_orders')->where('order_id',$item->order_id)->update([
  70. 'report_status'=>1,
  71. 'updated_at'=>date('Y-m-d H:i:s')
  72. ]);
  73. }catch (\Exception $e){
  74. \Log::info($e);
  75. }
  76. continue;
  77. }
  78. $data[] = ['created_at' => $item->created_at, 'openid' => $item->openid,'report_type'=>$item->report_type,
  79. 'id' => $item->order_id, 'appid' => $item->appid, 'price' => $item->price];
  80. }
  81. }
  82. return $data;
  83. }
  84. private function getDataAndReport($order_result){
  85. $result = $order_result;
  86. $client = new Client();
  87. foreach ($result as $item){
  88. $report_type = $this->transferReportType($item['report_type'],$item['created_at'],$item['id']);
  89. $item_array = $item;
  90. $user_action_set_id = $this->getDataSurce($item_array['appid']);
  91. $data = [
  92. 'user_action_set_id'=>$user_action_set_id,
  93. 'url'=>'',
  94. 'action_time'=>strtotime($item_array['created_at']),
  95. 'action_type'=>'COMPLETE_ORDER',
  96. 'openid'=>$item_array['openid'],
  97. 'appid'=>$item_array['appid'],
  98. 'product_id'=>$item_array['id'],
  99. 'value'=>$item_array['price']*100,
  100. 'source'=>'Biz',
  101. 'claim_type'=>0,
  102. 'object'=>$report_type
  103. ];
  104. $data['created_at'] = date('Y-m-d H:i:s');
  105. $data['updated_at'] = date('Y-m-d H:i:s');
  106. $data['result_status'] = 'FAIL';
  107. $book_info = $this->getBookName($item_array['id']);
  108. $product_id = '';
  109. $product_name = '';
  110. $data['bid'] = $book_info['en_bid'];
  111. if($book_info['en_bid'] && $book_info['book_name']){
  112. $product_id = $book_info['en_bid'];
  113. $data['bid'] = $book_info['en_bid'];
  114. $product_name = $book_info['book_name'].'-'.env('PROJECT_NAME');
  115. $data['product_name'] = $product_name;
  116. $data['url'] = env('GDT_REPORT_URL').'/detail?id='.$book_info['en_bid'];
  117. }
  118. $data['result'] = '';
  119. if(!$user_action_set_id) {
  120. $data['result_msg'] = $this->error_msg;
  121. DB::table('wechat_advertise_report_record')->insert($data);
  122. continue;
  123. };
  124. $request_data = [
  125. 'actions'=>[
  126. [
  127. 'user_action_set_id'=>$data['user_action_set_id'],
  128. 'url'=>$data['url'],
  129. 'action_time'=>$data['action_time'],
  130. 'action_type'=>$data['action_type'],
  131. 'user_id'=>[
  132. 'wechat_app_id'=>$data['appid'],
  133. 'wechat_openid'=>$data['openid']
  134. ],
  135. 'action_param'=>[
  136. 'object'=>$report_type,
  137. 'product_name'=>$product_name,
  138. 'product_id'=>$product_id,
  139. 'source'=>$data['source'],
  140. 'wechat_app_id'=>'',
  141. 'claim_type'=>$data['claim_type'],
  142. 'value'=>$item_array['price']*100
  143. ]
  144. ]
  145. ]
  146. ];
  147. $token = $this->getAccessToken($item_array['appid']);
  148. if(!$token) continue;
  149. $url = 'https://api.weixin.qq.com/marketing/user_actions/add?version=v1.0&access_token='.$token;
  150. try{
  151. $result = $client->request('post',$url,[
  152. 'headers'=>['Content-Type'=>'application/json'],
  153. 'body'=>\GuzzleHttp\json_encode($request_data)
  154. ])->getBody()->getContents();
  155. Log::info('user_actions/add result is: '.$result);
  156. $result_array = \GuzzleHttp\json_decode($result,1);
  157. if(isset($result_array['errcode']) && $result_array['errcode'] == 0){
  158. $data['result_status'] = 'SUCCESS';
  159. $data['result_msg'] = $result_array['errcode'];
  160. $data['result'] = $result;
  161. }else{
  162. $data['result_status'] = 'FAIL';
  163. $data['result_msg'] = isset($result_array['errcode'])?$result_array['errcode']:'unknown';
  164. $data['result'] = $result;
  165. }
  166. DB::table('wechat_advertise_report_record')->insert($data);
  167. try{
  168. if($data['result_status'] == 'SUCCESS'){
  169. DB::connection('api_mysql')->table('distribution_channel_weixin_ad_report_orders')->where('order_id',$item_array['id'])->update([
  170. 'report_status'=>1,
  171. 'updated_at'=>date('Y-m-d H:i:s')
  172. ]);
  173. }
  174. }catch (\Exception $e){\Log::info($e);}
  175. }catch (Exception $e){
  176. Log::error($e);
  177. }
  178. try{
  179. $this->secondReport($client,$item,$user_action_set_id,$book_info['en_bid'],$book_info['book_name'],$token,$report_type);
  180. }catch (\Exception $e){
  181. \Log::info($e);
  182. }
  183. }
  184. }
  185. private function secondReport(Client $client,$data,$user_action_set_id,$bid='',$book_name='',$token='',$report_type){
  186. $item_array = $data;
  187. $data = [
  188. 'user_action_set_id'=>$user_action_set_id,
  189. 'url'=>'',
  190. 'action_time'=>strtotime($item_array['created_at']),
  191. 'action_type'=>'PURCHASE',
  192. 'openid'=>$item_array['openid'],
  193. 'appid'=>$item_array['appid'],
  194. 'product_id'=>$item_array['id'],
  195. 'value'=>$item_array['price']*100,
  196. 'source'=>'Biz',
  197. 'claim_type'=>0,
  198. 'object'=>$report_type
  199. ];
  200. $data['created_at'] = date('Y-m-d H:i:s');
  201. $data['updated_at'] = date('Y-m-d H:i:s');
  202. $data['result_status'] = 'FAIL';
  203. $product_id = '';
  204. $product_name = '';
  205. $data['bid'] = '';
  206. if($bid && $book_name){
  207. $product_id = $bid;
  208. $data['bid'] = $bid;
  209. $product_name = $book_name.'-'.env('PROJECT_NAME');
  210. $data['product_name'] = $product_name;
  211. $data['url'] = env('GDT_REPORT_URL').'/detail?id='.$bid;
  212. }
  213. $data['result'] = '';
  214. if(!$user_action_set_id) {
  215. $data['result_msg'] = $this->error_msg;
  216. DB::table('wechat_advertise_report_record')->insert($data);
  217. };
  218. $request_data = [
  219. 'actions'=>[
  220. [
  221. 'user_action_set_id'=>$data['user_action_set_id'],
  222. 'url'=>$data['url'],
  223. 'action_time'=>$data['action_time'],
  224. 'action_type'=>$data['action_type'],
  225. 'user_id'=>[
  226. 'wechat_app_id'=>$data['appid'],
  227. 'wechat_openid'=>$data['openid']
  228. ],
  229. 'action_param'=>[
  230. 'object'=>$report_type,
  231. 'product_name'=>$product_name,
  232. 'product_id'=>$product_id,
  233. 'source'=>$data['source'],
  234. 'wechat_app_id'=>'',
  235. 'claim_type'=>$data['claim_type'],
  236. 'value'=>$item_array['price']*100
  237. ]
  238. ]
  239. ]
  240. ];
  241. if(!$token) return '';
  242. $url = 'https://api.weixin.qq.com/marketing/user_actions/add?version=v1.0&access_token='.$token;
  243. try{
  244. $result = $client->request('post',$url,[
  245. 'headers'=>['Content-Type'=>'application/json'],
  246. 'body'=>\GuzzleHttp\json_encode($request_data)
  247. ])->getBody()->getContents();
  248. Log::info('user_actions/add result is: '.$result);
  249. $result_array = \GuzzleHttp\json_decode($result,1);
  250. if(isset($result_array['errcode']) && $result_array['errcode'] == 0){
  251. $data['result_status'] = 'SUCCESS';
  252. $data['result_msg'] = $result_array['errcode'];
  253. $data['result'] = $result;
  254. }else{
  255. $data['result_status'] = 'FAIL';
  256. $data['result_msg'] = isset($result_array['errcode'])?$result_array['errcode']:'unknown';
  257. $data['result'] = $result;
  258. }
  259. DB::table('wechat_advertise_report_record')->insert($data);
  260. return $data['result_status'];
  261. }catch (Exception $e){
  262. Log::error($e);
  263. }
  264. return '';
  265. }
  266. private function getDataSurce($appid,$type='WECHAT'){
  267. if(!isset($this->user_action_set_id[$appid])){
  268. $result = $this->getDataSourceFromDB($appid,$type);
  269. if($result){
  270. $this->user_action_set_id[$appid] = $result;
  271. return $result;
  272. }
  273. $result = $this->createDataSource($appid,$type);
  274. if($result){
  275. $this->user_action_set_id[$appid] = $result;
  276. return $result;
  277. }
  278. Log::info('appid is :'.$appid.', createDataSource fail');
  279. return '';
  280. }
  281. return $this->user_action_set_id[$appid];
  282. }
  283. private function getAccessToken($appid){
  284. if(isset($this->assess_token[$appid])){
  285. return $this->assess_token[$appid];
  286. }
  287. /*$WechatController = new WechatController($appid);
  288. $accessToken = $WechatController->app->access_token; // EasyWeChat\Core\AccessToken 实例
  289. $token = $accessToken->getToken(); // token 字符串
  290. if($token){
  291. $this->assess_token[$appid] = $token;
  292. return $token;
  293. }
  294. Log::info('appid is :'.$appid.',request access_token fail');
  295. return '';*/
  296. $access_token = Redis::get('Wechat:access_token:appid:'.$appid);
  297. if($access_token){
  298. $this->assess_token[$appid] = $access_token;
  299. return $this->assess_token[$appid];
  300. }
  301. /*$appsecret = 'f73d3be068d86417bf1a3fafefe4596a';
  302. $url = sprintf(
  303. 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s',
  304. $appid,
  305. $appsecret
  306. );
  307. $client = new Client();
  308. $result = $client->request('get',$url)->getBody()->getContents();
  309. Log::info('request access token ,result is:'.$result);
  310. $result = \GuzzleHttp\json_decode($result,1);
  311. if($result && isset($result['access_token'])){
  312. Redis::setex('Wechat:access_token:appid:'.$appid,7000,$result['access_token']);
  313. $this->assess_token[$appid] = $result['access_token'];
  314. return $this->assess_token[$appid];
  315. }*/
  316. $this->error_msg = $appid.',access_token fail';
  317. return '';
  318. }
  319. private function createDataSource(string $appid,string $type){
  320. $token = $this->getAccessToken($appid);
  321. if(!$token) return 0;
  322. $url = 'https://api.weixin.qq.com/marketing/user_action_sets/add?version=v1.0&access_token='.$token;
  323. $client = new Client();
  324. $name = '支付下单';
  325. $description = '支付下单,充值统计';
  326. $body = json_encode([
  327. 'type'=>$type,
  328. 'wechat_app_id'=>$appid,
  329. 'name'=>$name,
  330. 'description'=>$description
  331. ]);
  332. try{
  333. $result = $client->request('post',$url,[
  334. 'headers'=>['Content-Type'=>'application/json'],
  335. 'body'=>$body
  336. ])->getBody()->getContents();
  337. $result = \GuzzleHttp\json_decode($result,1);
  338. if($result['errcode'] == 0 && isset($result['data']) && isset($result['data']['user_action_set_id'])){
  339. $user_action_set_id = $result['data']['user_action_set_id'];
  340. $this->saveDataSource($appid,$name,$type,$description,$user_action_set_id);
  341. return $user_action_set_id;
  342. }
  343. if($result['errcode'] == 900351000){
  344. $msg_array = explode(':',$result['errmsg']);
  345. if(isset($msg_array[1])){
  346. $user_action_set_id = trim($msg_array[1]);
  347. $this->saveDataSource($appid,$name,$type,$description,$user_action_set_id);
  348. return $user_action_set_id;
  349. }
  350. }
  351. }catch (Exception $e){
  352. Log::error($e);
  353. }
  354. $this->error_msg = $appid.',createDataSource fail';
  355. return 0;
  356. }
  357. private function getDataSourceFromDB($appid,$type):int
  358. {
  359. $result = DB::table('wechat_advertise_data_source')->where('appid', $appid)->where('type', $type)->select('user_action_set_id')->first();
  360. if($result){
  361. return $result->user_action_set_id;
  362. }
  363. return 0;
  364. }
  365. private function saveDataSource(string $appid,string $name,string $type,string $description,int $user_action_set_id){
  366. DB::table('wechat_advertise_data_source')->insert([
  367. 'appid'=>$appid,
  368. 'name'=>$name,
  369. 'type'=>$type,
  370. 'description'=>$description,
  371. 'user_action_set_id'=>$user_action_set_id,
  372. 'created_at'=>date('Y-m-d H:i:s'),
  373. 'updated_at'=>date('Y-m-d H:i:s')
  374. ]);
  375. }
  376. private function getBookName($order_id){
  377. $result = ['bid'=>'','book_name'=>'','en_bid'=>''];
  378. try{
  379. $order_info = DB::connection('api_mysql')->table('orders')->select('from_bid')->where('id',$order_id)->first();
  380. if($order_info && $order_info->from_bid){
  381. $result['bid'] = $order_info->from_bid;
  382. $result['en_bid'] = \Hashids::encode($order_info->from_bid);
  383. $book_info = DB::connection('api_mysql')->table('book_configs')
  384. ->select('book_name','is_on_shelf')
  385. ->where('bid',$order_info->from_bid)->first();
  386. if($book_info){
  387. if($book_info->is_on_shelf == 2){
  388. $result['book_name'] = $book_info->book_name;
  389. }
  390. }
  391. return $result;
  392. }
  393. }catch (\Exception $e){
  394. }
  395. return $result;
  396. }
  397. private function transferReportType($report_type,$order_time,$order_id){
  398. $map = [
  399. 'one_day_first_pay'=>'read_1',
  400. 'one_day_all_pay'=>'read_2',
  401. 'current_day_register_first_pay'=>'read_3',
  402. 'current_day_register'=>'read_4',
  403. 'three_day_first_pay'=>'read_5',
  404. 'three_day_all_pay'=>'read_6'
  405. ];
  406. if(isset($map[$report_type])){
  407. return $map[$report_type];
  408. }
  409. $order_info = DB::connection('api_mysql')->table('orders')->where('id',$order_id)->select('uid')->first();
  410. if(!$order_info){
  411. return '';
  412. }
  413. $uid = $order_info->uid;
  414. $user_info = DB::connection('api_mysql')->table('users')->where('id',$uid)->select('created_at')->first();
  415. if(!$user_info) return '';
  416. $register_time = $user_info->created_at;
  417. $register_timestamp = strtotime($register_time);
  418. $order_timestamp = strtotime($order_time);
  419. if(date('Y-m-d',$register_timestamp) == date('Y-m-d',$order_timestamp)){
  420. return 'read_4';
  421. }
  422. if(strtotime($order_time) - strtotime($register_time) < 86400){
  423. return 'read_2';
  424. }
  425. if(strtotime($order_time) - strtotime($register_time) < 3*86400){
  426. return 'read_6';
  427. }
  428. return '';
  429. }
  430. }