OrdersController.php 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090
  1. <?php
  2. namespace App\Http\Controllers\WapAlipay\Pay;
  3. use Illuminate\Routing\Controller;
  4. use App\Libs\Pay\WechatPay;
  5. use Illuminate\Http\Request;
  6. use App\Modules\Subscribe\Services\YearOrderService;
  7. use App\Modules\Subscribe\Services\BookOrderService;
  8. use App\Modules\Subscribe\Services\OrderService;
  9. use App\Modules\Product\Services\ProductService;
  10. use App\Modules\Book\Services\BookConfigService;
  11. use App\Modules\User\Services\UserService;
  12. use App\Modules\Channel\Services\ChannelService;
  13. use Log;
  14. use DB;
  15. use Cookie;
  16. use Redis;
  17. use Hashids;
  18. use EasyWeChat\Foundation\Application;
  19. use EasyWeChat\Support\XML;
  20. use App\Modules\OfficialAccount\Services\ForceSubscribeService;
  21. use App\Jobs\SendTexts;
  22. use App\Jobs\SendStatisticsList;
  23. use App\Libs\SMS;
  24. use App\Modules\Activity\Services\ActivityService;
  25. use App\Modules\SendOrder\Services\SendOrderService;
  26. use GuzzleHttp\Client;
  27. class OrdersController extends Controller
  28. {
  29. /**
  30. * @apiDefine pay 支付
  31. */
  32. /**
  33. * 支付唤起入口
  34. * 功能:授权、请求支付参数、并跳转微信支付
  35. * TODO 暂时不创建订单
  36. * tail -f /var/www/ydy_wap_backend/storage/logs/laravel-2017-12-01.log
  37. * zwap/goToPay?distribution_channel_id=3&price=1&uid=3
  38. * @apiVersion 1.0.0
  39. * @apiDescription 支付
  40. * @api {get} http://pay.aizhuishu.com/goToPay 支付
  41. * @apiGroup pay
  42. * @apiName wxindex
  43. * @apiParam {Int} product_id product_id
  44. * @apiParam {Int} uid uid
  45. * @apiParam {Int} distribution_channel_id distribution_channel_id
  46. * @apiParam {String} pay_redirect_url pay_redirect_url
  47. * @apiSuccess {int} code 状态码
  48. * @apiSuccessExample {json} Success-Response:
  49. * HTTP/1.1 200 OK
  50. * {
  51. * code: 0,
  52. * msg: "",
  53. * data: {
  54. * }
  55. */
  56. function wxindex(Request $request){
  57. $product_id = $request->has('product_id')?$request->get('product_id'):'';
  58. $uid = $request->has('uid')?$request->get('uid'):'';
  59. $distribution_channel_id = $request->has('distribution_channel_id')?$request->get('distribution_channel_id'):'';
  60. $pay_redirect_url = $request->has('pay_redirect_url')?$request->get('pay_redirect_url'):'';
  61. $send_order_id = $request->has('send_order_id')?$request->get('send_order_id'):0;
  62. $activity_id = $request->has('activity_id')?$request->get('activity_id'):0;
  63. $n = $request->has('n')?$request->get('n'):0;
  64. if($send_order_id && strlen($send_order_id)>50 ){
  65. try{
  66. $send_order_id = decrypt($send_order_id);
  67. }catch (\Exception $e){
  68. $send_order_id = 0;
  69. }
  70. }
  71. if($send_order_id && strlen($send_order_id)>50){
  72. $send_order_id = 0;
  73. }
  74. //活动判断
  75. if($activity_id){
  76. $limit = $request->get('limit',0);
  77. if($limit && $limit == 1){
  78. $order = OrderService::userIsParticipateActivity($uid,$activity_id);
  79. if($order){
  80. $activity = ActivityService::getById($activity_id);
  81. if($activity){
  82. $url = env('PROTOCOL','https').'://site'.encodeDistributionChannelId($distribution_channel_id).'.'.env('CUSTOM_HOST','leyuee').'.com'.$activity->activity_page;
  83. return redirect()->to($url);
  84. }
  85. return '';
  86. }
  87. }
  88. }
  89. if(empty($product_id) || empty($uid) || empty($distribution_channel_id) || empty($pay_redirect_url)){
  90. return response()->error('WAP_PARAM_ERROR');
  91. }
  92. $openid = $request->has('openid')?$request->get('openid'):'';
  93. $bid = $request->has('bid')?$request->get('bid'):0;
  94. $hash_bid = $bid;
  95. $fromtype = $request->has('fromtype')?$request->get('fromtype'):$request->get('from');
  96. if($fromtype && strlen($fromtype)>50 ){
  97. try{
  98. $fromtype = decrypt($fromtype);
  99. }catch (\Exception $e){
  100. $fromtype = 'main';
  101. }
  102. }
  103. if($fromtype && strlen($fromtype)>50){
  104. $fromtype = 'main';
  105. }
  106. if(empty($product_id) || empty($uid) || empty($distribution_channel_id) || empty($pay_redirect_url)){
  107. return response()->error('WAP_PARAM_ERROR');
  108. }
  109. //根据分校id获取支付配置id
  110. Log::info($request->all());
  111. $channel = ChannelService::getById($distribution_channel_id);
  112. if(!$channel || !$channel->pay_merchant_id){
  113. return response()->error('WAP_PARAM_ERROR');
  114. }
  115. //获取支付类型
  116. $pay_merchant = DB::table('pay_merchants')->select('appid','source','config_info')->where('id',$channel->pay_merchant_id)->where('is_enabled',1)->first();
  117. if(!$pay_merchant || !$pay_merchant->appid || !$pay_merchant->source) return response()->error('WAP_PARAM_ERROR');
  118. //重定向 获取用户信息的次数
  119. $n++;
  120. if($n >= 5){
  121. //重定向次数过多,则授权公众号出问题
  122. $this->payAlert($channel->pay_merchant_id,'','',$n);
  123. $back_url = env('PROTOCOL') . '://site' . encodeDistributionChannelId($distribution_channel_id) . '.' . env('CUSTOM_HOST') . '.com' . '/pay';
  124. return redirect()->to($back_url);
  125. }
  126. if(empty($openid)){
  127. $trade_no = date("YmdHis").hexdec(uniqid());
  128. $params = compact('uid','product_id','distribution_channel_id','send_order_id','bid','trade_no','pay_redirect_url','fromtype','activity_id','n');
  129. $redirect_url = env('CREATE_PAY_URL').'?'.http_build_query($params);
  130. //$redirect_url = env('CREATE_PAY_URL').'?uid='.$uid.'&product_id='.$product_id.'&distribution_channel_id='
  131. // .$distribution_channel_id.'&send_order_id='.$send_order_id.'&bid='.$bid.'&pay_redirect_url='.urlencode($pay_redirect_url)
  132. $auth_url = env('AUTH_URL').'?gzh_app_id='.$pay_merchant->appid.'&redirect_url='.urlencode($redirect_url);
  133. Log::info('redirect_auth_url:'.$auth_url);
  134. header("Location:".$auth_url);
  135. exit();
  136. }
  137. $trade_no = $request->input('trade_no');
  138. $order_info = OrderService::getByTradeNo($trade_no);
  139. if($order_info) return response()->error('WAP_SYS_ERROR');
  140. $cid = $request->has('cid')?$request->get('cid'):'';
  141. $product_info = ProductService::getProductSingle($product_id);
  142. $price = $product_info->price*100;
  143. if($uid < 32){
  144. $price = 1;
  145. }
  146. if(!$send_order_id){
  147. try{
  148. $send_order_id = (int)Redis::hget('book_read:' . $uid, 'send_order_id');
  149. }catch (\Exception $e){
  150. }
  151. }
  152. if(in_array($uid,explode(',',env('TEST_UID')))){
  153. $price = 1;
  154. }
  155. if($bid){
  156. try{
  157. $bid = Hashids::decode($bid)[0];
  158. }catch (\Exception $e){
  159. $bid = 0;
  160. }
  161. }
  162. try{
  163. $key = 'leyuee:to_send_not_pay_uid:distribution_channel_id:'.$distribution_channel_id;
  164. Redis::hset($key,$uid,time());
  165. $date = date('Y-m-d');
  166. Redis::hincrby('order_stat:'.$distribution_channel_id,'order_num_'.$date,1);
  167. if($send_order_id){
  168. Redis::hincrby('order_promotion_stat:'.$send_order_id,'order_num_'.$date,1);
  169. Redis::hincrby('order_promotion_stat:'.$send_order_id,'total',1);
  170. }
  171. }catch (\Exception $e){
  172. }
  173. $data = [];
  174. $data['price'] = $price;
  175. $data['create_ip'] = $request->getClientIp();
  176. $data['openid'] = $openid;//
  177. $data['body'] = 'novel read';
  178. $official_name = $this->getSubscribeOfficialName($uid);
  179. if($official_name){
  180. $data['body'] = '搜索公众号'.$official_name.',请继续阅读';
  181. }
  182. $data['detail'] = 'novel read';
  183. $data['trade_no'] = $trade_no;
  184. $data['remark'] = json_encode(
  185. [
  186. 'uid'=>$uid,
  187. 'dcd'=>$distribution_channel_id,
  188. 'bid'=>$bid,
  189. 'cp'=>$request->getClientIp(),
  190. 'pms'=>$pay_merchant->source,
  191. 'pmi'=>$channel->pay_merchant_id,
  192. 'pd'=>$product_id,
  193. 'soi'=>$send_order_id,
  194. ]
  195. );
  196. if($product_info->type == 'YEAR_ORDER'){
  197. $order_type = 'YEAR';
  198. }elseif ($product_info->type == 'BOOK_ORDER'){
  199. $order_type = 'BOOK';
  200. }elseif ($product_info->type == 'TICKET_RECHARGE'){
  201. $order_type = 'RECHARGE';
  202. }else{
  203. $order_type = '';
  204. }
  205. /*
  206. $this->createOrderTotal([
  207. 'distribution_channel_id'=>$distribution_channel_id,
  208. 'uid'=>$uid,
  209. 'product_id'=>$product_id,
  210. 'price'=>$price/100,
  211. 'pay_type'=>1,
  212. 'trade_no'=>$data['trade_no'],
  213. 'pay_merchant_source'=>$pay_merchant->source,
  214. 'pay_merchant_id'=>$channel->pay_merchant_id,
  215. 'create_ip'=>$request->getClientIp(),
  216. 'send_order_id'=>$send_order_id,
  217. 'order_type'=>$order_type,
  218. 'from_bid'=>$bid
  219. ]);*/
  220. $send_order_name = '';
  221. if($send_order_id){
  222. $send_order_info= SendOrderService::getById($send_order_id);
  223. if($send_order_info && isset($send_order_info->name) && !empty($send_order_info->name)){
  224. $send_order_name = $send_order_info->name;
  225. }
  226. }
  227. $this->createUnPayOrder([
  228. 'distribution_channel_id'=>$distribution_channel_id,
  229. 'uid'=>$uid,
  230. 'product_id'=>$product_id,
  231. 'price'=>$price/100,
  232. 'pay_type'=>1,
  233. 'trade_no'=>$data['trade_no'],
  234. 'pay_merchant_source'=>$pay_merchant->source,
  235. 'pay_merchant_id'=>$channel->pay_merchant_id,
  236. 'create_ip'=>$request->getClientIp(),
  237. 'send_order_id'=>$send_order_id,
  238. 'send_order_name'=>$send_order_name,
  239. 'order_type'=>$order_type,
  240. 'from_bid'=>$bid,
  241. 'from_type'=>$fromtype,
  242. 'activity_id'=>$activity_id
  243. ]);
  244. Log::info($data);
  245. $config = [];
  246. if($pay_merchant->config_info){
  247. $config = json_decode($pay_merchant->config_info,true);
  248. }
  249. $wechatPay = WechatPay::instance($pay_merchant->source,$config);
  250. if(!$wechatPay) return response()->error('WAP_PARAM_ERROR');
  251. $pay_info = $wechatPay->send($data);
  252. if(!$pay_info){
  253. $pay_info = $wechatPay->send($data);
  254. }
  255. if(!isset($pay_info['appId']) || !isset($pay_info['package'])){
  256. //支付异常
  257. $this->payAlert($channel->pay_merchant_id,$trade_no,$pay_info);
  258. }
  259. $pay_info['pay_redirect_url'] = urldecode($pay_redirect_url);
  260. if($request->has('cid')){
  261. $pay_info['pay_redirect_url'] = $pay_info['pay_redirect_url'].'&cid='.$request->input('cid');
  262. }
  263. if($hash_bid){
  264. $pay_info['pay_redirect_url'] = $pay_info['pay_redirect_url'].'&bid='.$hash_bid;
  265. }
  266. $pay_url_info = parse_url($pay_redirect_url);
  267. $pay_info['pay_wait_url'] = $pay_url_info['scheme'].'://'.$pay_url_info['host'].'/pay/wait?order='.$data['trade_no'].'&redirect='.urlencode($pay_info['pay_redirect_url']);
  268. //$h5_scheme = env('H5_SCHEME','https');
  269. //$jsSdkSign = $this->jsSdkSign($pay_info,str_replace('http',$h5_scheme,url()->current()));
  270. Log::info('$pay_info is');
  271. $jsSdkSign =0;
  272. Log::info($pay_info);
  273. Log::info('jsSdkSign---- :'.$jsSdkSign);
  274. $pay_order = $trade_no;
  275. return view('pay.order.index',compact('pay_info','referer','jsSdkSign','pay_order'));
  276. }
  277. public function reportError(Request $request){
  278. $data = $request->post('data');
  279. DB::table('pay_page_error')->insert([
  280. 'msg'=>$data,
  281. 'created_at'=>date('Y-m-d H:i:s'),
  282. 'updated_at'=>date('Y-m-d H:i:s')
  283. ]);
  284. return response()->success();
  285. }
  286. private function jsSdkSign($pay_info,$url){
  287. if(!isset($pay_info['appId']) || !isset($pay_info['package'])){
  288. return 0;
  289. }
  290. $appid = $pay_info['appId'];
  291. $jsapi_ticket = Redis::hget($appid,'jsapi_ticket');
  292. //如果能获取到jsapi_ticket 则直接签名
  293. if($jsapi_ticket){
  294. $sign_arr = [
  295. 'noncestr'=>$pay_info['nonceStr'],
  296. 'jsapi_ticket'=>$jsapi_ticket,
  297. 'timestamp'=>$pay_info['timeStamp'],
  298. 'url'=>$url
  299. ];
  300. return sha1($this->arr_to_url($sign_arr));
  301. }
  302. //获取不到jsapi_ticket
  303. $app_secret_info = DB::table('official_setting')->select('secret')->first();
  304. if($app_secret_info && !empty($app_secret_info->secret)){
  305. $client = new Client(['timeout' => 5]);
  306. try{
  307. //获取access_token
  308. $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$app_secret_info->secret;
  309. $res = $client->request('get',$url)->getBody()->getContents();
  310. if(!$res){
  311. return 0;
  312. }
  313. $res = json_decode($res,1);
  314. if(!isset($res['access_token']) || empty($res['access_token'])){
  315. return 0;
  316. }
  317. Redis::hset($appid,'access_token',$res['access_token']);
  318. //获取jsapi_ticket
  319. $res = null;
  320. $url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='.$res['access_token'].'&type=jsapi';
  321. $res = $client->request('get',$url)->getBody()->getContents();
  322. if(!$res){
  323. return 0;
  324. }
  325. $res = json_decode($res,1);
  326. if(!isset($res['ticket']) || empty($res['ticket'])){
  327. return 0;
  328. }
  329. Redis::hset($appid,'jsapi_ticket',$res['ticket']);
  330. Redis::EXPIRE($appid,7000);
  331. $sign_arr = [
  332. 'noncestr'=>$pay_info['nonceStr'],
  333. 'jsapi_ticket'=>$res['ticket'],
  334. 'timestamp'=>$pay_info['timeStamp'],
  335. 'url'=>$url
  336. ];
  337. return sha1($this->arr_to_url($sign_arr));
  338. }catch (\Exception $e){
  339. return 0;
  340. }
  341. }
  342. return 0;
  343. }
  344. public function waitPage(Request $request){
  345. $order = $request->input('order');
  346. //$order = "201712081711401585932843356442";
  347. $order = (string)$order;
  348. $url = urldecode($request->input('redirect'));
  349. return view('pay.order.wait',compact('order','url'));
  350. //return view('pay.order.wait');
  351. }
  352. /**
  353. * 官方微信回调
  354. * @param Request $request
  355. * @return \Symfony\Component\HttpFoundation\Response
  356. */
  357. function wcback_official(Request $request){
  358. $xml = XML::parse(strval($request->getContent()));
  359. Log::info('xml is');
  360. Log::info($xml);
  361. if(!$xml || !is_array($xml)) return 'fail';
  362. $remarks = json_decode($xml['attach'],true);
  363. $pay_merchant_id = $remarks['pmi'];
  364. $pay_merchant = DB::table('pay_merchants')->select('appid','source','config_info')->where('id',$pay_merchant_id)->where('is_enabled',1)->first();
  365. $application = WechatPay::instance('OFFICIALPAY',json_decode($pay_merchant->config_info,true));
  366. //$app = new Application($options);
  367. $app = $application->app;
  368. $response = $app->payment->handleNotify(function($notify, $successful){
  369. if(!$successful) return 'fail';
  370. $trade_no = $notify->out_trade_no;
  371. $order = OrderService::getByTradeNo($trade_no);
  372. if(isset($order->status) && $order->status=='PAID'){
  373. Log::info('has_pay:'.$trade_no);
  374. return true;
  375. }
  376. DB::beginTransaction();
  377. try{
  378. $transaction_id = $notify->transaction_id;
  379. $remarks = json_decode($notify->attach,true);
  380. $uid = $remarks['uid'];
  381. $distribution_channel_id = $remarks['dcd'];
  382. $product_id = $remarks['pd'];
  383. $product = ProductService::getProductSingle($product_id);
  384. $pay_merchant_source = $remarks['pms'];
  385. $pay_merchant_id = $remarks['pmi'];
  386. $send_order_id = $remarks['soi'];
  387. $create_ip = $remarks['cp'];
  388. $price =$product->price;
  389. $bid = $remarks['bid'];
  390. //$this->updateOrderTotal($trade_no,$transaction_id);
  391. // 更新其他定制Order表
  392. if($product->type == 'YEAR_ORDER'){
  393. Log::info('YEAR_ORDERYEAR_ORDERYEAR_ORDERYEAR_ORDERYEAR_ORDERYEAR_ORDERYEAR_ORDERYEAR_ORDER');
  394. $order_type = 'YEAR';
  395. $this->yearOrder($uid,$distribution_channel_id,$price,$send_order_id);
  396. $order->order_type = $order_type;
  397. $order->status = 'PAID';
  398. $order->pay_end_at = date('Y-m-d H:i:s');
  399. $order->transaction_id = $transaction_id;
  400. $order->save();
  401. //$price = $price/100;
  402. /*
  403. $this->createOrder(
  404. compact(
  405. 'uid','distribution_channel_id','product_id','price','trade_no','send_order_id','order_type','pay_merchant_source',
  406. 'pay_merchant_id','create_ip','bid','transaction_id'
  407. )
  408. );*/
  409. }elseif($product->type == 'BOOK_ORDER'){
  410. Log::info('BOOK_ORDERBOOK_ORDERBOOK_ORDERBOOK_ORDERBOOK_ORDERBOOK_ORDERBOOK_ORDERBOOK_ORDER');
  411. $order_type = 'BOOK';
  412. $this->bookOrder($product_id,$uid,$send_order_id,$price,$distribution_channel_id);
  413. $order->order_type = $order_type;
  414. $order->status = 'PAID';
  415. $order->pay_end_at = date('Y-m-d H:i:s');
  416. $order->transaction_id = $transaction_id;
  417. $order->save();
  418. //$price = $price/100;
  419. /*
  420. $this->createOrder(
  421. compact(
  422. 'uid','distribution_channel_id','product_id','price','trade_no','send_order_id','order_type','pay_merchant_source',
  423. 'pay_merchant_id','create_ip','bid','transaction_id'
  424. )
  425. );*/
  426. }elseif($product->type == 'TICKET_RECHARGE'){
  427. Log::info('TICKET_RECHARGETICKET_RECHARGETICKET_RECHARGETICKET_RECHARGETICKET_RECHARGE');
  428. $order_type = 'RECHARGE';
  429. $this->userCharge($product,$uid);
  430. $order->order_type = $order_type;
  431. $order->status = 'PAID';
  432. $order->pay_end_at = date('Y-m-d H:i:s');
  433. $order->transaction_id = $transaction_id;
  434. $order->save();
  435. //$price = $price/100;
  436. /*
  437. $this->createOrder(
  438. compact(
  439. 'uid','distribution_channel_id','product_id','price','trade_no','send_order_id','order_type','pay_merchant_source',
  440. 'pay_merchant_id','create_ip','bid','transaction_id'
  441. ));*/
  442. }else{
  443. DB::rollback();
  444. return 'Order not exist.';
  445. }
  446. $this->successPayPushMsg($uid,$product);
  447. $this->orderStatistical($order);
  448. $key = 'leyuee:to_send_not_pay_uid:distribution_channel_id:'.$distribution_channel_id;
  449. Redis::hdel($key,$uid);
  450. DB::commit();
  451. return true;
  452. }catch (\Exception $e){
  453. DB::rollback();
  454. return 'fail';
  455. }
  456. });
  457. return $response;
  458. }
  459. /**
  460. * 通联支付回调
  461. * @param Request $request
  462. */
  463. function wcback_allinpay(Request $request)
  464. {
  465. Log::info('wcback_allinpay_request');
  466. try{
  467. $data = $request->all();
  468. Log::info($request->all());
  469. if(!$data['trxreserved']) return 'fail';
  470. $pay_merchant_id = json_decode($data['trxreserved'],true)['pmi'];
  471. $pay_merchant = DB::table('pay_merchants')->select('appid','source','config_info')->where('id',$pay_merchant_id)->where('is_enabled',1)->first();
  472. unset($data['_url']);
  473. if(!$pay_merchant->config_info) return 'fail';
  474. $wechatPay = WechatPay::instance('ALLINPAY',json_decode($pay_merchant->config_info,true));
  475. if($wechatPay->NotifyValidSign($data,$wechatPay->appkey)){
  476. Log::info('allinpay_notify_sign_success');
  477. /**
  478. 只有0000表示交易成功或下单成功,其他为失败
  479. 0000:交易成功
  480. 3045,3088:交易超时
  481. 3008:余额不足
  482. 3999:交易失败
  483. 2008:交易处理中
  484. 3050:交易已撤销
  485. */
  486. if($data['trxstatus'] == '0000')
  487. {
  488. // 修改表比较多,开启事务
  489. DB::beginTransaction();
  490. $trade_no = $data['cusorderid'];
  491. $transaction_id = $data['chnltrxid'];
  492. //$openid = $data['acct'];
  493. $remarks = $data['trxreserved'];
  494. // $remarks = '{"openid":"oEteU1VNvYozhXuu8TXhByPBtSl4","distribution_channel_id":2,"product_id":1,"uid":1,"price":"1","trade_no":"201711301937151585490779316114","create_ip":"::1","servicer":"AllinPay"}';
  495. $remarks = json_decode($remarks,true);
  496. Log::info('$remarks');
  497. Log::info($remarks);
  498. // 更新Order
  499. $order = OrderService::getByTradeNo($trade_no);
  500. // 防止重复推送
  501. if(isset($order->status) && $order->status=='PAID'){
  502. Log::info('has_pay:'.$trade_no);
  503. echo 'success';
  504. exit();
  505. }
  506. $uid = $remarks['uid'];
  507. $distribution_channel_id = $remarks['dcd'];
  508. $product_id = $remarks['pd'];
  509. $product = ProductService::getProductSingle($product_id);
  510. $pay_merchant_source = $remarks['pms'];
  511. $pay_merchant_id = $remarks['pmi'];
  512. $send_order_id = $remarks['soi'];
  513. $create_ip = $remarks['cp'];
  514. $price =$product->price;
  515. $bid = $remarks['bid'];
  516. Log::info('save_order_end');
  517. //$this->updateOrderTotal($trade_no,$transaction_id);
  518. Log::info($product);
  519. Log::info('product_type:'.$product->type);
  520. // 更新其他定制Order表
  521. if($product->type == 'YEAR_ORDER'){
  522. Log::info('YEAR_ORDERYEAR_ORDERYEAR_ORDERYEAR_ORDERYEAR_ORDERYEAR_ORDERYEAR_ORDERYEAR_ORDER');
  523. $order_type = 'YEAR';
  524. $this->yearOrder($uid,$distribution_channel_id,$price,$send_order_id);
  525. $order->order_type = $order_type;
  526. $order->status = 'PAID';
  527. $order->pay_end_at = date('Y-m-d H:i:s');
  528. $order->transaction_id = $transaction_id;
  529. $order->save();
  530. //$price = $price/100;
  531. /*
  532. $this->createOrder(
  533. compact(
  534. 'uid','distribution_channel_id','product_id','price','trade_no','send_order_id','order_type','pay_merchant_source',
  535. 'pay_merchant_id','create_ip','bid','transaction_id'
  536. )
  537. );*/
  538. }elseif($product->type == 'BOOK_ORDER'){
  539. Log::info('BOOK_ORDERBOOK_ORDERBOOK_ORDERBOOK_ORDERBOOK_ORDERBOOK_ORDERBOOK_ORDERBOOK_ORDER');
  540. $order_type = 'BOOK';
  541. $this->bookOrder($product_id,$uid,$send_order_id,$price,$distribution_channel_id);
  542. $order->order_type = $order_type;
  543. $order->status = 'PAID';
  544. $order->pay_end_at = date('Y-m-d H:i:s');
  545. $order->transaction_id = $transaction_id;
  546. $order->save();
  547. //$price = $price/100;
  548. /*
  549. $this->createOrder(
  550. compact(
  551. 'uid','distribution_channel_id','product_id','price','trade_no','send_order_id','order_type','pay_merchant_source',
  552. 'pay_merchant_id','create_ip','bid','transaction_id'
  553. )
  554. );*/
  555. }elseif($product->type == 'TICKET_RECHARGE'){
  556. Log::info('TICKET_RECHARGETICKET_RECHARGETICKET_RECHARGETICKET_RECHARGETICKET_RECHARGE');
  557. $order_type = 'RECHARGE';
  558. $this->userCharge($product,$uid);
  559. $order->order_type = $order_type;
  560. $order->status = 'PAID';
  561. $order->pay_end_at = date('Y-m-d H:i:s');
  562. $order->transaction_id = $transaction_id;
  563. $order->save();
  564. //$price = $price/100;
  565. /*
  566. $this->createOrder(
  567. compact(
  568. 'uid','distribution_channel_id','product_id','price','trade_no','send_order_id','order_type','pay_merchant_source',
  569. 'pay_merchant_id','create_ip','bid','transaction_id'
  570. ));*/
  571. }
  572. $this->successPayPushMsg($uid,$product);
  573. $this->orderStatistical($order);
  574. DB::commit();
  575. //redis 删除未支付的uid
  576. try{
  577. $key = 'leyuee:to_send_not_pay_uid:distribution_channel_id:'.$distribution_channel_id;
  578. Redis::hdel($key,$uid);
  579. //Redis::srem($key,$uid);
  580. }catch (\Exception $e){
  581. Log::info('redis remote error-----------------------');
  582. Log::info($e);
  583. }
  584. }
  585. }else{
  586. Log::info('allinpay_notify_sign_fail');
  587. }
  588. }
  589. catch(\Exception $e){
  590. var_dump($e->getMessage());
  591. DB::rollBack();
  592. Log::info('receive_allinpay_ept:'.$e->getMessage());
  593. }
  594. Log::info('pay_callback_end');
  595. echo "success";
  596. }
  597. public function wcback_lianlianpay(Request $request){
  598. $data = $request->getContent();
  599. Log::info('wcback_lianlianpay call back enter');
  600. Log::info($request->getContent());
  601. $data = json_decode($data,true);
  602. if($data['result_pay'] == 'SUCCESS'){
  603. $trade_no = $data['no_order'];
  604. $order = OrderService::getByTradeNo($trade_no);
  605. if(!$order) return response()->json(['ret_code'=>'-1']);
  606. $pay_merchant_id = $order->pay_merchant_id;
  607. $pay_merchant = DB::table('pay_merchants')->select('appid','source','config_info')->where('id',$pay_merchant_id)->where('is_enabled',1)->first();
  608. unset($data['_url']);
  609. if(!$pay_merchant->config_info) response()->json(['ret_code'=>'-1']);
  610. $wechatPay = WechatPay::instance('LIANLIANPAY',json_decode($pay_merchant->config_info,true));
  611. $uid = $order->uid;
  612. $distribution_channel_id = $order->distribution_channel_id;
  613. $price = $order->price;
  614. $send_order_id = $order->send_order_id;
  615. $product_id = $order->product_id;
  616. if(!$wechatPay->rsaCheck($data)){
  617. Log::info('sign check error');
  618. //return response()->json(['ret_code'=>'-1']);
  619. }
  620. // 防止重复推送
  621. if(isset($order->status) && $order->status=='PAID'){
  622. Log::info('has_pay:'.$trade_no);
  623. return response()->json(['ret_code'=>'0000','ret_msg'=>'交易成功']);
  624. }
  625. DB::beginTransaction();
  626. try {
  627. $product = ProductService::getProductSingle($order->product_id);
  628. $transaction_id = $data['oid_paybill'];
  629. // 更新其他定制Order表
  630. if($product->type == 'YEAR_ORDER'){
  631. Log::info('YEAR_ORDERYEAR_ORDERYEAR_ORDERYEAR_ORDERYEAR_ORDERYEAR_ORDERYEAR_ORDERYEAR_ORDER');
  632. $order_type = 'YEAR';
  633. $this->yearOrder($uid,$distribution_channel_id,$price,$send_order_id);
  634. $order->order_type = $order_type;
  635. $order->status = 'PAID';
  636. $order->pay_end_at = date('Y-m-d H:i:s');
  637. $order->transaction_id = $transaction_id;
  638. $order->save();
  639. }elseif($product->type == 'BOOK_ORDER'){
  640. Log::info('BOOK_ORDERBOOK_ORDERBOOK_ORDERBOOK_ORDERBOOK_ORDERBOOK_ORDERBOOK_ORDERBOOK_ORDER');
  641. $order_type = 'BOOK';
  642. $this->bookOrder($product_id,$uid,$send_order_id,$price,$distribution_channel_id);
  643. $order->order_type = $order_type;
  644. $order->status = 'PAID';
  645. $order->pay_end_at = date('Y-m-d H:i:s');
  646. $order->transaction_id = $transaction_id;
  647. $order->save();
  648. }elseif($product->type == 'TICKET_RECHARGE'){
  649. Log::info('TICKET_RECHARGETICKET_RECHARGETICKET_RECHARGETICKET_RECHARGETICKET_RECHARGE');
  650. $order_type = 'RECHARGE';
  651. $this->userCharge($product,$uid);
  652. $order->order_type = $order_type;
  653. $order->status = 'PAID';
  654. $order->pay_end_at = date('Y-m-d H:i:s');
  655. $order->transaction_id = $transaction_id;
  656. $order->save();
  657. }
  658. $this->successPayPushMsg($uid,$product);
  659. $this->orderStatistical($order);
  660. DB::commit();
  661. //redis 删除未支付的uid
  662. $key = 'leyuee:to_send_not_pay_uid:distribution_channel_id'.$distribution_channel_id;
  663. Redis::hdel($key,$uid);
  664. return response()->json(['ret_code'=>'0000','ret_msg'=>'交易成功']);
  665. } catch (\Exception $e) {
  666. DB::rollBack();
  667. Log::info('lianlian:'.$e->getMessage());
  668. }
  669. }
  670. return response()->json(['ret_code'=>'-1']);
  671. }
  672. /**
  673. * 微众支付回调
  674. * @param Request $request
  675. */
  676. function wcback_palmpay(Request $request)
  677. {
  678. Log::info('wcback_palmpay_request');
  679. try{
  680. $data = $request->except('_url');
  681. Log::info($request->all());
  682. //订单
  683. $trade_no = $data['outTradeNo'];
  684. $order = OrderService::getByTradeNo($trade_no);
  685. if(!$order) die('failed');
  686. // 防止重复推送
  687. if(isset($order->status) && $order->status=='PAID'){
  688. Log::info('has_pay:'.$trade_no);
  689. echo 'success';
  690. exit();
  691. }
  692. $pay_merchant = DB::table('pay_merchants')->select('appid','source','config_info')->where('id',$order->pay_merchant_id)->where('is_enabled',1)->first();
  693. //校验签名
  694. $sign = _sign($data,json_decode($pay_merchant->config_info,1)['appKey']);
  695. if($sign != $data['sign']) die('failed');
  696. $transaction_id = $data['chorderid'];
  697. if($data['status'] == 'success'){
  698. Log::info('wcback_palmpay_notify_sign_success');
  699. if($data['status'] == 'success')
  700. {
  701. // 修改表比较多,开启事务
  702. DB::beginTransaction();
  703. // 更新Order
  704. $order = OrderService::getByTradeNo($trade_no);
  705. $uid = $order->uid;
  706. $distribution_channel_id = $order->distribution_channel_id;
  707. $product_id = $order->product_id;
  708. $product = ProductService::getProductSingle($product_id);
  709. $send_order_id = $order->send_order_id;
  710. $price =$product->price;
  711. Log::info('save_order_end');
  712. Log::info($product);
  713. Log::info('product_type:'.$product->type);
  714. // 更新其他定制Order表
  715. if($product->type == 'YEAR_ORDER'){
  716. Log::info('YEAR_ORDERYEAR_ORDERYEAR_ORDERYEAR_ORDERYEAR_ORDERYEAR_ORDERYEAR_ORDERYEAR_ORDER');
  717. $order_type = 'YEAR';
  718. $this->yearOrder($uid,$distribution_channel_id,$price,$send_order_id);
  719. $order->order_type = $order_type;
  720. $order->status = 'PAID';
  721. $order->pay_end_at = date('Y-m-d H:i:s');
  722. $order->transaction_id = $transaction_id;
  723. $order->save();
  724. }elseif($product->type == 'BOOK_ORDER'){
  725. Log::info('BOOK_ORDERBOOK_ORDERBOOK_ORDERBOOK_ORDERBOOK_ORDERBOOK_ORDERBOOK_ORDERBOOK_ORDER');
  726. $order_type = 'BOOK';
  727. $this->bookOrder($product_id,$uid,$send_order_id,$price,$distribution_channel_id);
  728. $order->order_type = $order_type;
  729. $order->status = 'PAID';
  730. $order->pay_end_at = date('Y-m-d H:i:s');
  731. $order->transaction_id = $transaction_id;
  732. $order->save();
  733. }elseif($product->type == 'TICKET_RECHARGE'){
  734. Log::info('TICKET_RECHARGETICKET_RECHARGETICKET_RECHARGETICKET_RECHARGETICKET_RECHARGE');
  735. $order_type = 'RECHARGE';
  736. $this->userCharge($product,$uid);
  737. $order->order_type = $order_type;
  738. $order->status = 'PAID';
  739. $order->pay_end_at = date('Y-m-d H:i:s');
  740. $order->transaction_id = $transaction_id;
  741. $order->save();
  742. }
  743. $this->successPayPushMsg($uid,$product);
  744. $this->orderStatistical($order);
  745. DB::commit();
  746. //redis 删除未支付的uid
  747. try{
  748. $key = 'leyuee:to_send_not_pay_uid:distribution_channel_id:'.$distribution_channel_id;
  749. Redis::hdel($key,$uid);
  750. }catch (\Exception $e){
  751. Log::info('redis remote error-----------------------');
  752. Log::info($e);
  753. }
  754. }
  755. }else{
  756. Log::info('wcback_palmpay_notify_sign_fail');
  757. }
  758. }
  759. catch(\Exception $e){
  760. var_dump($e->getMessage());
  761. DB::rollBack();
  762. Log::info('receive_wcback_palmpay_ept:'.$e->getMessage());
  763. }
  764. Log::info('pay_callback_end');
  765. echo "success";
  766. }
  767. /**
  768. * 公众号签名@华灯初上
  769. * @param $params
  770. * @return string
  771. */
  772. protected function getSign($params,$key)
  773. {
  774. $url = $this->arr_to_url($params, false);
  775. $url = $url . '&key=' . $key;
  776. $sign = md5($url);
  777. return $sign;
  778. }
  779. /**
  780. * 公众号签名@华灯初上
  781. * @param $array
  782. * @param bool $has_sign
  783. * @return string
  784. */
  785. protected function arr_to_url($array, $has_sign = false)
  786. {
  787. ksort($array);
  788. reset($array);
  789. $arg = "";
  790. while (list ($name, $val) = each($array)) {
  791. if ($name == 'sign' && !$has_sign) continue;
  792. if (strpos($name, "_") === 0)
  793. continue;
  794. if (is_array($val))
  795. $val = join(',', $val);
  796. if ($val === "")
  797. continue;
  798. $arg .= $name . "=" . $val . "&";
  799. }
  800. $arg = substr($arg, 0, count($arg) - 2);
  801. return $arg;
  802. }
  803. /**
  804. * 单本充值会掉
  805. * @param $product_id
  806. * @param $uid
  807. * @param $send_order_id
  808. * @param $fee
  809. */
  810. protected function bookOrder($product_id,$uid,$send_order_id,$fee,$distribution_channel_id){
  811. $book_conf = BookConfigService::getBookByProduct($product_id);
  812. $insert_data['bid'] = isset($book_conf->bid)?$book_conf->bid:'';
  813. $insert_data['book_name'] = isset($book_conf->book_name)?$book_conf->book_name:'';
  814. $insert_data['uid'] = $uid;
  815. $insert_data['distribution_channel_id'] = $distribution_channel_id;
  816. $insert_data['fee'] = $fee;
  817. $insert_data['send_order_id'] = $send_order_id;
  818. $insert_data['charge_balance'] = 0;
  819. $insert_data['reward_balance'] = 0;
  820. Log::info('start_save_book_order');
  821. Log::info($insert_data);
  822. return BookOrderService::save_book_order($insert_data);
  823. }
  824. /**
  825. * 包年
  826. * @param $uid
  827. * @param $distribution_channel_id
  828. * @param $fee
  829. * @param $send_order_id
  830. * @return mixed
  831. */
  832. protected function yearOrder($uid,$distribution_channel_id,$fee,$send_order_id){
  833. Log::info('start_save_year_order');
  834. $insert_data['uid'] = $uid;
  835. $insert_data['distribution_channel_id'] = $distribution_channel_id;
  836. $insert_data['fee'] = $fee;
  837. $insert_data['send_order_id'] = $send_order_id;
  838. Log::info($insert_data);
  839. return YearOrderService::save_year_order($insert_data);
  840. }
  841. /**
  842. * 用户充值
  843. * @param $product
  844. * @param $uid\
  845. */
  846. protected function userCharge($product,$uid){
  847. $total = $product->price*100+$product->given;
  848. UserService::addBalance($uid,$total, $product->price*100,$product->given);
  849. Log::info('update_user_balance_end:'.$uid.' balance_add:'.$total);
  850. }
  851. /**
  852. * 添加订单
  853. * @param array $data
  854. * @return mixed
  855. */
  856. protected function createOrder(array $data){
  857. $insert_data = array();
  858. $insert_data['uid'] = $data['uid'];
  859. $insert_data['distribution_channel_id'] = $data['distribution_channel_id'];
  860. $insert_data['product_id'] = $data['product_id'];
  861. $insert_data['price'] = $data['price'];
  862. $insert_data['status'] = 'PAID';
  863. $insert_data['pay_type'] = 1;
  864. $insert_data['trade_no'] = $data['trade_no'];
  865. $insert_data['send_order_id'] = $data['send_order_id'];
  866. $insert_data['order_type'] = $data['order_type'];
  867. $insert_data['pay_merchant_source'] = $data['pay_merchant_source'];
  868. $insert_data['pay_merchant_id'] = $data['pay_merchant_id'];
  869. $insert_data['transaction_id'] = $data['transaction_id'];
  870. $insert_data['pay_end_at'] = date('Y-m-d H:i:s');
  871. $insert_data['create_ip'] =$data['create_ip'];
  872. $insert_data['from_bid'] =$data['bid'];
  873. Log::info('createOrder');
  874. Log::info($insert_data);
  875. return OrderService::save_order($insert_data);
  876. }
  877. /**
  878. * 添加位置付订单
  879. * @param $data
  880. * @return mixed
  881. */
  882. protected function createUnPayOrder($data){
  883. $data['status'] = 'UNPAID';
  884. $data['transaction_id'] = '';
  885. $data['pay_end_at'] = '0000-00-00 00:00:00';
  886. return OrderService::save_order($data);
  887. }
  888. /**
  889. * order total
  890. * @param $data
  891. *
  892. */
  893. protected function createOrderTotal($data){
  894. $data['status'] = 'UNPAID';
  895. $data['created_at'] = date('Y-m-d H:i:s');
  896. $data['updated_at'] = date('Y-m-d H:i:s');
  897. DB::table('orders_total')->insert($data);
  898. }
  899. protected function updateOrderTotal($trade_no,$transaction_id){
  900. $data['status'] = 'PAID';
  901. $data['transaction_id'] = $transaction_id;
  902. $data['pay_end_at'] = date('Y-m-d H:i:s');
  903. //DB::table('orders_total')->where('trade_no',$trade_no)->update($data);
  904. }
  905. protected function successPayPushMsg($uid,$product_info){
  906. try {
  907. $force_sub_info = $this->getSubscribe($uid);
  908. $data = UserService::getById($uid);
  909. if(!in_array($data->distribution_channel_id,[5,123])){
  910. //return false;
  911. }
  912. if($force_sub_info){
  913. $content_format = "您好,你已经成功充值\r\n\r\n会员:%s\r\n会员ID:%s\r\n充值金额:%s\r\n充值状态:充值成功\r\n如有疑问,请点击用户中心-联系客服\r\n\r\n><a href='%s'>点击继续阅读上次阅读</a>";
  914. if($product_info->type == 'YEAR_ORDER'){
  915. $money_text = $product_info->price.'元(尊贵的年费VIP会员)';
  916. }elseif ($product_info->type == 'TICKET_RECHARGE'){
  917. if($product_info->given){
  918. $money_text = $product_info->price.'元('.($product_info->price*100).'书币+赠送'.$product_info->given.'书币)';
  919. }else{
  920. $money_text = $product_info->price.'元('.($product_info->price*100).'书币)';
  921. }
  922. }else {
  923. $money_text = '未知';
  924. }
  925. $delay = 0;
  926. $url = env('PROTOCOL').'://site'.encodeDistributionChannelId($data->distribution_channel_id).'.'.env('CUSTOM_HOST').'.com/continue';;
  927. $content = sprintf($content_format,$data->nickname?$data->nickname:'匿名',$uid,$money_text,$url);
  928. $res['openid'] = $force_sub_info->openid;
  929. $res['appid'] = $force_sub_info->appid;
  930. $res['content'] = $content;
  931. $res['type'] = 'one_task';
  932. $res['send_time'] = date("Y-m-d H:i:s");
  933. $res['task_id'] = md5('pay_success_push');
  934. $send_data=array(
  935. 'send_time'=>date("Y-m-d H:i:s"),
  936. 'data' => $res
  937. );
  938. dispatch((new SendTexts($send_data))->onConnection('rabbitmq')->delay($delay)->onQueue('send_texts_list'));
  939. }
  940. } catch (\Exception $e) {
  941. }
  942. return true;
  943. }
  944. private function orderStatistical($order){
  945. try{
  946. $send_data=array(
  947. 'type'=>'order_info',
  948. 'data' => $order->toArray()
  949. );
  950. $send = new SendStatisticsList($send_data);
  951. $job = ($send)->onConnection('rabbitmq')->delay(0)->onQueue('send_statistics_list');
  952. dispatch($job);
  953. }catch (\Exception $e){
  954. Log::info($e);
  955. }
  956. }
  957. private function getSubscribe($uid){
  958. return ForceSubscribeService::forceSubscribeUsersByUid(['uid'=>$uid]);
  959. }
  960. public function getSubscribeOfficialName($uid){
  961. $subscribe = $this->getSubscribe($uid);
  962. if($subscribe && isset($subscribe->appid)){
  963. $official = DB::table('official_accounts')->where('appid',$subscribe->appid)->select('nickname')->first();
  964. if($official && isset($official->nickname)){
  965. return $official->nickname;
  966. }
  967. }
  968. return '';
  969. }
  970. private function payAlert($pay_merchant_id,$trade_no='',$pay_info='',$n=0){
  971. $change_pay_id = 9;
  972. if($pay_merchant_id == 9){
  973. $change_pay_id = 12;
  974. }
  975. try{
  976. $time = (int)date('H');
  977. $change = false;
  978. if($time <= 8 || $time>=23){
  979. if($pay_info){
  980. DB::table('distribution_channels')->where('pay_merchant_id',$pay_merchant_id)->update(['pay_merchant_id'=>$change_pay_id]);
  981. $change = true;
  982. }
  983. }
  984. $phone_arr = ['15868100210','18072713392','15088790066','13858057394','18668029091','18668420256'];
  985. //$phone_arr = ['18668029091'];
  986. if($n){
  987. $content = '支付通道:'.$pay_merchant_id.',获取授权信息失败';
  988. }else{
  989. $content = '支付通道:'.$pay_merchant_id.',订单号为'.$trade_no.'支付异常,异常信息:'.json_encode($pay_info);
  990. }
  991. if($change){
  992. $content .= ',已经切换到支付通道:'.$change_pay_id;
  993. }
  994. foreach ($phone_arr as $phone){
  995. SMS::send($phone,$content);
  996. }
  997. file_put_contents(date('Y-m-d').'.txt',json_encode($pay_info),FILE_APPEND);
  998. }catch (\Exception $e){
  999. }
  1000. }
  1001. }