123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353 |
- <?php
- namespace App\Http\Controllers;
- use App\Events\RetailOutboundEvent;
- use App\Events\NewOrder;
- use App\Models\Amount;
- use App\Models\Integral;
- use App\Models\IntegralW;
- use App\Models\InventoryW;
- use App\Models\LogW;
- use App\Models\OrderW;
- use App\Models\UserZ;
- use App\Models\VipLog;
- use App\Models\Address;
- use App\Models\DwbsUser;
- use App\Models\Goods;
- use App\Models\GoodSku;
- use App\Models\Order;
- use App\Models\OrderDetail;
- use App\Models\Store;
- use App\Models\User;
- use App\Models\ZbsBasic;
- use App\Models\ZbsEnroll;
- use App\Models\ZbsOrder;
- use Carbon\Carbon;
- use EasyWeChat\Factory;
- use Illuminate\Http\Request;
- use Illuminate\Support\Facades\Auth;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\Log;
- class PaymentController extends Controller
- {
- protected $option = [];
- protected $header = array();
- protected $retryTimes;
- public function pay(Request $request)
- {
- $order_no=$request->input('order_no');
- try{
- DB::transaction(function()use($order_no, &$order ,&$seconds){
- $order=Order::where('order_no',$order_no)->lockForUpdate()->first();
- $seconds=Carbon::now()->subSeconds(60)->toDateTimeString();//限制调起支付60秒
- if(empty($order)){
- throw new \Exception("订单有误");
- }
- if($order->prepare_pay_at >= $seconds){
- throw new \Exception("订单正在支付中");
- }
- $order->prepare_pay_at=Carbon::now();
- $order->save();
- });
- }catch(\Exception $e){
- return $this->error('450001',$e->getMessage());
- }
- if($order->apply_cancel == 2){
- return $this->error('450001','订单已取消');
- }
- if($order->is_pay != 0 || $order->status != 0){
- return $this->error('450001','订单状态有误');
- }
- if($order->account <= 0){
- return $this->error('450001','支付金额有误');
- }
- $openid=User::where('id',Auth::user()->id)->value('openId');
- $store=Store::where('id',$order->store_id)->first();
- if(empty($store)){
- return $this->error('450001','代理店铺信息不存在或者已被删除');
- }
- if($store->status==1){
- return $this->error('450001','代理店铺已被禁用');
- }
- $agent=DwbsUser::where('id',$store->user_id)->first();
- if(empty($agent)){
- return $this->error('450001','代理信息不存在或者已被删除');
- }
- if($agent->status==1){
- return $this->error('450001','代理已被禁用');
- }
- $options = $this->options($order->store_id);
- $payment = Factory::payment($options);
- $jssdk = $payment->jssdk;
- Log::info(round($order->account/1000,2));
- Log::info(round($order->account/10));
- $two_minutes=Carbon::now()->addSeconds(55)->toDateTimeString();//限制支付时间55秒
- $cancel_time=Carbon::parse($order->created_at)->addMinutes(59)->toDateTimeString();//系统自动取消时间前一分钟
- if(Carbon::now() >= $cancel_time){
- return $this->error('450001','订单将被取消');
- }
- if($two_minutes <= $cancel_time){
- $expire=date("YmdHis",strtotime($two_minutes));
- }else{
- $expire=date("YmdHis",strtotime($cancel_time));
- }
- Log::info('qaqaqaqaqa'.$expire);
- $attributes = [
- 'time_expire' => $expire,
- 'trade_type' => 'JSAPI', // 支付方式
- 'body' => '订单支付', // 订单说明
- 'out_trade_no' => mt_rand('1000','9999').'_'.$order_no, // 自定义订单号
- 'total_fee' => $order->account*100, // 单位:分
- 'openid' => $openid, // 当前用户的openId
- 'profit_sharing' => 'Y'
- ];
- $result = $payment->order->unify($attributes);
- if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
- $prepayId = $result['prepay_id'];
- $config = $jssdk->sdkConfig($prepayId);
- return response()->json([
- 'error_code'=>200,
- 'msg'=>'成功',
- 'data'=>$config
- ]);
- }
- Log::info($result);
- if ($result['return_code'] == 'FAIL' && array_key_exists('return_msg', $result)) {
- Log::info('订单支付失败:'.$order->user_id.'/'.$order_no.'/'.$order->money.'/'.$result['return_msg']);
- return response()->json([
- 'error_code'=>401,
- 'msg'=> $result['return_msg'],
- ]);
- }
- Log::info('订单支付失败:'.$order->user_id.'/'.$order_no.'/'.$order->money.'/'.$result['err_code_des']);
- return response()->json([
- 'error_code'=>401,
- 'msg'=> $result['err_code_des'],
- ]);
- }
- protected function options($id){
- return [
- 'app_id' => config('wechat.payment.default.app_id'),
- 'mch_id' => config('wechat.payment.default.mch_id'),
- 'sub_mch_id' => Store::where('id',$id)->value('sub_mchid'),
- 'key' => config('wechat.payment.default.key'),
- 'notify_url' => url('api/payment/notify')
- ];
- }
- public function notify(Request $request)
- {
- Log::info('支付回调成功');
- $options = [
- 'app_id' => config('wechat.payment.default.app_id'),
- 'mch_id' => config('wechat.payment.default.mch_id'),
- 'key' => config('wechat.payment.default.key'),
- 'notify_url' => url('api/payment/notify')
- ];
- $payment = Factory::payment($options);
- $response = $payment->handlePaidNotify(function ($message, $fail)
- {
- Log::info('支付返回数据:'.json_encode($message));
- LogW::create([
- 'content'=>json_encode($message),
- 'type'=>1
- ]);
- // 根据返回的订单号查询订单数据
- Log::info($message['out_trade_no']);
- $rand_no=explode('_',$message['out_trade_no'])[0];
- $message['out_trade_no']=explode('_',$message['out_trade_no'])[1];
- Log::info($message['out_trade_no']);
- $order=Order::where('order_no',$message['out_trade_no'])->first();
- if($order->is_pay==1){
- Log::info('订单号为:'.$message['out_trade_no'].'的订单已支付');
- return true;
- }
- if (!$order || $order->status == 1) {
- Log::info('订单不存在,订单号:'.$message['out_trade_no'].'/支付单号:'.$message['transaction_id'].'/支付状态:'.$message['result_code']);
- return true;//订单不存在 或者 订单已支付
- }
- if ($message['result_code'] === 'FAIL') { //支付失败
- Log::warning('支付失败');
- return true;
- }
- if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态,不代表支付状态
- Log::info('支付成功,微信支付单号:'.$message['transaction_id']);
- // 支付成功后的业务逻辑
- if($message['result_code'] === 'SUCCESS') {
- $total_fee=$message['total_fee']/100;
- DB::transaction(function()use($order,$message,$total_fee,$rand_no){
- $basic=ZbsBasic::whereIn('keys',['round_start_time','round_end_time','season'])->pluck('value','keys')->toArray();
- $start_time=$basic['round_start_time'];
- $end_time=$basic['round_end_time'];
- $season=$basic['season'];
- Log::info('0000000-00000'.$start_time.'///'.$end_time.'///'.$season);
- $sto=Store::where('id',$order->store_id)->first();
- // $userz = UserZ::where('dwbs_id', $sto->user_id)->first();
- $userzs = UserZ::where('dwbs_id', $sto->user_id)->get();
- $order->is_zbs = 0;
- $integral=$order->total*2;
- $zbs=0; //不在争霸赛期间
- // if(!empty($userz)) { //争霸赛存在该用户
- if(count($userzs) > 0) { //争霸赛存在该用户
- $now = Carbon::now()->timestamp;
- $pay_time=Carbon::parse($message['time_end'])->timestamp;
- Log::info('<<<<<1>>>>>'.$now.'///'.$start_time.'///'.$end_time.'///'.$pay_time);
- if ($pay_time >= $start_time && $pay_time <= $end_time) { //在争霸赛期间
- // $uids = ZbsEnroll::where('season',$season)->where('is_refund',0)->where('status',0)->pluck('uid')->toArray();
- $uids = \Illuminate\Support\Facades\Cache::remember('uids', Carbon::now()->addHours(12), function () use ($season) {
- return ZbsEnroll::where('season', $season)->where('is_refund', 0)->where('status', 0)->pluck('uid')->toArray();
- });
- foreach($userzs as $key=>$val){
- if (in_array($val->id, $uids)) {//报名了争霸赛
- //标记争霸赛订单
- $order->is_zbs = 1;
- //学分变更
- $integral=0;
- $zbs=1; //在争霸赛期间
- }
- }
- // if (in_array($userz->id, $uids)) {//报名了争霸赛
- // //标记争霸赛订单
- // $order->is_zbs = 1;
- // //学分变更
- // $integral=0;
- // $zbs=1; //在争霸赛期间
- // }
- }
- }
- //学分变更
- $inte=Integral::where('order_no',$order->order_no)->where('store_id',$order->store_id)->where('type',1)->first();
- if(empty($inte)){
- Integral::create([
- 'store_id'=>$order->store_id,
- 'order_no'=>$order->order_no,
- 'num'=>$order->total,
- 'integral'=>$integral,
- 'integral_double'=>$integral,
- 'type'=>1,
- 'remark'=>'下单成功',
- 'is_zbs'=>$zbs,
- ]);
- }
- //修改订单状态
- $order->status = 1;
- $order->is_pay = 1;
- $order->pay_type = 1;
- $order->pay_money = $total_fee;
- $order->rand_no = $rand_no;
- $order->pay_open_id = $message['openid'];
- $order->self_pay = 0;
- $order->wechat_pay_no = $message['transaction_id'];
- $order->pay_at = $message['time_end'];
- $order->save();
- //店铺信息
- $store=Store::where('id',$order->store_id)->lockForUpdate()->first();
- $start_money= $store->pending_amount;
- $store->pending_amount = $store->pending_amount += $total_fee;
- $store->integral += $integral;
- $store->cycle_inte += $integral;
- $store->save();
- //规格销量
- $details=OrderDetail::where('order_no',$order->order_no)->get();
- foreach($details as $key=>$val){
- $where=[];
- $where['goods_id']=$val->goods_id;
- $where['size']=$val->size;
- $where['type']=$val->type;
- //规格销量
- $sku=GoodSku::where($where)->lockForUpdate()->first();
- $sku->sale_num += $val->num;
- $sku->save();
- //商品销量
- $goods=Goods::where('id',$val->goods_id)->lockForUpdate()->first();
- $goods->sale_num += $val->num;
- $goods->save();
- //减微店代理库存
- $arr_test=Store::getTest();
- if(in_array($order->store_id,$arr_test)){
- $storeInventory=Inventory::where(['store_id'=>$order->store_id,'goods_id'=>$val->goods_id,'sku_id'=>$val->sku_id])->lockForUpdate()->first();
- $storeInve_num=!empty($storeInventory)?$storeInventory->num:0;
- if($val->num > $storeInve_num){
- Log::info('【'.$store->name.'的店铺-'.$goods->main_attr.'-'.$val->type.'-'.$val->size.'】库存不足');
- }
- $storeInventory->num-=$val->num;
- $storeInventory->save();
- }
- }
- //用户vip变更
- $vipLog=VipLog::where('user_id',$order->user_id)
- ->where('store_id',$order->store_id)->first();
- if(empty($vipLog) && $order->total>=2){
- VipLog::create([
- 'user_id'=>$order->user_id,
- 'store_id'=>$order->store_id,
- 'order_no'=>$message['out_trade_no'],
- 'type'=>2,//购买两套,添加vip
- 'remark'=>'购买自动添加vip'
- ]);
- Order::where('order_no',$message['out_trade_no'])->update([
- 'vip'=>1
- ]);
- }
- //支付日志
- Amount::create([
- 'user_id' => $order->user_id,
- 'store_id' => $order->store_id,
- 'order_no' => $message['out_trade_no'],
- 'transaction_id'=> $message['transaction_id'],
- 'money' => $total_fee,
- 'type' => 1, //支付
- 'status' => 1, //成功
- 'service_fee' => 0,
- 'start_money' => $start_money,//支付前冻结金额
- 'end_money' => $store->pending_amount,//支付后冻结金额
- 'start_amount' => $store->available_amount,//支付前可用金额
- 'end_amount' => $store->available_amount,//支付后可用金额
- 'remark' => '收款',
- ]);
- });
- //减库存
- DB::connection('mysql_dwbs')->transaction(function()use($order) {
- event(new RetailOutboundEvent($order->order_no));
- },5);
- //算争霸赛学分
- ZbsOrder::create([
- 'order_id'=>$order->id,
- 'status'=>0,
- 'is_cancel'=>0,
- ]);
- //新订单通知
- $store=Store::where('id',$order->store_id)->first();
- $user=DwbsUser::withTrashed()->where('id',$store->user_id)->first();
- if($user->openid){
- Log::info($user->openid);
- $data['openid']=$user->openid;
- $data['data']=[
- 'first' => '您有新的客户订单,请及时处理',
- 'keyword1' => User::where('id',$order->user_id)->value('nickname'),
- 'keyword2' => number_format($order->account, 2),
- 'keyword3' => $order->order_no,
- 'keyword4' => $order->created_at
- ];
- event(new NewOrder($data));
- }
- }
- Log::info('支付结束');
- return true;
- }else{
- Log::info('通信失败');
- return $fail('通信失败,请稍后再通知我');
- }
- });
- return $response;
- }
- }
|