pay_type, $payTypes)){ return true; } return false; } public function is_b2b() { $payTypes = [ Order::PAY_TYPE_WX_B2B, ]; if(in_array($this->pay_type, $payTypes)){ return true; } return false; } /** * 商城充值回调 */ public function StoreReOrderNotify($res) { $order = StoreReOrder::findOne([ 'order_no' => $res['out_trade_no'], ]); if (!$order) { return; } $order->is_pay = 1; $order->pay_time = time(); if ($order->save()) { $time = strtotime('+1 year'); $store = Store::findOne($order->store_id); if($order->store_price_id){ $store_price = \app\models\StorePrice::findOne($order->store_price_id); $itime = $store->end_time > time() ? $store->end_time : time(); $time = $itime + 86400 * $store_price->days; } $store->end_time = $time; $store->save(); //分佣逻辑(代理分润比例)start /** * 判断当前商城所属的代理人 * 将佣金分发给代理人 * 增加佣金明细记录 */ //计算分佣金额 $profit = Option::get('admin_profit', 0, 'saas', 0)['value'];//$store->profit $share_profit = sprintf('%.2f',($order->total_price * ($profit / 100))); if ($store->salesman_id > 0) { $admin_id = Salesman::findOne($store->salesman_id)->admin_id; //判断当前商城所属的代理人并将佣金分发给代理人 $saas_user_id = Admin::findOne($admin_id)->saas_user_id; if(!empty($saas_user_id)){ $saas_user = SaasUser::findOne($saas_user_id); $saas_user->share_profit = $saas_user->share_profit*1 + $share_profit*1; if($saas_user->save()){ //增加佣金明细记录 $log = new StoreShareMoney(); $log->profit = $profit; $log->user_id = $saas_user_id; $log->order_id = $order->id; $log->store_id = $store->id; $log->created_at = time(); $log->total_price = $order->total_price; $log->commission = $share_profit*1; $log->desc = $order->desc; $log->is_send = 1; $log->status = StoreShareMoney::STATUS_STORE_SETTLED; $log->type = StoreShareMoney::TYPE_BD_AGENT; $log->save(); } } } $option = Option::get('agency_price_config', 0, 'saas', [])['value']; if ($option) { $option = json_decode($option, true); } $province_percent = isset($option['province_percent']) ? $option['province_percent'] : 0; $city_percent = isset($option['city_percent']) ? $option['city_percent'] : 0; $district_percent = isset($option['district_percent']) ? $option['district_percent'] : 0; // $model_type = $option['model_type'] ?? 0; // $rate = 0; // if ((int)$model_type === 1) { // $check_ = Admin::findOne([ // 'area_level' => 1, // 'province_id' => $store->province_id, // 'city_id' => $store->city_id, // 'district_id' => $store->district_id, // ]); // if ($check_) { // // $rate = $district_percent; // // } // } else { // $check_ = Admin::findOne([ // 'area_level' => [2, 3], // 'province_id' => $store->province_id, // 'city_id' => $store->city_id, // ]); // // if ($check_) { // $rate = (int)$check_->area_level === 2 ? $city_percent : $province_percent; // } // } $province_id = $store->province_id; $city_id = $store->city_id; $district_id = $store->district_id; $admin_list = Admin::find()->where(['province_id' => $province_id, 'is_delete' => 0])->andWhere(['>', 'area_level', 0])->asArray()->all(); foreach ($admin_list as $item) { $rate = 0; $desc = ''; $saas_user_id = $item['saas_user_id']; $ag_rebate = 0; //省 if ((int)$item['area_level'] === 3) { $rate = $province_percent; $ag_rebate = $order->total_price * ($rate / 100); $desc = '用户下单,订单' . $order->order_no . ',发放 ' . $ag_rebate . '元省代佣金'; } //市 if ((int)$item['area_level'] === 2 && (int)$item['city_id'] === (int)$city_id) { $rate = $city_percent; $ag_rebate = $order->total_price * ($rate / 100); $desc = '用户下单,订单' . $order->order_no . ',发放 ' . $ag_rebate . '元市代佣金'; } //区 if ((int)$item['area_level'] === 1 && (int)$item['city_id'] === (int)$city_id && (int)$item['district_id'] === (int)$district_id) { $rate = $district_percent; $ag_rebate = $order->total_price * ($rate / 100); $desc = '用户下单,订单' . $order->order_no . ',发放 ' . $ag_rebate . '元区代佣金'; } if ($ag_rebate) { //给用户增加佣金 $saasUser = SaasUser::findOne($saas_user_id); $saasUser->share_profit += $ag_rebate; //增加记录 if ($saasUser->save()) { $form = new StoreShareMoney(); $form->user_id = $saas_user_id; $form->store_id = $store->id; $form->profit = $rate; $form->total_price = $order->total_price; $form->desc = $desc; $form->order_id = $order->id; $form->created_at = time(); $form->status = StoreShareMoney::STATUS_STORE_ORDER; $form->commission = $ag_rebate; $form->type = StoreShareMoney::TYPE_AREA_AGENT; $form->is_send = 1; $form->save(); } } } // $new = $rate / 100; // $saas_user_id = $check_->saas_user_id; // //给用户增加佣金 // $saasUser = SaasUser::findOne($saas_user_id); // if($saasUser){ // $ag_rebate = $order->total_price * 1 * $new; // $saasUser->share_profit += $ag_rebate; // if ($ag_rebate < 0.01) { // return; // } // //增加记录 // if ($saasUser->save()) { // $form = new StoreShareMoney(); // $form->user_id = $saas_user_id; // $form->store_id = $store->id; // $form->profit = $rate; // $form->total_price = $order->total_price; // $form->desc = "用户下单" . $order->order_no; // $form->order_id = $order->id; // $form->created_at = time(); // $form->type = 1; // $form->commission = $ag_rebate; // $form->status = 1; // $form->is_send = 1; // $form->save(); // } // } //end echo 'success'; return; } else { echo "支付失败"; return; } } /** * 合并订单支付回调 */ public function UnionOrderNotify($res) { $order_union = OrderUnion::findOne([ 'order_no' => $res['out_trade_no'], ]); if ($order_union->is_pay == 1) { echo "订单已支付"; return; } $order_id_list = json_decode($order_union->order_id_list, true); if (!$order_id_list) { echo "订单数据错误"; return; } if($order_union->type == \app\utils\OrderNo::ORDER_ALLIANCE_PURCHASE){ return $this->APUnionOrderNotify($res); } foreach ($order_id_list as $order_id) { $order = Order::findOne([ 'id' => $order_id, 'is_pay' => 0, ]); if (!$order) { continue; } $order->is_pay = 1; $order->pay_time = time(); $order->pay_type = $this->pay_type; $order->trade_status = Order::ORDER_FLOW_NO_SEND; $order->is_delete = 0; $order->transaction_id = $res['transaction_id']; if ($order->save()) { try { $this->addReceiver($order); //支付完成之后,相关的操作 $form = new OrderComplete(); $form->store_id = $order->store_id; $form->order_id = $order->id; $form->order_type = 0; $form->notify(); } catch (\Exception $e) { \Yii::warning(['UNION ORDER EXCEPTION <======> ', $e->getMessage()]); } } } $order_union->is_pay = 1; $order_union->save(); echo 'success'; return; } /** * 充值回调 */ public function RechargeOrderNotify($res) { $order = ReOrder::findOne(['order_no' => $res['out_trade_no']]); if (!$order) { return; } if ($order->is_pay == 1) { echo "订单已支付"; return; } // 此处取回调过来的金额作为订单金额,防止用户充值时抓包修改充值金额 $order->pay_price = $res['total_fee'] / 100; $order->save(); $order->is_pay = 1; $order->pay_time = time(); $order->pay_type = $this->pay_type; $order->transaction_id = $res['transaction_id']; if ($order->save()) { try { $this->updateMembershipAndCommission($order); if ($order->is_use_platform_mch == 1) { $store = Store::findOne($order->store_id); $profit = $order->pay_price * $store->transfer_profit / 100; $price = $order->pay_price - $profit; Store::addMoney($store, $price, '用户充值', $order->id, $order->user_id); } } catch (\Exception $e) { // Todo } try { // 用户充值成为股东 BonusPool::generalUserRecharge($order->user_id, $order->store_id); } catch (\Exception $e) {} //金额充值 $user = User::findOne($order->user_id); $before = $user->money; $user->money += floatval($order->pay_price) + floatval($order->send_price); if ($order->send_integral > 0) { $old_integral = $user->integral; $user->integral += $order->send_integral; $user->total_integral += $order->send_integral; $log = new AccountLog(); $log->store_id = get_store_id(); $log->user_id = $user->id; $log->type = AccountLog::TYPE_INTEGRAL; $log->log_type = AccountLog::LOG_TYPE_INCOME; $log->amount = $order->send_integral; $log->desc = "充值赠送, 订单号:{$order->order_no}"; $log->before = $old_integral; $log->after = $user->integral; $log->operator = 'system'; $log->operator_id = 0; $log->operator_type = AccountLog::TYPE_OPERATOR_NORMAL; $log->created_at = time(); $log->order_id = $order->id; $log->order_type = AccountLog::TYPE_PLATFORM_ORDER; $log->save(); } $user->save(); $log = new AccountLog(); $log->store_id = $order->store_id; $log->user_id = $user->id; $log->type = AccountLog::TYPE_BALANCE; $log->log_type = AccountLog::LOG_TYPE_INCOME; $log->amount = floatval($order->pay_price) + floatval($order->send_price); $log->desc = "充值余额微信在线支付,付款金额:{$order->pay_price}元,赠送金额:{$order->send_price}元。"; $log->before = $before; $log->after = $user->money; $log->operator = ''; $log->operator_id = 0; $log->operator_type = AccountLog::TYPE_OPERATOR_NORMAL; $log->created_at = time(); $log->order_id = $order->id; $log->order_type = AccountLog::TYPE_RECHARGE_ORDER; $log->save(); NoticeSend::UserChang($order->user_id, $user->binding, $order->pay_price, '充值到账'); echo 'success'; try { $this->ReOrderAfter($order); $this->addRechargeReceiver($order); sleep(10); $event = new OrderEvent(); $event->wechatProfitSharing($order); } catch (\Exception $e) { } // 赠送优惠券 AutoSendCoupon::send($user->id, CouponAutoSend::EVENT_RECHARGE, $user->store_id, $order->pay_price); } else { echo "支付失败"; } return; } /** * 更新用户会员等级和佣金信息 * @param $order 订单对象,用于获取订单相关信息 */ private function updateMembershipAndCommission($order) { $t = \Yii::$app->db->beginTransaction(); try { $user = User::findOne($order->user_id); $old_level_id = $user->level; if ($user->level < $order->level_up) { $user->level = $order->level_up; } // 如果用户不是分销商,并且对应的会员等级允许推广 $level = Level::findOne(['level' => $order->level_up]); if ($user->is_distributor == 0 && $level->promotion_status == 1) { $user->is_distributor = 1; // 更新用户为分销商 $share = Share::findOne(['user_id' => $user->id, 'store_id' => $user->store_id, 'is_delete' => 0]); if (!$share) { $share = new Share(); $share->user_id = $user->id; $share->mobile = $user->binding; $share->name = $user->nickname; $share->is_delete = 0; $share->store_id = $user->store_id; $share->status = 1; $share->created_at = time(); if (!$share->save()) { debug_log('添加用户分销商信息失败' . $share->getErrors(), 'wx.log'); } } } if (!$user->save()) { debug_log('更新用户会员等级失败' . $user->getErrors(), 'wx.log'); } $upgradeRecord = new MemberUpgradeRecord([ 'user_id' => $order->user_id, 'store_id' => $order->store_id, 'old_level_id' => $old_level_id, 'new_level_id' => $order->level_up, 'recharge_id' => $order->recharge_id, ]); if (!$upgradeRecord->save()) { debug_log('记录会员等级变更失败' . $upgradeRecord->getErrors(), 'wx.log'); } if ($user->parent_id != 0) { $recharge = Recharge::findOne($order->recharge_id); // 计算应发放给上级的佣金金额,根据被推荐人的数量计算 $referrals_count = RcCommissionLog::find()->where(['parent_id' => $user->parent_id, 'type' => 21])->count(); $referrer = User::findOne($user->parent_id); // 上级是代理才发放佣金 if ($referrer->is_distributor == 1) { // 如果用户成为代理,发放推广佣金 $commission = json_decode($recharge->referral_commission, true); $commission_amount = 0; if ($user->is_distributor == 1 && !empty($commission)) { // 发放推广佣金的逻辑... $length = count($commission); $index = ($referrals_count) % $length; $value = $commission[$index]; $commission_amount = $value['value']; if ($commission_amount > 0) { $log = new RcCommissionLog(); $log->user_id = $user->id; $log->store_id = get_store_id(); $log->amount = $commission_amount; $log->desc = "充值余额" . $recharge->name . "套餐赠送推广佣金, 订单号:{$order->order_no}"; $log->recharge_id = 1; $log->commission_type = 1; $log->created_at = time(); $log->order_id = $order->id; $log->parent_id = $user->parent_id; $log->recharge_id = $order->recharge_id; $log->bind_type = 1; $log->operator_type = RcCommissionLog::TYPE_OPERATOR_NORMAL; $log->order_type = RcCommissionLog::TYPE_RECHARGE_ORDER; $log->log_type = RcCommissionLog::LOG_TYPE_INCOME; $log->type = RcCommissionLog::TYPE_REFERRAL_COMMISSION; if (!$log->save()) { throw new \Exception('充值余额赠送佣金失败' . $log->getErrors()); } $referrer->total_price += $commission_amount; $referrer->price += $commission_amount; if (!$referrer->save()) { throw new \Exception('增加上级推广佣金失败' . $referrer->getErrors()); } $UserShareMoney = new UserShareMoney(); $UserShareMoney->store_id = get_store_id(); $UserShareMoney->order_id = $order->id; $UserShareMoney->user_id = $user->parent_id; $UserShareMoney->type = 0; $UserShareMoney->source = 7; //推广佣金 $UserShareMoney->money = $commission_amount; $UserShareMoney->created_at = time(); $UserShareMoney->order_type = 5; //充值订单 $UserShareMoney->is_delete = 0; $UserShareMoney->desc = "充值余额" . $recharge->name . "套餐赠送推广佣金, 订单号:{$order->order_no}"; $UserShareMoney->version = cyy_version(); if (!$UserShareMoney->save()) { throw new \Exception('用户推广佣金记录失败' . $referrer->getErrors()); } } else { $commission_amount_one = $recharge->level_one_bonus; $commission_amount_two = $recharge->level_two_bonus; if ($commission_amount_one > 0 && $user->parent_id > 0) { $log = new RcCommissionLog(); $log->user_id = $user->id; $log->store_id = get_store_id(); $log->amount = $commission_amount_one; $log->desc = "充值余额" . $recharge->name . "套餐赠送一级返现奖励, 订单号:{$order->order_no}"; $log->commission_type = 1; $log->created_at = time(); $log->order_id = $order->id; $log->parent_id = $user->parent_id; $log->recharge_id = $order->recharge_id; $log->bind_type = 1; $log->operator_type = RcCommissionLog::TYPE_OPERATOR_NORMAL; $log->order_type = RcCommissionLog::TYPE_RECHARGE_ORDER; $log->log_type = RcCommissionLog::LOG_TYPE_INCOME; $log->type = RcCommissionLog::TYPE_LEVEL_ONE_BONUS; if (!$log->save()) { throw new \Exception('充值余额赠送一级返现奖励失败' . $log->getErrors()); } $referrer->total_price += $commission_amount_one; $referrer->price += $commission_amount_one; if (!$referrer->save()) { throw new \Exception('增加上级返现奖励失败' . $referrer->getErrors()); } $UserShareMoney = new UserShareMoney(); $UserShareMoney->store_id = get_store_id(); $UserShareMoney->order_id = $order->id; $UserShareMoney->user_id = $user->parent_id; $UserShareMoney->type = 0; $UserShareMoney->source = 8; // 一级返现奖励 $UserShareMoney->money = $commission_amount_one; $UserShareMoney->created_at = time(); $UserShareMoney->order_type = 5; //充值订单 $UserShareMoney->is_delete = 0; $UserShareMoney->version = cyy_version(); $UserShareMoney->desc = "充值余额" . $recharge->name . "套餐赠送一级返现奖励, 订单号:{$order->order_no}"; if (!$UserShareMoney->save()) { throw new \Exception('用户一级返现奖励记录失败' . $referrer->getErrors()); } } if ($commission_amount_two > 0 && $referrer->parent_id > 0) { $log = new RcCommissionLog(); $log->user_id = $user->id; $log->store_id = get_store_id(); $log->amount = $commission_amount_two; $log->desc = "充值余额" . $recharge->name . "套餐赠送二级返现奖励, 订单号:{$order->order_no}"; $log->commission_type = 1; $log->created_at = time(); $log->order_id = $order->id; $log->parent_id = $referrer->parent_id; $log->recharge_id = $order->recharge_id; $log->bind_type = 2; $log->operator_type = RcCommissionLog::TYPE_OPERATOR_NORMAL; $log->order_type = RcCommissionLog::TYPE_RECHARGE_ORDER; $log->log_type = RcCommissionLog::LOG_TYPE_INCOME; $log->type = RcCommissionLog::TYPE_LEVEL_TWO_BONUS; if (!$log->save()) { throw new \Exception('充值余额赠送二级返现奖励失败' . $log->getErrors()); } $referrer = User::findOne($referrer->parent_id); $referrer->total_price += $commission_amount_two; $referrer->price += $commission_amount_two; if (!$referrer->save()) { throw new \Exception('增加上级返现奖励失败' . $referrer->getErrors()); } $UserShareMoney = new UserShareMoney(); $UserShareMoney->store_id = get_store_id(); $UserShareMoney->order_id = $order->id; $UserShareMoney->user_id = $referrer->parent_id; $UserShareMoney->type = 0; $UserShareMoney->source = 9; //二级返现奖励 $UserShareMoney->money = $commission_amount_two; $UserShareMoney->created_at = time(); $UserShareMoney->order_type = 5; // 充值订单 $UserShareMoney->is_delete = 0; $UserShareMoney->version = cyy_version(); $UserShareMoney->desc = "充值余额" . $recharge->name . "套餐赠送二级返现奖励, 订单号:{$order->order_no}"; if (!$UserShareMoney->save()) { throw new \Exception('用户二级返现奖励记录失败' . $referrer->getErrors()); } } } } else { // 如果用户没有成为代理,发放一二级佣金 $commission_amount_one = $recharge->level_one_bonus; $commission_amount_two = $recharge->level_two_bonus; if ($commission_amount_one > 0 && $user->parent_id > 0) { $log = new RcCommissionLog(); $log->user_id = $user->id; $log->store_id = get_store_id(); $log->amount = $commission_amount_one; $log->desc = "充值余额" . $recharge->name . "套餐赠送一级返现奖励, 订单号:{$order->order_no}"; $log->commission_type = 1; $log->created_at = time(); $log->order_id = $order->id; $log->parent_id = $user->parent_id; $log->recharge_id = $order->recharge_id; $log->bind_type = 1; $log->operator_type = RcCommissionLog::TYPE_OPERATOR_NORMAL; $log->order_type = RcCommissionLog::TYPE_RECHARGE_ORDER; $log->log_type = RcCommissionLog::LOG_TYPE_INCOME; $log->type = RcCommissionLog::TYPE_LEVEL_ONE_BONUS; if (!$log->save()) { throw new \Exception('充值余额赠送一级返现奖励失败' . $log->getErrors()); } $referrer->total_price += $commission_amount_one; $referrer->price += $commission_amount_one; if (!$referrer->save()) { throw new \Exception('增加上级返现奖励失败' . $referrer->getErrors()); } $UserShareMoney = new UserShareMoney(); $UserShareMoney->store_id = get_store_id(); $UserShareMoney->order_id = $order->id; $UserShareMoney->user_id = $user->parent_id; $UserShareMoney->type = 0; $UserShareMoney->source = 8; // 一级返现奖励 $UserShareMoney->money = $commission_amount_one; $UserShareMoney->created_at = time(); $UserShareMoney->order_type = 5; //充值订单 $UserShareMoney->is_delete = 0; $UserShareMoney->version = cyy_version(); $UserShareMoney->desc = "充值余额" . $recharge->name . "套餐赠送一级返现奖励, 订单号:{$order->order_no}"; if (!$UserShareMoney->save()) { throw new \Exception('用户一级返现奖励记录失败' . $referrer->getErrors()); } } if ($commission_amount_two > 0 && $referrer->parent_id > 0) { $log = new RcCommissionLog(); $log->user_id = $user->id; $log->store_id = get_store_id(); $log->amount = $commission_amount_two; $log->desc = "充值余额" . $recharge->name . "套餐赠送二级返现奖励, 订单号:{$order->order_no}"; $log->commission_type = 1; $log->created_at = time(); $log->order_id = $order->id; $log->parent_id = $referrer->parent_id; $log->recharge_id = $order->recharge_id; $log->bind_type = 2; $log->operator_type = RcCommissionLog::TYPE_OPERATOR_NORMAL; $log->order_type = RcCommissionLog::TYPE_RECHARGE_ORDER; $log->log_type = RcCommissionLog::LOG_TYPE_INCOME; $log->type = RcCommissionLog::TYPE_LEVEL_TWO_BONUS; if (!$log->save()) { throw new \Exception('充值余额赠送二级返现奖励失败' . $log->getErrors()); } $referrer = User::findOne($referrer->parent_id); $referrer->total_price += $commission_amount_two; $referrer->price += $commission_amount_two; if (!$referrer->save()) { throw new \Exception('增加上级返现奖励失败' . $referrer->getErrors()); } $UserShareMoney = new UserShareMoney(); $UserShareMoney->store_id = get_store_id(); $UserShareMoney->order_id = $order->id; $UserShareMoney->user_id = $referrer->parent_id; $UserShareMoney->type = 0; $UserShareMoney->source = 9; //二级返现奖励 $UserShareMoney->money = $commission_amount_two; $UserShareMoney->created_at = time(); $UserShareMoney->order_type = 5; // 充值订单 $UserShareMoney->is_delete = 0; $UserShareMoney->version = cyy_version(); $UserShareMoney->desc = "充值余额" . $recharge->name . "套餐赠送二级返现奖励, 订单号:{$order->order_no}"; if (!$UserShareMoney->save()) { throw new \Exception('用户二级返现奖励记录失败' . $referrer->getErrors()); } } } } } $t->commit(); } catch (\Exception $e) { $t->rollBack(); throw $e; } } /** * 积分充值回调 */ public function IntegralRechargeOrderNotify($res) { $order = IntegralRechargeOrder::findOne(['order_no' => $res['out_trade_no']]); if (!$order) { return; } if ($order->is_pay == 1) { echo "订单已支付"; return; } $order->is_pay = 1; $order->pay_time = time(); $order->pay_type = $this->pay_type; $order->transaction_id = $res['transaction_id']; if ($order->save()) { //金额充值 $user = User::findOne($order->user_id); if ($order->send_integral > 0) { $old_integral = $user->integral; $user->integral += $order->send_integral; $user->total_integral += $order->send_integral; $log = new AccountLog(); $log->store_id = get_store_id(); $log->user_id = $user->id; $log->type = AccountLog::TYPE_INTEGRAL; $log->log_type = AccountLog::LOG_TYPE_INCOME; $log->amount = $order->send_integral; $log->desc = "充值积分, 订单号:{$order->order_no}"; $log->before = $old_integral; $log->after = $user->integral; $log->operator = 'system'; $log->operator_id = 0; $log->operator_type = AccountLog::TYPE_OPERATOR_NORMAL; $log->created_at = time(); $log->order_id = $order->id; $log->order_type = AccountLog::TYPE_PLATFORM_ORDER; $log->save(); } $user->save(); NoticeSend::UserChang($order->user_id, $user->binding, $order->send_integral, '充值积分到账'); echo 'success'; $this->addIntegralRechargeReceiver($order); sleep(10); $event = new OrderEvent(); $event->wechatProfitSharing($order); } else { echo "支付失败"; } return; } private function addIntegralRechargeReceiver($order) { if (!\Yii::$app->isSaas()) { return; } $exists = IntegralRecharge::findOne($order->recharge_id); // 一级佣金发放 $user_1 = User::findOne($order->user_id); if ($user_1->parent_id <= 0) { \Yii::warning('<============= 订单:' . $order->order_no . '不存在店铺分销关系'); return; } $user_1 = User::findOne($user_1->parent_id); if (!$user_1) { return; } $user_1_money = round($order->pay_price * ($exists->first_commission / 100), 2); if ($user_1_money > 0.00) { $old_integral = $user_1->integral; $user_1->integral += $user_1_money; $user_1->total_integral += $user_1_money; $log = new AccountLog(); $log->store_id = get_store_id(); $log->user_id = $user_1->id; $log->type = AccountLog::TYPE_INTEGRAL; $log->log_type = AccountLog::LOG_TYPE_INCOME; $log->amount = $order->send_integral; $log->desc = "充值积分分销, 订单号:{$order->order_no}"; $log->before = $old_integral; $log->after = $user_1->integral; $log->operator = 'system'; $log->operator_id = 0; $log->operator_type = AccountLog::TYPE_OPERATOR_NORMAL; $log->created_at = time(); $log->order_id = $order->id; $log->order_type = AccountLog::TYPE_PLATFORM_ORDER; $log->save(); } //二级佣金发放 $user_2 = User::findOne($user_1->parent_id); if (!$user_2) { return; } $user_2_money = round($order->pay_price * ($exists->second_commission / 100), 2); if ($user_2_money > 0.00) { $old_integral = $user_2->integral; $user_2->integral += $user_2_money; $user_2->total_integral += $user_2_money; $log = new AccountLog(); $log->store_id = get_store_id(); $log->user_id = $user_2->id; $log->type = AccountLog::TYPE_INTEGRAL; $log->log_type = AccountLog::LOG_TYPE_INCOME; $log->amount = $order->send_integral; $log->desc = "充值积分分销, 订单号:{$order->order_no}"; $log->before = $old_integral; $log->after = $user_2->integral; $log->operator = 'system'; $log->operator_id = 0; $log->operator_type = AccountLog::TYPE_OPERATOR_NORMAL; $log->created_at = time(); $log->order_id = $order->id; $log->order_type = AccountLog::TYPE_PLATFORM_ORDER; $log->save(); } //三级佣金发放 $user_3 = User::findOne($user_2->parent_id); if (!$user_3) { return; } $user_3_money = round($order->pay_price * ($exists->third_commission / 100), 2); if ($user_3_money > 0.00) { $old_integral = $user_3->integral; $user_3->integral += $user_3_money; $user_3->total_integral += $user_3_money; $log = new AccountLog(); $log->store_id = get_store_id(); $log->user_id = $user_3->id; $log->type = AccountLog::TYPE_INTEGRAL; $log->log_type = AccountLog::LOG_TYPE_INCOME; $log->amount = $order->send_integral; $log->desc = "充值积分分销, 订单号:{$order->order_no}"; $log->before = $old_integral; $log->after = $user_3->integral; $log->operator = 'system'; $log->operator_id = 0; $log->operator_type = AccountLog::TYPE_OPERATOR_NORMAL; $log->created_at = time(); $log->order_id = $order->id; $log->order_type = AccountLog::TYPE_PLATFORM_ORDER; $log->save(); } } /** * @param $order * 充值订单回调 */ public function ReOrderAfter($order) { if ($order) { $total_price = 0; $orderAfter = null; if ((int)$order->type === 0 && $order->order_id) { $orderAfter = \app\plugins\scanCodePay\models\Order::findOne($order->order_id); if (!$orderAfter) { return; } $total_price = $orderAfter->total_price; } if ($total_price) { $user = User::findOne($order->user_id); if ($user) { $before = $user->money; $money = $user->money - $total_price; if ($money >= 0) { $user->money = $money; if ($user->save()) { $orderAfter->is_pay = 1; $orderAfter->pay_time = time(); if ($orderAfter->save()) { if (intval($orderAfter->user_coupon_id) > 0) { UserCoupon::updateAll(['is_use' => 1], ['id' => $orderAfter->user_coupon_id]); } $form = new NewMerchantForm(); $form->store_id = $orderAfter->store_id; $form->saasGiveIntegral($orderAfter->pay_price, $orderAfter->user_id, $orderAfter->order_no); $form_ = new \app\modules\client\models\v1\NewMerchantForm(); $form_->order_no = $orderAfter->order_no; $form->payResult(); $log = new AccountLog(); $log->store_id = $order->store_id; $log->user_id = $user->id; $log->type = AccountLog::TYPE_BALANCE; $log->log_type = AccountLog::LOG_TYPE_EXPEND; $log->amount = floatval($orderAfter->total_price); $log->desc = "当面付微信在线支付,订单编号为" . $orderAfter->order_no; $log->before = $before; $log->after = $user->money; $log->operator = ''; $log->operator_id = 0; $log->operator_type = AccountLog::TYPE_OPERATOR_NORMAL; $log->created_at = time(); $log->order_id = $order->id; $log->order_type = AccountLog::TYPE_SCAN_CODE_PAY; $log->save(); }; }; } } } } } public function LPorderNotify($res) { $order = RechargeReOrder::findOne(['order_no' => $res['out_trade_no']]); if (!$order) { return; } if ($order->is_pay == 1) { echo "订单已支付"; return; } $order->is_pay = 1; $order->pay_time = time(); $order->pay_type = $this->pay_type; $order->transaction_id = $res['transaction_id']; if ($order->save()) { //联盟券充值 $store_profit_max_option_model = Option::findOne(['name' => 'store_profit_max','store_id' => 0]); $recharge_profit = $store_profit_max_option_model->value; $league_price = $order->league_price; $store = Store::findOne($order->store_id); //给商家返券 $before = $store->league_price; $store->updateCounters(['league_price' => floatval($league_price)]); \app\models\SaaSLeaguePriceLog::setLeaguePriceLog( $order->store_id, 0, $league_price, $before, \app\models\SaaSLeaguePriceLog::TYPE_LEAGUE_RECHARGE, \app\models\SaaSLeaguePriceLog::SEND_TYPE, \app\models\SaaSLeaguePriceLog::ROLE_STORE, $order->id ); echo 'success'; return; } else { echo "支付失败"; return; } } /** * 充值回调 */ public function PROrderNotify($res) { $order = PurchaseReOrder::findOne(['order_no' => $res['out_trade_no']]); if (!$order) { return; } if ($order->is_pay == 1) { echo "订单已支付"; return; } $order->is_pay = 1; $order->pay_time = time(); $order->pay_type = $this->pay_type; $order->transaction_id = $res['transaction_id']; if ($order->save()) { //金额充值 $form = new BalanceForm(); $form->store_id = $order->store_id; $form->saas_id = $order->saas_id; $form->order = $order; $result = $form->storeSubmitRecharge(); if($result['code'] != 0){ $order->err = '支付成功,但是余额数据修改失败,原因:' . $result['msg']; $order->save(); \Yii::error([__METHOD__, $res, $result, $order]); } echo 'success'; return; } else { echo "支付失败"; return; } } /** * 会员购买回调 */ public function LevelOrderNotify($res) { $order = LevelOrder::findOne([ 'order_no' => $res['out_trade_no'], ]); if (!$order) { return; } if ($order->is_pay == 1) { echo "订单已支付"; return; } $order->is_pay = 1; $order->pay_time = time(); $order->pay_type = $this->pay_type; if ($order->save()) { //会员升级 $user = User::findOne($order->user_id); $user->level = $order->after_level; $user->save(); try { if ($order->is_use_platform_mch == 1) { $store = Store::findOne($order->store_id); $profit = $order->pay_price * $store->transfer_profit / 100; $price = $order->pay_price - $profit; Store::addMoney($store, $price, '用户购买会员等级', $order->id, $order->user_id); } } catch (\Exception $e) { // Todo } $level = Level::findOne(['level' => $user->level, 'store_id' => $order->store_id, 'is_delete' => 0]); if ($level) { $saas_user = SaasUser::findOne(['mobile' => $user->binding, 'is_delete' => 0]); $user_name = $user->nickname; if ($saas_user) { $user_name = $saas_user->name; } if ($user->old_parent_id) { $parent = User::findOne($user->old_parent_id);//上级 //检测一级是否存在且佣金是否设置 if ($parent && $level->firstProfit) { //发放一级佣金 //... $parent->total_price += $level->firstProfit; $parent->price += $level->firstProfit; $parent->save(); UserShareMoney::set($level->firstProfit, $user->old_parent_id, $order->id, 0, 1, $order->store_id, UserShareMoney::LEVEL_ORDER_TYPE, '用户' . $user_name . '购买会员发放一级佣金'); if ($parent->old_parent_id) { $parent_1 = User::findOne($parent->old_parent_id);//上级 //检测二级是否存在且佣金是否设置 if ($parent_1 && $level->secondProfit) { //发放二级佣金 $parent_1->total_price += $level->secondProfit; $parent_1->price += $level->secondProfit; $parent_1->save(); UserShareMoney::set($level->secondProfit, $parent->old_parent_id, $order->id, 0, 1, $order->store_id, UserShareMoney::LEVEL_ORDER_TYPE, '用户' . $user_name . '购买会员发放二级佣金'); //检测三级是否存在且佣金是否设置 $parent_2 = User::findOne($parent_1->old_parent_id);//上级 if ($parent_2 && $level->thirdProfit) { //发放三级佣金 $parent_2->total_price += $level->thirdProfit; $parent_2->price += $level->thirdProfit; $parent_2->save(); UserShareMoney::set($level->thirdProfit, $parent_1->old_parent_id, $order->id, 0, 1, $order->store_id, UserShareMoney::LEVEL_ORDER_TYPE, '用户' . $user_name . '购买会员发放三级佣金'); } } } } } } echo 'success'; return; } else { echo "支付失败"; return; } } /** * saas联盟佣金提现回调 */ public function saasProfitCash($res) { $order = SaasProfitCash::findOne([ 'order_no' => $res['out_trade_no'], ]); if (!$order) { return; } $order->is_pay = 1; $order->pay_time = time(); if ($order->save()) { echo 'success'; return; } else { echo "支付失败"; return; } } /** * 商城订单回调 * @param $res */ public function MallOrderNotify($res) { $order = Order::findOne([ 'order_no' => $res['out_trade_no'], ]); $orderPayType = $order->pay_type; if ($order->is_pay == 1) { echo "订单已支付"; return; } $order->is_pay = 1; $order->pay_time = time(); $order->pay_type = $this->pay_type; // 如果是货到付款的支付 支付成功后修改订单状态为已完成 if($orderPayType == 2){ $order->trade_status = Order::ORDER_FLOW_CONFIRM; $order->send_time = time(); $order->confirm_time = time(); }else{ $order->trade_status = Order::ORDER_FLOW_NO_SEND; } $order->is_delete = 0; $order->transaction_id = $res['transaction_id']; $res['trxid'] && $order->allinpay_payment_id = $res['trxid']; $res['trxcode'] && $order->allinpay_trxcode = $res['trxcode']; if ($order->save()) { // // 同城配送订单下单 // if ($order->is_delivery == 1) { // if($order->alipay_trade_no){ // $delivery_info = DeliveryInfo::findOne(['store_id' => $order->store_id, 'order_no' => $order->order_no]); // $detail_goods = OrderDetail::find()->where(['order_id' => $order->id])->select('goods_name as name, pic, num, total_price as price')->asArray()->all(); // $delivery_res = ADelivery::createOrder(0, $order->store_id, $delivery_info->mini_id, // $order->user->alipay_open_id, $detail_goods, $order->order_no, $delivery_info->address_id); // \Yii::error('-----------同城配送返回' . Json::encode($delivery_res)); // }else{ // $detail_goods = OrderDetail::find()->where(['order_id' => $order->id])->select('goods_name as name, pic, num, total_price as price')->asArray()->all(); // $delivery_res = Delivery::addOrder($detail_goods, $order->order_no); // \Yii::error('-----------同城配送返回' . Json::encode($delivery_res)); // } // } if ($order->level_order_id) { $levelOrder = LevelOrder::findOne($order->level_order_id); $this->LevelOrderNotify(['out_trade_no' => $levelOrder->order_no]); } // 预约商品库存操作 BookOrderNum::bookNumReduce($order); $this->addReceiver($order); $this->OrderVoucherUse($order); //支付完成之后,相关的操作 //抖品佣金处理 $this->videoGoodsShare($order); $form = new OrderComplete(['notify_res' => $res]); $form->store_id = $order->store_id; $form->order_id = $order->id; $form->order_type = 0; $form->notify(); echo 'success'; return; } else { echo "支付失败"; return; } } /** * 采购员单回调 * @param $res */ public function APOrderNotify($res) { $order = PurchaseOrder::findOne([ 'order_no' => $res['out_trade_no'], ]); if ($order->is_pay == 1) { echo "订单已支付"; return; } $order->is_pay = 1; $order->pay_time = time(); $order->pay_type = $this->pay_type; $order->trade_status = Order::ORDER_FLOW_NO_SEND; $order->is_delete = 0; $order->transaction_id = $res['transaction_id']; if ($order->save()) { //支付完成之后,相关的操作 OrderPayDataForm::notify($order->id); echo 'success'; return; } else { \Yii::error('-----------PurchaseOrder保存失败' . Json::encode($order->getErrors())); echo "支付失败"; return; } } /** * 采购员单回调 * @param $res */ public function APUnionOrderNotify($res) { $order_union = OrderUnion::findOne([ 'order_no' => $res['out_trade_no'], ]); if ($order_union->is_pay == 1) { echo "订单已支付"; return; } $order_id_list = json_decode($order_union->order_id_list, true); if (!$order_id_list) { echo "订单数据错误"; return; } foreach ($order_id_list as $order_id) { $order = PurchaseOrder::findOne([ 'id' => $order_id, 'is_pay' => 0, ]); if (!$order) { continue; } $order->is_pay = 1; $order->pay_time = time(); $order->pay_type = $this->pay_type; $order->trade_status = Order::ORDER_FLOW_NO_SEND; $order->is_delete = 0; $order->transaction_id = $res['transaction_id']; $order->save(); } try { OrderPayDataForm::notify($order->id, $order_id_list); } catch (\Exception $e) { \Yii::warning(['UNION ORDER EXCEPTION <======> ', $e->getMessage()]); } $order_union->is_pay = 1; $order_union->save(); echo 'success'; return; } /** * 商盟订单回调 * @param $res */ public function BusinessNotify($res) { $order = Order::findOne([ 'order_no' => $res['out_trade_no'], ]); if ($order->is_pay == 1) { echo "订单已支付"; return; } $order->is_pay = 1; $order->pay_time = time(); $order->pay_type = $this->pay_type; $order->trade_status = Order::ORDER_FLOW_NO_SEND; $order->is_delete = 0; $order->transaction_id = $res['transaction_id']; if ($order->save()) { // 同城配送订单下单 // 预约商品库存操作 BookOrderNum::bookNumReduce($order); //商盟订单 $this->addReceiver($order); // 支付完成之后,相关的操作 $form = new AllianceOrderComplete(); $form->store_id = $order->store_id; $form->order_id = $order->id; $form->order_type = 0; $form->notify(); echo 'success'; return; } else { echo "支付失败"; return; } } /** * 入驻商提现支付宝回调 * @param $res */ public function batchTransNotify($res) { $cash = MchCash::findOne(['order_no' => $res['out_batch_no']]); $cash->updated_at = time(); $cash->virtual_type = 2; if ($res['batch_status'] == 'SUCCESS' && $res['fail_count'] == '0') { $cash->status = 1; $cash->save(false); echo 'success'; return; } else if ($res['batch_status'] == 'FAIL' && $res['fail_count'] == '1'){ $cash->status = 2; $cash->save(); echo 'success'; return; } else { echo 'success'; return; } } /** * @param $res */ public function ScanOrderNotify($res) { $order = \app\plugins\scanCodePay\models\Order::findOne([ 'order_no' => $res['out_trade_no'], ]); $this->is_scan = 1; if ($order->is_pay == 1) { echo "订单已支付"; return; } $order->is_pay = 1; $order->pay_time = time(); $order->pay_type = $this->pay_type; $order->trade_status = Order::ORDER_FLOW_CONFIRM; $order->is_delete = 0; $order->transaction_id = $res['transaction_id']; if ($order->save()) { if (intval($order->user_coupon_id) > 0) { UserCoupon::updateAll(['is_use' => 1], ['id' => $order->user_coupon_id]); } // if (intval($order->is_platform) === 1) { $form = new \app\modules\alliance\models\NewMerchantForm(); $form->store_id = $order->store_id; $result = $form->saasGiveIntegral($order->pay_price, $order->user_id, $order->order_no); } else { $form = new \app\modules\client\models\v1\NewMerchantForm(); } $form->order_no = $res['out_trade_no']; $form->payResult(); //计算余额抵扣的钱 if ($order->is_combine_pay && $order->combine_money > 0 && (int)$order->is_reduce_combine === 1) { $user = User::findOne($order->user_id); $user->money -= $order->combine_money; $user->save(); $order->is_reduce_combine = 1; $order->save(); } try { if ($order->is_use_platform_mch == 1) { $store = Store::findOne($order->store_id); $profit = $order->pay_price * $store->transfer_profit / 100; $price = $order->pay_price - $profit; Store::addMoney($store, $price, '用户当面付', $order->id, $order->user_id); } } catch (\Exception $e) { // Todo } //商盟订单 if (Store::hasIncoming($order->store_id) || intval($order->pay_type) === Order::PAY_TYPE_YUNST_WECHAT_PAY) { $this->addReceiver($order); } // sleep(10); // $event = new OrderEvent(); // $event->wechatProfitSharing($order); if ($order->store_id > 0) { $delay = 86400; if (intval($order->pay_type) === Order::PAY_TYPE_YUNST_WECHAT_PAY) { $tomoTime = strtotime(date('Y-m-d', strtotime("+1 day"))) + 39600; $delay = $tomoTime - time(); debug_log(['当面付添加延时队列时间' => $delay]); } \queue_push(new NoAfterSalesOrderJob(['order_id' => $order->id, 'store_id' => $order->store_id, 'is_scan' => 1]), $delay); } // 支付完成之后,相关的操作 $form = new OrderComplete(); $form->order_id = $order->id; $form->order_type = 6; $form->notify(); $this->ScanOrderAfter($order); echo 'success'; return; } else { echo "支付失败"; return; } } //自购返利 private function buseinessSaasSelf($order){ $store = Store::findOne($order->store_id); $saas_transfer_profit = $store->transfer_profit; //判断商城让利比例 //当面付 if ($this->is_scan) { $saas_transfer_profit = $store->scan_transfer_profit; } // 点餐判断 判断订单中是否设置food_flag_id if (isset($order->food_flag_id) && intval($order->food_flag_id) > 0) { $saas_transfer_profit = $store->food_transfer_profit; } // 收银台判断 判断收银订单中是否存在当前订单 if (isset($order->hanging_order_id) && intval($order->hanging_order_id) > 0) { $saas_transfer_profit = $store->cashier_transfer_profit; } // if (isset($order->pay_type) && intval($order->pay_type) === Order::PAY_TYPE_YUNST_WECHAT_PAY) { // $saas_transfer_profit = $store->ratio ?: 0; // } if ($saas_transfer_profit <= 0) { return; } if($store->self_rebate_switch != 0 && $store->self_rebate_value == 0){ $defaultSet = Option::get(OptionSetting::SHARE_SELF_REBATE_DEFAULT_SETTING, -1, OptionSetting::SHARE_GROUP_NAME, '{}'); $defaultSet = json_decode($defaultSet['value'], true); if(!empty($defaultSet['self_rebate_switch']) && !empty($defaultSet['self_rebate_value'])){ $store->self_rebate_value = $defaultSet['self_rebate_value']; } } // 自购返利 if ($store->self_rebate_switch != 0 && $store->self_rebate_value > 0) { //判断是否开启自购返利 且 自购返利比例大于0 $saas_share_money = floor_num($order->pay_price * $saas_transfer_profit / 100, 2); //计算初始总返利金额 $self_money = (($saas_share_money * ($store->self_rebate_value / 100))); $user = User::findOne(['id' => $order->user_id, 'store_id' => $order->store_id]); if ($order->saas_id) { //普通分账 $self_user = SaasUser::findOne(['id' => $order->saas_id]); } else { $binding = $user->binding; $self_user = SaasUser::findOne(['mobile' => $binding]); } $share_num = 1; $self_money = round(($self_money * $share_num), 2); // if ($order->is_platform) { // $execute_flag = SharingReceiver::EXECUTE_TYPE_TRANSFER; // } // 判断是否为联盟支付 if ($order->is_platform) { // //没有分销账户信息的不分账 // $distributionInfo = SaasDistribution::find()->where(['saas_id'=>$self_user->id,'is_delete'=>0])->asArray()->one(); // if(empty($distributionInfo) || !isset($distributionInfo['platform_open_id']) || empty($distributionInfo['platform_open_id'])){ // return; // } //新逻辑 $add_type = WechatShare::RECEIVE_PERSONAL_OPENID; $add_type_num = SharingReceiver::RECEIVE_OPENID; $execute_flag = SharingReceiver::EXECUTE_TYPE_NORMAL; $account = $self_user->platform_open_id; } else { $add_type = WechatShare::RECEIVE_PERSONAL_SUB_OPENID; $add_type_num = SharingReceiver::RECEIVE_SUB_OPENID; if ($user) {//如果用户存在,则走分账 $execute_flag = SharingReceiver::EXECUTE_TYPE_NORMAL; $account = $user->wechat_open_id; } // else {//不存在走联盟转账 // $execute_flag = SharingReceiver::EXECUTE_TYPE_TRANSFER; // $account = $self_user->platform_open_id; // } } if ($account) { $sharing = SharingReceiver::findOne([ 'store_id' => $order->store_id, 'account' => $account, 'order_no' => $order->order_no, 'from' => SharingReceiver::FROM_SELF, 'is_delete' => 0 ]); if ($self_money > 0) { if ($execute_flag == SharingReceiver::EXECUTE_TYPE_NORMAL) { //如果走分账 if (!$sharing) { $add_self_res = WechatShare::addReceivers($account, WechatShare::RELATION_USER, $add_type, null, false, $order->store_id, $order->is_platform, $order); \Yii::error(['<====== 订单号:' . $order->order_no .' 平台分销一级接收方添加结果 =====>', $add_self_res]); } $is_pay = SharingReceiver::PAY_WAIT; } else { $self_user->share_profit += $self_money; $self_user->save(); $is_pay = SharingReceiver::PAY_SUCCESS; } $this->business_saas_self_money = $self_money; if (!$sharing) { $sharing = new SharingReceiver(); $sharing->store_id = $order->store_id; $sharing->rate = $store->self_rebate_value; $sharing->order_no = $order->order_no; $sharing->transaction_id = $order->transaction_id; $sharing->type = $add_type_num; $sharing->from = SharingReceiver::FROM_SELF; $sharing->account = $account; $sharing->execute_type = SharingReceiver::EXECUTE_TYPE_NORMAL; $sharing->name = $self_user->name; $sharing->saas_id = $self_user->id; $sharing->user_id = 0; $sharing->description = '平台分账到个人'; $sharing->is_pay = $is_pay; $sharing->remark = '平台(自购返利)'; $sharing->is_delete = SharingReceiver::IS_DELETE_NO; $sharing->created_at = time(); $sharing->updated_at = time(); $sharing->is_platform = $order->is_platform; $this->saas_self_money = $sharing->amount; } $sharing->amount = $self_money; if (!$sharing->save()) { \Yii::error(['联盟佣金 <====== 订单号:' . $order->order_no .' SAAS 平台自购返利分账详情, 平台openid:' . $self_user->platform_open_id . ',入库失败 =====>', $sharing->errors[0]]); } } else { SharingReceiver::updateAll([ 'is_delete' => 1 ], [ 'store_id' => $order->store_id, 'account' => $account, 'order_no' => $order->order_no, 'from' => SharingReceiver::FROM_SELF, 'is_delete' => 0 ]); } } } } public function ScanOrderAfter($order) { $file_name = \Yii::$app->runtimePath . '/logs/scan_pay.log'; try { if ($order->store_id) { //获取规则 $rule = GiveIntegralRules::find()->where(['and', ['<', 'start_date', time()], ['>', 'end_date', time()], ['status' => 1, 'is_delete' => 0]])->select('id, rate')->asArray()->all(); $rule_ids = array_column($rule, 'id'); foreach ($rule_ids as $item) { $rule_id = RulesFaceStore::find()->where(['rule_id' => $item, 'store_id' => $order->store_id])->select('rule_id')->column(); foreach ($rule as $rule_item) { //$rule_ids = RulesFaceStore::find()->where(['rule_id' => $rule_ids, 'store_id' => $order->store_id])->select('rule_id')->column(); if ($rule_id) { if (in_array($rule_item['id'], $rule_id)) { $store_ids = RulesGiveIntegralStore::find()->where(['rule_id' => $rule_id])->select('store_id')->column(); $user = User::findOne($order->user_id); if (!$order->user_id) { $saas_user = SaasUser::findOne($order->saas_id); $user = User::findOne(['binding' => $saas_user->mobile]); if (empty($user)) { $user = User::findOne(['alipay_open_id' => $saas_user->ali_user_id]); } } foreach ($store_ids as $item) { $other_user = User::findOne(['store_id' => $item, 'binding' => $user->binding]); if (!$other_user) { $other_user = new User(); $other_user->access_token = \Yii::$app->security->generateRandomString(); $other_user->binding = $user->binding; $other_user->type = User::USER_TYPE_NORMAL; $other_user->nickname = substr_replace($user->binding, '******', 3, 6); $other_user->avatar_url = \Yii::$app->request->hostInfo . \Yii::$app->request->baseUrl . '/web/v1/statics/images/avatar.png'; $other_user->username = \Yii::$app->security->generateRandomString(); $other_user->password = \Yii::$app->security->generatePasswordHash(\Yii::$app->security->generateRandomString(), 5); $other_user->auth_key = \Yii::$app->security->generateRandomString(); $other_user->is_delete = User::USER_NOT_DELETE; $other_user->store_id = $item; $other_user->parent_id = $user->id; $other_user->platform = User::USER_FROM_WECHAT; $other_user->alipay_open_id = $user->alipay_open_id; $other_user->save(); if ($other_user->save()) { $share_log = new UserShareLog(); $share_log->parent_id = $user->id; $share_log->user_id = $other_user->id; $share_log->created_at = time(); $share_log->save(); } } $integral = (int)($order->total_price * ($rule_item['rate'] / 100)); $log = new AccountLog(); $log->store_id = $item; $log->user_id = $other_user->id; $log->type = AccountLog::TYPE_INTEGRAL; $log->log_type = AccountLog::LOG_TYPE_INCOME; $log->amount = $integral; $log->desc = '订单'.$order->order_no.'赠送积分'; $log->before = $other_user->integral * 1; $log->after = (int)($other_user->integral * 1 + $integral); $log->operator = ''; $log->operator_id = 0; $log->operator_type = AccountLog::TYPE_OPERATOR_NORMAL; $log->created_at = time(); $log->order_id = $order->id; $log->order_type = AccountLog::TYPE_SCAN_CODE_PAY; if (!$log->save()) { file_put_contents($file_name, "\r\n" . '[当面付][' . date('Y-m-d H:i:s') . ']' . json_encode($log->errors), FILE_APPEND); } else { $other_user->integral = (int)($other_user->integral * 1 + $integral); $other_user->total_integral = (int)($other_user->total_integral * 1 + $integral); if (!$other_user->save()) { file_put_contents($file_name, "\r\n" . '[用户积分][' . date('Y-m-d H:i:s') . ']' . json_encode($other_user->errors), FILE_APPEND); \Yii::error("[用户积分]" . json_encode($other_user->errors)); } } } } } } } } } catch (\Exception $e) { file_put_contents($file_name, "\r\n" . '[用户积分发放失败][' . date('Y-m-d H:i:s') . ']' . json_encode($e->getMessage() . $e->getFile() . $e->getLine()), FILE_APPEND); echo "支付失败"; return; } } /** * @param Order $order * 微信分账支付回调时添加分账接收方并计算相关分账数额 */ public function addReceiver($order) { if (!\Yii::$app->isSaas()) { return; } debug_log(['type' => '分账'], 'orderDetail.log'); // TODO: 目前平台分销部分因openid问题,走提现逻辑 //联盟分销 $this->newSaasShareReceiver($order); // 商城级分销 $this->shareStoreToStore($order); // 平台推荐 $this->newSaasRecommendReceiver($order); //自购返利 $this->buseinessSaasSelf($order); //自定义分账接收方 $this->addCustomReceiver($order); //区域代理 / 推广代理分账接收方 $this->addAgentReceiver($order); // 服务商分成 $this->newSaasPlatformReceiver($order); // 以下为商城分销 return; } /** * @param ReOrder $order * 微信分账支付回调时添加分账接收方并计算相关分账数额 */ public function addRechargeReceiver($order) { if (!\Yii::$app->isSaas()) { return; } // TODO: 目前平台推荐和分销不走分账,走提现逻辑 $this->newSaasShareReceiver($order); $this->shareStoreToStore($order); // $this->newSaasRecommendReceiver($order); $this->newSaasPlatformReceiver($order); $share_setting = Option::get('share_basic_setting', $order->store_id); $share_setting = $share_setting ? Json::decode($share_setting['value']) : []; if (!isset($share_setting['level'])) { return; } if ($share_setting['level']['value'] == 0) { return; } $share_money_setting = Option::get('share_money_setting', $order->store_id); $share_money_setting = $share_money_setting ? Json::decode($share_money_setting['value']) : []; // 一级佣金发放 if ($share_setting['level']['value'] >= 1) { if ($share_setting['is_rebate']['value'] > 0) { $user_1 = User::findOne($order->user_id); $remark = '店铺一级分销(自购返利)'; } else { $user_1 = User::findOne($order->user_id); if ($user_1->parent_id <= 0) { \Yii::warning('<============= 订单:' . $order->order_no . '不存在店铺分销关系'); return; } $remark = '店铺一级分销'; $user_1 = User::findOne($user_1->parent_id); } if (!$user_1) { return; } // 如果是平台用户,获取平台openid if ($order->is_platform) { $saas_user_1 = SaasUser::findOne(['mobile' => $user_1->binding]); if (!$saas_user_1) { return; } $wechat_openid_1 = $saas_user_1->platform_open_id; $user_name_1 = $saas_user_1->name; $user_id_1 = $saas_user_1->id; $add_type = WechatShare::RECEIVE_PERSONAL_SUB_OPENID; $add_type_number = SharingReceiver::RECEIVE_SUB_OPENID; } else { $wechat_openid_1 = $user_1->wechat_open_id; $user_name_1 = $user_1->nickname; $user_id_1 = $user_1->id; $add_type = WechatShare::RECEIVE_PERSONAL_SUB_OPENID; $add_type_number = SharingReceiver::RECEIVE_SUB_OPENID; } $user_1_money = round($order->pay_price * ($share_money_setting['level_one']['value'] / 100), 2); if ($user_1_money > 0.00) { $add_res_1 = [ 'code' => 1 ]; $share_receiver = SharingReceiver::findOne(['store_id' => $order->store_id, 'account' => $wechat_openid_1, 'order_no' => $order->order_no]); if (!$share_receiver) { $add_res_1 = WechatShare::addReceivers($wechat_openid_1, WechatShare::RELATION_USER, $add_type, null, false, $order->store_id, $order->is_platform, $order); \Yii::error(['<====== 充值订单号:' . $order->order_no .' 一级接收方添加结果 =====>', $add_res_1]); } if ($this->adapay() || $add_res_1['code'] == 0 || $share_receiver) { $sharing = new SharingReceiver(); $sharing->store_id = $order->store_id; $sharing->rate = $share_money_setting['level_one']['value']; $sharing->order_no = $order->order_no; $sharing->transaction_id = $order->transaction_id; $sharing->type = $add_type_number; $sharing->from = SharingReceiver::FROM_STORE; $sharing->account = $wechat_openid_1; $sharing->user_id = $user_id_1; $sharing->execute_type = SharingReceiver::EXECUTE_TYPE_NORMAL; $sharing->name = $user_name_1; $sharing->description = '店铺分账到个人'; $sharing->remark = $remark; $sharing->amount = $user_1_money; $sharing->is_pay = SharingReceiver::PAY_WAIT; $sharing->is_delete = SharingReceiver::IS_DELETE_NO; $sharing->created_at = time(); $sharing->updated_at = time(); if (!$sharing->save()) { \Yii::error(['<====== 订单号:' . $order->order_no .' 添加接收方openid ' . $wechat_openid_1 . '入库失败 =====>', $sharing->errors[0]]); } } } } //二级佣金发放 if ($share_setting['level']['value'] >= 2) { $user_2 = User::findOne($user_1->parent_id); if (!$user_2) { return; } // 如果是平台用户,获取平台openid if ($order->is_platform) { $saas_user_2 = SaasUser::findOne(['mobile' => $user_2->binding]); if (!$saas_user_2) { return; } $wechat_openid_2 = $saas_user_2->platform_open_id; $user_name_2 = $saas_user_2->name; $user_id_2 = $saas_user_2->id; } else { $wechat_openid_2 = $user_2->wechat_open_id; $user_name_2 = $user_2->nickname; $user_id_2 = $user_2->id; } $user_2_money = round($order->pay_price * ($share_money_setting['level_two']['value'] / 100), 2); if ($user_2_money > 0.00) { $add_res_2 = [ 'code' => 1 ]; $share_receiver = SharingReceiver::findOne(['store_id' => $order->store_id, 'account' => $wechat_openid_2, 'order_no' => $order->order_no]); if (!$share_receiver) { $add_res_2 = WechatShare::addReceivers($wechat_openid_2, WechatShare::RELATION_USER, $add_type, null, false, $order->store_id, $order->is_platform, $order); \Yii::error(['<====== 订单号:' . $order->order_no . ' 二级接收方添加结果 =====>', $add_res_2]); } if ($this->adapay() || $add_res_2['code'] == 0 || $share_receiver) { $sharing = new SharingReceiver(); $sharing->store_id = $order->store_id; $sharing->rate = $share_money_setting['level_two']['value']; $sharing->order_no = $order->order_no; $sharing->transaction_id = $order->transaction_id; $sharing->type = $add_type_number; $sharing->from = SharingReceiver::FROM_STORE; $sharing->account = $wechat_openid_2; $sharing->user_id = $user_id_2; $sharing->execute_type = SharingReceiver::EXECUTE_TYPE_NORMAL; $sharing->name = $user_name_2; $sharing->description = '店铺分账到个人'; $sharing->remark = '店铺二级分销'; $sharing->amount = $user_2_money; $sharing->is_pay = SharingReceiver::PAY_WAIT; $sharing->is_delete = SharingReceiver::IS_DELETE_NO; $sharing->created_at = time(); $sharing->updated_at = time(); if (!$sharing->save()) { \Yii::error(['<====== 订单号:' . $order->order_no .' 添加接收方openid ' . $wechat_openid_2 . '入库失败 =====>', $sharing->errors[0]]); } } } } //三级佣金发放 if ($share_setting['level']['value'] >= 3) { $user_3 = User::findOne($user_2->parent_id); if (!$user_3) { return; } // 如果是平台用户,获取平台openid if ($order->is_platform) { $saas_user_3 = SaasUser::findOne(['mobile' => $user_3->binding]); if (!$saas_user_3) { return; } $wechat_openid_3 = $saas_user_3->platform_open_id; $user_name_3 = $saas_user_3->name; $user_id_3 = $saas_user_3->id; } else { $wechat_openid_3 = $user_3->wechat_open_id; $user_name_3 = $user_3->nickname; $user_id_3 = $user_3->id; } $user_3_money = round($order->pay_price * ($share_money_setting['level_three']['value'] / 100), 2); if ($user_3_money > 0.00) { $add_res_3 = [ 'code' => 1 ]; $share_receiver = SharingReceiver::findOne(['store_id' => $order->store_id, 'account' => $wechat_openid_3, 'order_no' => $order->order_no]); if (!$share_receiver) { $add_res_3 = WechatShare::addReceivers($wechat_openid_3, WechatShare::RELATION_USER, $add_type, null, false, $order->store_id, $order->is_platform, $order); \Yii::error(['<====== 订单号:' . $order->order_no .' 三级接收方添加结果 =====>', $add_res_3]); } if ($this->adapay() || $add_res_3 == 0 || $share_receiver) { $sharing = new SharingReceiver(); $sharing->store_id = $order->store_id; $sharing->rate = $share_money_setting['level_three']['value']; $sharing->order_no = $order->order_no; $sharing->transaction_id = $order->transaction_id; $sharing->type = $add_type_number; $sharing->from = SharingReceiver::FROM_STORE; $sharing->account = $wechat_openid_3; $sharing->user_id = $user_id_3; $sharing->execute_type = SharingReceiver::EXECUTE_TYPE_NORMAL; $sharing->name = $user_name_3; $sharing->description = '店铺分账到个人'; $sharing->remark = '店铺三级分销'; $sharing->amount = $user_3_money; $sharing->is_pay = SharingReceiver::PAY_WAIT; $sharing->is_delete = SharingReceiver::IS_DELETE_NO; $sharing->created_at = time(); $sharing->updated_at = time(); if (!$sharing->save()) { \Yii::error(['<====== 订单号:' . $order->order_no .' 添加接收方openid ' . $wechat_openid_3 . '入库失败 =====>', $sharing->errors[0]]); } } } } } private function newSaasShareReceiver($order) { debug_log(['type' => 'newSaasShareReceiver'], 'orderDetail.log'); $store = Store::findOne($order->store_id); $saas_transfer_profit = $store->transfer_profit; if ($this->is_scan) { $saas_transfer_profit = $store->scan_transfer_profit; } // 点餐判断 判断订单中是否设置food_flag_id if (isset($order->food_flag_id) && intval($order->food_flag_id) > 0) { $saas_transfer_profit = $store->food_transfer_profit; } // 收银台判断 判断收银订单中是否存在当前订单 if (isset($order->hanging_order_id) && intval($order->hanging_order_id) > 0) { $saas_transfer_profit = $store->cashier_transfer_profit; } // if (isset($order->pay_type) && intval($order->pay_type) === Order::PAY_TYPE_YUNST_WECHAT_PAY) { // $saas_transfer_profit = $store->ratio ?: 0; // } if ($saas_transfer_profit <= 0) { return; } $saas_share_money = floor_num($order->pay_price * $saas_transfer_profit / 100, 2);//10 * 0.1 = 1 // 根据商城运营模式,判断分账权限 /**if ($store->business_model != 1) { //分账接收方类型枚举:个人sub_openid,特约商户option_id $add_type = WechatShare::RECEIVE_PERSONAL_OPENID; // 接收方类型:sub_openid $add_type_num = SharingReceiver::RECEIVE_OPENID; } else { //分账接收方类型枚举:个人sub_openid,特约商户option_id $add_type = WechatShare::RECEIVE_PERSONAL_SUB_OPENID; // 接收方类型:sub_openid $add_type_num = SharingReceiver::RECEIVE_SUB_OPENID; }*/ // 联盟三级分销 $store_share_setting = Json::decode($store->share_setting); if(!empty($store_share_setting['level']) && $store_share_setting['level_one'] == 0 && $store_share_setting['level_two'] == 0 && $store_share_setting['level_three'] == 0){ $defaultSet = Option::get(OptionSetting::SHARE_SAAS_DEFAULT_SETTING, -1, OptionSetting::SHARE_GROUP_NAME, '{}'); $defaultSet = json_decode($defaultSet['value'], true); if(!empty($defaultSet['level']) && (!empty($defaultSet['level_one']) || !empty($defaultSet['level_two']) || !empty($defaultSet['level_three']))){ $store_share_setting = $defaultSet; } } if (is_array($store_share_setting)) { if ($store_share_setting['level'] > 0) { // 一级 if ($store_share_setting['level'] >= 1 && $store_share_setting['level_one'] > 0) { $saas_user_1_money = floor_num($saas_share_money * ($store_share_setting['level_one'] / 100), 2); if ($order->saas_id > 0) { $share_user_1 = SaasUser::findOne($order->saas_id); } else { $binding = User::findOne(['id' => $order->user_id, 'store_id' => $order->store_id])->binding; $share_user_1 = SaasUser::findOne(['mobile' => $binding]); } if (!$share_user_1) { return; } $share_user_1 = SaasUser::findOne(['id' => $share_user_1->parent_id]); if (!$share_user_1) { return; } //没有分销账户信息的不分账 // $distributionInfo = SaasDistribution::find()->where(['saas_id'=>$share_user_1->id,'is_delete'=>0])->asArray()->one(); // if(empty($distributionInfo) || !isset($distributionInfo['platform_open_id']) || empty($distributionInfo['platform_open_id']) ){ // return; // } $user_1 = User::findOne(['binding' => $share_user_1->mobile, 'store_id' => $order->store_id]); $account_1 = null; $execute_flag = SharingReceiver::EXECUTE_TYPE_NORMAL; // 判断是否为联盟支付 if ($order->is_platform) { //新逻辑 $add_type = WechatShare::RECEIVE_PERSONAL_OPENID; $add_type_num = SharingReceiver::RECEIVE_OPENID; $account_1 = $share_user_1->platform_open_id; } else { $add_type = WechatShare::RECEIVE_PERSONAL_SUB_OPENID; $add_type_num = SharingReceiver::RECEIVE_SUB_OPENID; if ($user_1) {//如果用户存在,则走分账 $account_1 = $user_1->wechat_open_id; } // else {//不存在走联盟转账 // $execute_flag = SharingReceiver::EXECUTE_TYPE_TRANSFER; // $account_1 = $share_user_1->platform_open_id; // } } if ($account_1) { $sharing = SharingReceiver::findOne([ 'store_id' => $order->store_id, 'account' => $account_1, 'order_no' => $order->order_no, 'from' => SharingReceiver::FROM_PLATFORM, 'is_delete' => 0 ]); if ($saas_user_1_money > 0) { $this->saas_user_1_money = $saas_user_1_money; $is_pay = SharingReceiver::PAY_WAIT; if (!$sharing) { $add_res_1 = WechatShare::addReceivers($account_1, WechatShare::RELATION_USER, $add_type, null, false, $order->store_id, $order->is_platform, $order); \Yii::error(['<====== 订单号:' . $order->order_no .' 平台分销一级接收方添加结果 =====>', $add_res_1]); $sharing = new SharingReceiver(); $sharing->store_id = $order->store_id; $sharing->rate = $store_share_setting['level_one']; $sharing->order_no = $order->order_no; $sharing->transaction_id = $order->transaction_id; $sharing->type = $add_type_num; $sharing->from = SharingReceiver::FROM_PLATFORM; $sharing->account = $account_1; $sharing->execute_type = $execute_flag; $sharing->name = $order->is_platform ? $share_user_1->name : ($user_1->nickname ?? $share_user_1->name); // $sharing->user_id = isset($user_1->id) && $user_1->id ? $user_1->id : 0; $sharing->user_id = isset($user_1->id) && $user_1->id ? $user_1->id : 0; $sharing->saas_id = $share_user_1->id ? $share_user_1->id : 0; $sharing->description = '平台分账到个人'; $sharing->is_pay = $is_pay; $sharing->remark = '平台一级分销'; $sharing->is_delete = SharingReceiver::IS_DELETE_NO; $sharing->created_at = time(); $sharing->updated_at = time(); } $sharing->amount = $saas_user_1_money; if (!$sharing->save()) { \Yii::error(['联盟佣金 <====== 订单号:' . $order->order_no .' SAAS 平台一级分账详情, 平台openid:' . $account_1 . ',入库失败 =====>', $sharing->errors[0]]); } } else { SharingReceiver::updateAll(['is_delete' => 1], [ 'store_id' => $order->store_id, 'account' => $account_1, 'order_no' => $order->order_no, 'from' => SharingReceiver::FROM_PLATFORM, 'is_delete' => 0 ]); } } } // 二级 if ($store_share_setting['level'] >= 2 && $store_share_setting['level_two'] > 0) { $saas_user_2_money = floor_num($saas_share_money * ($store_share_setting['level_two'] / 100), 2); if (empty($share_user_1->parent_id)) { return; } $share_user_2 = SaasUser::findOne(['id' => $share_user_1->parent_id]); if (!$share_user_2) { return; } //没有分销账户信息的不分账 // $distributionInfo2 = SaasDistribution::find()->where(['saas_id'=>$share_user_2->id,'is_delete'=>0])->asArray()->one(); // if(empty($distributionInfo2) || !isset($distributionInfo2['platform_open_id']) || empty($distributionInfo2['platform_open_id']) ){ // return; // } // 判断上级是否有分账权限 $share_num_2 = 1; // 分账比例 if ($share_num_2 > 0) { $user_2 = User::findOne(['binding' => $share_user_2->mobile, 'store_id' => $order->store_id]); $account_2 = null; $execute_flag = SharingReceiver::EXECUTE_TYPE_NORMAL; // 判断是否为联盟支付 if ($order->is_platform) { //新逻辑 $add_type = WechatShare::RECEIVE_PERSONAL_OPENID; $add_type_num = SharingReceiver::RECEIVE_OPENID; $account_2 = $share_user_2->platform_open_id; } else { $add_type = WechatShare::RECEIVE_PERSONAL_SUB_OPENID; $add_type_num = SharingReceiver::RECEIVE_SUB_OPENID; if ($user_2) {//如果用户存在,则走分账 $account_2 = $user_2->wechat_open_id; } // else {//不存在走联盟转账 // $execute_flag = SharingReceiver::EXECUTE_TYPE_TRANSFER; // $account_2 = $share_user_2->platform_open_id; // } } if ($account_2) { $sharing = SharingReceiver::findOne([ 'store_id' => $order->store_id, 'account' => $account_2, 'order_no' => $order->order_no, 'from' => SharingReceiver::FROM_PLATFORM, 'is_delete' => 0 ]); if ($saas_user_2_money > 0) { $this->saas_user_2_money = $saas_user_2_money; $is_pay = SharingReceiver::PAY_WAIT; if (!$sharing) { $add_res_2 = WechatShare::addReceivers($account_2, WechatShare::RELATION_USER, $add_type, null, false, $order->store_id, $order->is_platform, $order); \Yii::error(['<====== 订单号:' . $order->order_no .' 平台分销二级接收方添加结果 =====>', $add_res_2]); $sharing = new SharingReceiver(); $sharing->store_id = $order->store_id; $sharing->rate = $store_share_setting['level_two']; $sharing->order_no = $order->order_no; $sharing->transaction_id = $order->transaction_id; $sharing->type = $add_type_num; $sharing->from = SharingReceiver::FROM_PLATFORM; $sharing->account = $account_2; $sharing->execute_type = $execute_flag; $sharing->name = $order->is_platform ? $share_user_2->name : ($user_2->nickname ?? $share_user_2->name); $sharing->user_id = isset($user_2->id) && $user_2->id ? $user_2->id : 0; $sharing->saas_id = $share_user_2->id ? $share_user_2->id : 0; $sharing->description = '平台分账到个人'; $sharing->is_pay = $is_pay; $sharing->is_delete = SharingReceiver::IS_DELETE_NO; $sharing->remark = '平台二级分销'; $sharing->created_at = time(); $sharing->updated_at = time(); } $sharing->amount = $saas_user_2_money; if (!$sharing->save()) { \Yii::error(['联盟佣金 <====== 订单号:' . $order->order_no .' SAAS 平台二级分账详情, 平台openid:' . $account_2 . ',入库失败 =====>', $sharing->errors[0]]); } } else { SharingReceiver::updateAll([ 'is_delete' => 1 ], [ 'store_id' => $order->store_id, 'account' => $account_2, 'order_no' => $order->order_no, 'from' => SharingReceiver::FROM_PLATFORM, 'is_delete' => 0 ]); } } } } // 三级 if ($store_share_setting['level'] >= 3 && $store_share_setting['level_three'] > 0) { $saas_user_3_money = floor_num($saas_share_money * ($store_share_setting['level_three'] / 100), 2); $share_user_3 = SaasUser::findOne(['id' => $share_user_2->parent_id]); if (!$share_user_3) { return; } //没有分销账户信息的不分账 // $distributionInfo3 = SaasDistribution::find()->where(['saas_id'=>$share_user_3->id,'is_delete'=>0])->asArray()->one(); // if(empty($distributionInfo3) || !isset($distributionInfo3['platform_open_id']) || empty($distributionInfo3['platform_open_id']) ){ // return; // } // 判断上级是否有分账权限 $user_3 = User::findOne(['binding' => $share_user_3->mobile, 'store_id' => $order->store_id]); //旧分账逻辑 $account_3 = null; $execute_flag = SharingReceiver::EXECUTE_TYPE_NORMAL; if ($order->is_platform) { //新逻辑 $add_type = WechatShare::RECEIVE_PERSONAL_OPENID; $add_type_num = SharingReceiver::RECEIVE_OPENID; $account_3 = $share_user_3->platform_open_id; } else { $add_type = WechatShare::RECEIVE_PERSONAL_SUB_OPENID; $add_type_num = SharingReceiver::RECEIVE_SUB_OPENID; if ($user_3) {//如果用户存在,则走分账 $account_3 = $user_3->wechat_open_id; } // else {//不存在走联盟转账 // $execute_flag = SharingReceiver::EXECUTE_TYPE_TRANSFER; // $account_3 = $share_user_3->platform_open_id; // } } if ($account_3) { $sharing = SharingReceiver::findOne([ 'store_id' => $order->store_id, 'account' => $account_3, 'order_no' => $order->order_no, 'from' => SharingReceiver::FROM_PLATFORM, 'is_delete' => 0 ]); if ($saas_user_3_money > 0) { $this->saas_user_3_money = $saas_user_3_money; $is_pay = SharingReceiver::PAY_WAIT; if (!$sharing) { $add_res_3 = WechatShare::addReceivers($account_3, WechatShare::RELATION_USER, $add_type, null, false, $order->store_id, $order->is_platform, $order); \Yii::error(['<====== 订单号:' . $order->order_no .' 平台分销三级接收方添加结果 =====>', $add_res_3]); $sharing = new SharingReceiver(); $sharing->store_id = $order->store_id; $sharing->rate = $store_share_setting['level_three']; $sharing->order_no = $order->order_no; $sharing->transaction_id = $order->transaction_id; $sharing->type = $add_type_num; $sharing->from = SharingReceiver::FROM_PLATFORM; $sharing->account = $account_3; $sharing->execute_type = $execute_flag; $sharing->name = $order->is_platform ? $share_user_3->name : ($user_3->nickname ?? $share_user_3->name); // $sharing->user_id = $order->is_platform ? $share_user_3->id : $user_3->id; $sharing->user_id = isset($user_3->id) && $user_3->id ? $user_3->id : 0; $sharing->saas_id = $share_user_3->id ? $share_user_3->id : 0; $sharing->description = '平台分账到个人'; $sharing->is_pay = $is_pay; $sharing->remark = '平台三级分销'; $sharing->is_delete = SharingReceiver::IS_DELETE_NO; $sharing->created_at = time(); $sharing->updated_at = time(); } $sharing->amount = $saas_user_3_money; if (!$sharing->save()) { \Yii::error(['联盟佣金 <====== 订单号:' . $order->order_no .' SAAS 平台三级分账详情, 平台openid:' . $account_3 . ',入库失败 =====>', $sharing->errors[0]]); } } else { SharingReceiver::updateAll([ 'is_delete' => 1 ], [ 'store_id' => $order->store_id, 'account' => $account_3, 'order_no' => $order->order_no, 'from' => SharingReceiver::FROM_PLATFORM, 'is_delete' => 0 ]); } } } } } } /** * saas平台商城间的分销(merchant) * @param Order $order */ private function shareStoreToStore($order) { try { debug_log(['type' => 'shareStoreToStore'], 'orderDetail.log'); // saas平台让利比例 $store = Store::findOne($order->store_id); $saas_transfer_profit = $store->transfer_profit; if ($this->is_scan) { $saas_transfer_profit = $store->scan_transfer_profit; } // 点餐判断 判断订单中是否设置food_flag_id if (isset($order->food_flag_id) && intval($order->food_flag_id) > 0) { $saas_transfer_profit = $store->food_transfer_profit; } // 收银台判断 判断收银订单中是否存在当前订单 if (isset($order->hanging_order_id) && intval($order->hanging_order_id) > 0) { $saas_transfer_profit = $store->cashier_transfer_profit; } // if (isset($order->pay_type) && intval($order->pay_type) === Order::PAY_TYPE_YUNST_WECHAT_PAY) { // $saas_transfer_profit = $store->ratio ?: 0; // } if ($saas_transfer_profit <= 0) { return; } $saas_share_money = round($order->pay_price * $saas_transfer_profit / 100, 2); if(empty($store->store_share_switch)){ return; } if(empty($store->store_share_value)){ $defaultSet = Option::get(OptionSetting::SHARE_STORE_DEFAULT_SETTING, -1, OptionSetting::SHARE_GROUP_NAME, '{}'); $defaultSet = json_decode($defaultSet['value'], true); if(!empty($defaultSet['store_share_switch']) && !empty($defaultSet['store_share_value'])){ $store->store_share_value = $defaultSet['store_share_value']; } if(empty($store->store_share_value)){ return; } } $saas_store_1_money = floor_num($saas_share_money * ($store->store_share_value / 100), 2); if(!isset($order->user_id)){ return; } $user_id = $order->user_id; $user = User::findOne($user_id); $saasUser = SaasUser::findOne(['mobile' => $user->binding]); if(!$saasUser || $saasUser->store_id <= 0){ return; } $store_parent_id = $saasUser->store_id; if ($store_parent_id < 1) { return; } $mch_wechat = WechatConfig::findOne(['store_id' => $store_parent_id]); $execute_flag = SharingReceiver::EXECUTE_TYPE_NORMAL; $remark = '店铺分销佣金';//'商城级一级分销'; $sharing = SharingReceiver::findOne([ 'store_id' => $order->store_id, 'account' => $mch_wechat['mch_id'], 'order_no' => $order->order_no, 'from' => SharingReceiver::FROM_STORE_TO_STORE, 'is_delete' => 0 ]); if ($saas_store_1_money > 0.00) { $this->saas_store_1_money = $saas_store_1_money; if (!$sharing) { $add_res_1 = WechatShare::addReceivers($mch_wechat['mch_id'], WechatShare::RELATION_STORE, WechatShare::RECEIVE_MERCHANT_ID, $mch_wechat['name'], false, $order->store_id, $order->is_platform, $order); \Yii::error(['<====== 订单号:' . $order->order_no .' 商城级分销一级接收方添加结果 =====>', $add_res_1]); $sharing = new SharingReceiver(); $sharing->store_id = $order->store_id; $sharing->rate = $store->store_share_value; $sharing->order_no = $order->order_no; $sharing->transaction_id = $order->transaction_id; $sharing->type = SharingReceiver::RECEIVE_MERCHANT_ID; $sharing->from = SharingReceiver::FROM_STORE_TO_STORE; $sharing->account = $mch_wechat['mch_id']; $sharing->execute_type = $execute_flag; $sharing->name = $mch_wechat['name']; $sharing->user_id = 0; $sharing->description = '分账到商户'; $sharing->to_store_id = $store_parent_id; $sharing->is_pay = SharingReceiver::PAY_WAIT; $sharing->remark = $remark; $sharing->is_delete = SharingReceiver::IS_DELETE_NO; $sharing->created_at = time(); $sharing->updated_at = time(); } $sharing->amount = $saas_store_1_money; if (!$sharing->save()) { \Yii::error(['联盟佣金 <====== 订单号:' . $order->order_no .' SAAS 商城级一级分账详情, 商城mch_id:' . $mch_wechat['mch_id'] . ',入库失败 =====>', $sharing->errors[0]]); } } else { SharingReceiver::updateAll([ 'is_delete' => 1 ], [ 'store_id' => $order->store_id, 'account' => $mch_wechat['mch_id'], 'order_no' => $order->order_no, 'from' => SharingReceiver::FROM_STORE_TO_STORE, 'is_delete' => 0 ]); } } catch (\Exception $e) { \Yii::error(['店铺分销添加分账人失败' . $e->getMessage()]); } } /** * 添加自定义分账接收方 */ private function addCustomReceiver($order) { try { $store = Store::findOne($order->store_id); $saas_transfer_profit = $store->transfer_profit; if ($this->is_scan) { $saas_transfer_profit = $store->scan_transfer_profit; } // 点餐判断 判断订单中是否设置food_flag_id if (isset($order->food_flag_id) && intval($order->food_flag_id) > 0) { $saas_transfer_profit = $store->food_transfer_profit; } // 收银台判断 判断收银订单中是否存在当前订单 if (isset($order->hanging_order_id) && intval($order->hanging_order_id) > 0) { $saas_transfer_profit = $store->cashier_transfer_profit; } if ($saas_transfer_profit <= 0) { return; } $saas_share_money = floor_num($order->pay_price * $saas_transfer_profit / 100, 2); //这里继续走 单个商品退款之后 需要重新计算分账金额 分账金额不足的需要删除 // if ($saas_share_money <= 0) { // return; // } //让利比例金额 - 自购返利 - 联盟分销一级 - 联盟分销二级 - 联盟分销三级 - 商城级一级; // $platform_money = floor_num($saas_share_money - $this->saas_self_money - $this->saas_user_1_money - $this->saas_user_2_money - $this->saas_user_3_money - $this->saas_store_1_money, 2); // if($platform_money <= 0){ // return; // } $platform_money = $saas_share_money; $saas_custom_money = 0; $sharingReceiverCustomList = SharingReceiverCustom::find() ->where(['is_delete' => SharingReceiverCustom::IS_DELETE_NO]) ->andWhere(['OR', [ 'sharing_way' => SharingReceiverCustom::SHARING_WAY_STORE, 'sharing_store_id' => $order->store_id ], [ 'sharing_way' => SharingReceiverCustom::SHARING_WAY_PLATFORM, ] ]) ->andWhere(['>', 'sharing_profit', 0]) ->select('id, name, sharing_type, type_id, sharing_way, sharing_store_id, sharing_profit, extra_saas_user_id') ->asArray()->all(); $execute_flag = SharingReceiver::EXECUTE_TYPE_NORMAL; foreach ($sharingReceiverCustomList as $item) { $sharing_amount = bcdiv(bcmul($saas_share_money, $item['sharing_profit'], 2), 100 ,2); $platform_money = bcsub($platform_money, $sharing_amount, 2); $saas_id = 0; $user_id = 0; if (intval($item['sharing_type']) == SharingReceiverCustom::SHARING_TYPE_USER) { $saasUser = SaasUser::findOne($item['type_id']); $saas_id = $saasUser->id ?? 0; $name = $saasUser->name; if ($order->is_platform) { //新逻辑 $add_type = WechatShare::RECEIVE_PERSONAL_OPENID; $add_type_num = SharingReceiver::RECEIVE_OPENID; $account = $saasUser->platform_open_id; } else { $add_type = WechatShare::RECEIVE_PERSONAL_SUB_OPENID; $add_type_num = SharingReceiver::RECEIVE_SUB_OPENID; $user = User::findOne(['binding' => $saasUser->mobile, 'store_id' => $order->store_id]); $account = $user->wechat_open_id; $user_id = $user->id ?? 0; $name = $user->nickname; } $account_name = null; $relation_type = WechatShare::RELATION_USER; $description = '平台分账到个人:自定义分账接收方'; } else { $account = $item['type_id']; $add_type = WechatShare::RECEIVE_MERCHANT_ID; $name = $account_name = $item['name']; $relation_type = WechatShare::RELATION_STORE; $add_type_num = SharingReceiver::RECEIVE_MERCHANT_ID; $description = '平台分账到商户:自定义分账接收方'; $user_id = $item['extra_saas_user_id']; } $sharing = SharingReceiver::findOne([ 'store_id' => $order->store_id, 'account' => $account, 'order_no' => $order->order_no, 'from' => SharingReceiver::FROM_CUSTOM, 'is_delete' => 0 ]); if ($sharing_amount > 0) { if (!$sharing) { $result = WechatShare::addReceivers($account, $relation_type, $add_type, $account_name, false, $order->store_id, $order->is_platform, $order); \Yii::error(['<====== 订单号:' . $order->order_no .' 自定义分账接收方添加结果 =====>', $result]); $sharing = new SharingReceiver(); $sharing->store_id = $order->store_id; $sharing->rate = $item['sharing_profit']; $sharing->order_no = $order->order_no; $sharing->transaction_id = $order->transaction_id; $sharing->type = $add_type_num; $sharing->from = SharingReceiver::FROM_CUSTOM; $sharing->account = $account; $sharing->execute_type = $execute_flag; $sharing->name = $name; $sharing->user_id = $user_id; $sharing->saas_id = $saas_id; $sharing->description = $description; $sharing->is_pay = SharingReceiver::PAY_WAIT; $sharing->remark = '平台自定义分销'; $sharing->is_delete = SharingReceiver::IS_DELETE_NO; $sharing->created_at = time(); $sharing->updated_at = time(); } $sharing->amount = $sharing_amount; if (!$sharing->save()) { \Yii::error(['联盟佣金 <====== 订单号:' . $order->order_no .' SAAS 平台自定义分账详情, 分账账户:' . $account . ',添加分账失败 =====>', $sharing->errors]); }; } else { SharingReceiver::updateAll(['is_delete' => 1], [ 'store_id' => $order->store_id, 'account' => $account, 'order_no' => $order->order_no, 'from' => SharingReceiver::FROM_CUSTOM, 'is_delete' => 0 ]); } $saas_custom_money = bcadd($saas_custom_money, $sharing_amount, 2); if ($platform_money < 0.01) { return ; } } $this->saas_custom_money = $saas_custom_money; return [ 'code' => 0, 'msg' => '处理完成' ]; } catch (\Exception $e) { debug_log(['message' => $e->getMessage()], '20250310.log'); return [ 'code' => 1, 'msg' => $e->getMessage() ]; } } private function addAgentReceiver($order) { try { debug_log(['start' => '开始添加代理分账'], '20250314.log'); $store = Store::findOne($order->store_id); $saas_transfer_profit = $store->transfer_profit; if ($this->is_scan) { $saas_transfer_profit = $store->scan_transfer_profit; } // 点餐判断 判断订单中是否设置food_flag_id if (isset($order->food_flag_id) && intval($order->food_flag_id) > 0) { $saas_transfer_profit = $store->food_transfer_profit; } // 收银台判断 判断收银订单中是否存在当前订单 if (isset($order->hanging_order_id) && intval($order->hanging_order_id) > 0) { $saas_transfer_profit = $store->cashier_transfer_profit; } if ($saas_transfer_profit <= 0) { return; } $saas_share_money = floor_num($order->pay_price * $saas_transfer_profit / 100, 2); debug_log(['saas_share_money' => $saas_share_money], '20250314.log'); //这里继续走 单个商品退款之后 需要重新计算分账金额 分账金额不足的需要删除 // if ($saas_share_money <= 0) { // return; // } $saas_agent_money = 0; $agency_price_config = Option::get('agency_price_config', 0, 'saas')['value']; $agency_price_config = json_decode($agency_price_config, true) ?: []; $province_percent = $agency_price_config['province_percent'] ?: 0; $city_percent = $agency_price_config['city_percent'] ?: 0; $district_percent = $agency_price_config['district_percent'] ?: 0; $bd_agency_price_config = Option::get('bd_agency_price_config', 0, 'saas')['value']; $bd_agency_price_config = json_decode($bd_agency_price_config, true) ?: []; $bd_agent_percent = $bd_agency_price_config['bd_agent_percent'] ?: 0; $admin_id = null; //查询推广代理 if ($store->salesman_id) { $salesman = Salesman::findOne($store->salesman_id); $admin_id = $salesman->admin_id; } if (empty($admin_id) && $store->admin_id) { $admin_id = $store->admin_id; } //查询当前区域下的代理 或者推广代理 $query = Admin::find()->where(['is_delete' => 0])->andWhere([ 'OR', [ 'AND', [ 'type' => Admin::ADMIN_TYPE_DEFAULT, ], [ 'OR', [ 'area_level' => 3, 'province_id' => $store->province_id, ], [ 'area_level' => 2, 'city_id' => $store->city_id, ], [ 'area_level' => 1, 'district_id' => $store->district_id, ], ] ], [ 'id' => $admin_id, 'type' => Admin::ADMIN_TYPE_BD_AGENT ] ]); debug_log(['sql' => $query->createCommand()->getRawSql()], '20250314.log'); $admin_list = $query->asArray()->all(); debug_log(['admin_list' => $admin_list], '20250314.log'); $execute_flag = SharingReceiver::EXECUTE_TYPE_NORMAL; foreach ($admin_list as $item) { $user_role_name = '推广代理'; $item['area_level'] = intval($item['area_level']); //推广代理 $sharing_profit = $bd_agent_percent; $from = SharingReceiver::FROM_BD_AGENT; //省市县代理 if ($item['type'] === Admin::ADMIN_TYPE_DEFAULT) { $sharing_profit = 0; $from = SharingReceiver::FROM_AREA_AGENT_PROVIDER; //区域代理 if ($item['area_level'] === 3) { //省 $sharing_profit = $province_percent; $user_role_name = '省代理'; } if ($item['area_level'] === 2) { //市 $from = SharingReceiver::FROM_AREA_AGENT_CITY; $sharing_profit = $city_percent; $user_role_name = '市代理'; } if ($item['area_level'] === 1) { //县 $from = SharingReceiver::FROM_AREA_AGENT_DISTRICT; $sharing_profit = $district_percent; $user_role_name = '区代理'; } } $sharing_amount = bcdiv(bcmul($saas_share_money, $sharing_profit, 2), 100 ,2); debug_log(['saas_share_money' => $saas_share_money, 'sharing_profit' => $sharing_profit, 'sharing_amount' => $sharing_amount], '20250314.log'); $saasUser = SaasUser::findOne($item['saas_user_id']); $saas_id = $saasUser->id ?? 0; $name = $saasUser->name; if ($order->is_platform) { //新逻辑 $add_type = WechatShare::RECEIVE_PERSONAL_OPENID; $add_type_num = SharingReceiver::RECEIVE_OPENID; $account = $saasUser->platform_open_id; $user_id = 0; } else { $add_type = WechatShare::RECEIVE_PERSONAL_SUB_OPENID; $add_type_num = SharingReceiver::RECEIVE_SUB_OPENID; $user = User::findOne(['binding' => $saasUser->mobile, 'store_id' => $order->store_id]); $account = $user->wechat_open_id; $user_id = $user->id ?? 0; $name = $user->nickname; } $account_name = null; $relation_type = WechatShare::RELATION_USER; $description = '平台分账到代理_' . $user_role_name; $sharing = SharingReceiver::findOne([ 'store_id' => $order->store_id, 'account' => $account, 'order_no' => $order->order_no, 'from' => $from, 'is_delete' => 0 ]); if ($sharing_amount > 0) { if (!$sharing) { $result = WechatShare::addReceivers($account, $relation_type, $add_type, $account_name, false, $order->store_id, $order->is_platform, $order); \Yii::error(['<====== 订单号:' . $order->order_no .' 代理分账接收方添加结果 =====>', $result]); $sharing = new SharingReceiver(); $sharing->store_id = $order->store_id; $sharing->rate = $sharing_profit; $sharing->order_no = $order->order_no; $sharing->transaction_id = $order->transaction_id; $sharing->type = $add_type_num; $sharing->from = $from; $sharing->account = $account; $sharing->execute_type = $execute_flag; $sharing->name = $name; $sharing->user_id = $user_id; $sharing->saas_id = $saas_id; $sharing->description = $description; $sharing->is_pay = SharingReceiver::PAY_WAIT; $sharing->remark = '平台代理分销'; $sharing->is_delete = SharingReceiver::IS_DELETE_NO; $sharing->created_at = time(); $sharing->updated_at = time(); } $sharing->amount = $sharing_amount; if (!$sharing->save()) { \Yii::error(['联盟佣金 <====== 订单号:' . $order->order_no .' SAAS 平台代理分账详情, 分账账户:' . $account . ',添加分账失败 =====>', $sharing->errors]); } } else { SharingReceiver::updateAll(['is_delete' => 1], [ 'store_id' => $order->store_id, 'account' => $account, 'order_no' => $order->order_no, 'from' => $from, 'is_delete' => 0 ]); } $saas_agent_money = bcadd($saas_agent_money, $sharing_amount, 2); } $this->saas_agent_money = $saas_agent_money; return [ 'code' => 0, 'msg' => '处理完成' ]; } catch (\Exception $e) { debug_log(['message' => $e->getMessage()], '20250310.log'); return [ 'code' => 1, 'msg' => $e->getMessage() ]; } } /** * 推荐关系 * @param Order $order * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException * @throws \GuzzleHttp\Exception\GuzzleException */ public function newSaasRecommendReceiver($order) { // saas平台让利比例 $store = Store::findOne($order->store_id); $saas_transfer_profit = $store->transfer_profit; if ($this->is_scan) { $saas_transfer_profit = $store->scan_transfer_profit; } // 点餐判断 判断订单中是否设置food_flag_id if (isset($order->food_flag_id) && intval($order->food_flag_id) > 0) { $saas_transfer_profit = $store->food_transfer_profit; } // 收银台判断 判断收银订单中是否存在当前订单 if (isset($order->hanging_order_id) && intval($order->hanging_order_id) > 0) { $saas_transfer_profit = $store->cashier_transfer_profit; } // if (isset($order->pay_type) && intval($order->pay_type) === Order::PAY_TYPE_YUNST_WECHAT_PAY) { // $saas_transfer_profit = $store->ratio ?: 0; // } if ($saas_transfer_profit <= 0) { return; } $saas_share_money = floor_num($order->pay_price * $saas_transfer_profit / 100, 2); /***** 推荐关系开始 *****/ $result = SaasStoreReferral::find()->where(['store_id' => $order->store_id, 'is_enable' => 1, 'type' => 1]) ->select(['referral_id', 'referral_rebate'])->asArray()->all(); $user_recommend_money = 0; $defaultSet = Option::get(OptionSetting::SHARE_SAAS_REFERRAL_DEFAULT_SETTING, -1, OptionSetting::SHARE_GROUP_NAME, '{}'); $defaultSet = json_decode($defaultSet['value'], true); if (!empty($result) && is_array($result)) { \Yii::warning($result); foreach ($result as $value) { if(($value['referral_rebate'] == 0) && (!empty($defaultSet['is_enable']) && !empty($defaultSet['referral_rebate']))){ $value['referral_rebate'] = $defaultSet['referral_rebate']; } $user_money = floor_num($saas_share_money * ($value['referral_rebate'] / 100), 2); $user_recommend_money += $user_money; $saas_user = SaasUser::findOne($value['referral_id']); if (!$saas_user) { \Yii::error([$value, $value['referral_id'], '没有$saas_user']); continue; } if ($order->is_platform) { //新逻辑 $add_type = WechatShare::RECEIVE_PERSONAL_OPENID; $add_type_num = SharingReceiver::RECEIVE_OPENID; $account = $saas_user->platform_open_id; $user_id = 0; } else { $add_type = WechatShare::RECEIVE_PERSONAL_SUB_OPENID; $add_type_num = SharingReceiver::RECEIVE_SUB_OPENID; $user = User::findOne(['binding' => $saas_user->mobile, 'store_id' => $order->store_id]); $account = $user->wechat_open_id; $user_id = $user->id ?? 0; } $account_name = null; $relation_type = WechatShare::RELATION_USER; $description = '平台分账到店铺推荐人'; if ($user_money > 0) { $sharing = SharingReceiver::findOne([ 'store_id' => $order->store_id, 'account' => $account, 'order_no' => $order->order_no, 'from' => SharingReceiver::FROM_NEW_STORE_RECOMMEND, 'is_delete' => 0 ]); if (!$sharing) { $WechatShareResult = WechatShare::addReceivers($account, $relation_type, $add_type, $account_name, false, $order->store_id, $order->is_platform, $order); \Yii::error(['<====== 订单号:' . $order->order_no .' 店铺推荐人分账接收方添加结果 =====>', $WechatShareResult]); $sharing = new SharingReceiver(); $sharing->store_id = $order->store_id; $sharing->rate = $value['referral_rebate']; $sharing->order_no = $order->order_no; $sharing->transaction_id = $order->transaction_id; $sharing->type = $add_type_num; $sharing->from = SharingReceiver::FROM_NEW_STORE_RECOMMEND; $sharing->account = $account; $sharing->saas_id = $saas_user->id; $sharing->name = $order->is_platform ? $saas_user->name : $user->nickname; $sharing->user_id = $user_id; $sharing->execute_type = SharingReceiver::EXECUTE_TYPE_NORMAL; $sharing->description = '推荐分账到个人'; $sharing->remark = '店铺推荐人返利';//'商城推荐'; $sharing->is_pay = SharingReceiver::PAY_WAIT; $sharing->is_delete = SharingReceiver::IS_DELETE_NO; $sharing->created_at = time(); $sharing->updated_at = time(); } $sharing->amount = $user_money; if (!$sharing->save()) { \Yii::error(['联盟佣金 <====== 订单号:' . $order->order_no .' SAAS 商城推荐详情, 平台openid:' . $account . ',入库失败 =====>', $sharing->errors[0]]); } } else { SharingReceiver::updateAll([ 'is_delete' => 1 ], [ 'store_id' => $order->store_id, 'account' => $account, 'order_no' => $order->order_no, 'from' => SharingReceiver::FROM_NEW_STORE_RECOMMEND, 'is_delete' => 0 ]); } } $this->saas_recommend_money = $user_recommend_money; } /***** 推荐关系结束 *****/ } /** * @param Order $order * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException * @throws \GuzzleHttp\Exception\GuzzleException */ private function newSaasPlatformReceiver($order) { // saas平台让利比例 $store = Store::findOne($order->store_id); $saas_transfer_profit = $store->transfer_profit; if ($this->is_scan) { $saas_transfer_profit = $store->scan_transfer_profit; } // 点餐判断 判断订单中是否设置food_flag_id if (isset($order->food_flag_id) && intval($order->food_flag_id) > 0) { $saas_transfer_profit = $store->food_transfer_profit; } // 收银台判断 判断收银订单中是否存在当前订单 if (isset($order->hanging_order_id) && intval($order->hanging_order_id) > 0) { $saas_transfer_profit = $store->cashier_transfer_profit; } // if (isset($order->pay_type) && intval($order->pay_type) === Order::PAY_TYPE_YUNST_WECHAT_PAY) { // $saas_transfer_profit = $store->ratio ?: 0; // } if ($saas_transfer_profit <= 0) { //如果分账比例小于等于0,直接解冻商户资金,调用分账接口,上送抽用金额为0,不然自己一直冻结不释放 debug_log('分账给服务商1'); if(in_array($order->pay_type, [Order::PAY_TYPE_YUNST_WECHAT_PAY, Order::PAY_TYPE_YUNST_ALI_PAY])){ $res_yunst = $this->yunstReceiver($order); $orderNoHead = substr($order->order_no, 0, 2); if ($orderNoHead == 'SC'){ $order_info = \app\plugins\scanCodePay\models\Order::findOne($order->id); }else{ $order_info = Order::findOne($order->id); } if ($res_yunst) { debug_log('0佣金分账成功'); $order_info->is_yunst_sharing = 1; }else{ debug_log('0佣金分账失败'); $order_info->is_yunst_sharing = 2; } $order_info->save(); // return; } } $saas_share_money = floor_num($order->pay_price * $saas_transfer_profit / 100, 2); // if ($saas_share_money <= 0.00) { // return; // } $platform_money = floor_num($saas_share_money - $this->saas_self_money - $this->saas_user_1_money - $this->saas_user_2_money - $this->saas_user_3_money - $this->saas_store_1_money - $this->business_saas_self_money - $this->saas_custom_money - $this->saas_agent_money - $this->saas_recommend_money, 2); // if($platform_money <= 0){ // return; // } $sharing = null; /***** 服务商分账开始 *****/ $wechat_config = Option::getSaasWechat(); if (!$this->is_yunst){ $sharing = SharingReceiver::findOne([ 'store_id' => $order->store_id, 'account' => $wechat_config['sp_mch_id'], 'order_no' => $order->order_no, 'from' => SharingReceiver::FROM_SERVICE_PROVIDER, 'is_delete' => 0 ]); if (!$sharing) { $add_res = WechatShare::addReceivers($wechat_config['sp_mch_id'], WechatShare::RELATION_SERVICE_PROVIDER, WechatShare::RECEIVE_MERCHANT_ID, $wechat_config['sp_name'], false, $order->store_id, $order->is_platform, $order); \Yii::error(['<====== 订单号:' . $order->order_no .' SAAS 服务商接收方添加结果 =====>', $add_res]); } } if($platform_money > 0){ if ($this->adapay() || $this->is_b2b() || (isset($add_res['code']) && $add_res['code'] == 0) || $sharing || $this->is_yunst) { if (!$sharing) { $sharing = new SharingReceiver(); $sharing->store_id = $order->store_id; $sharing->rate = $saas_transfer_profit; $sharing->order_no = $order->order_no; $sharing->transaction_id = $order->transaction_id; $sharing->type = SharingReceiver::RECEIVE_MERCHANT_ID; $sharing->from = SharingReceiver::FROM_SERVICE_PROVIDER; $sharing->account = $wechat_config['sp_mch_id']??0; $sharing->name = $wechat_config['sp_name']??0; $sharing->execute_type = SharingReceiver::EXECUTE_TYPE_NORMAL; $sharing->user_id = 0; $sharing->description = '分账到服务商'; $sharing->remark = '服务商'; $sharing->is_pay = SharingReceiver::PAY_WAIT; $sharing->is_delete = SharingReceiver::IS_DELETE_NO; $sharing->created_at = time(); $sharing->updated_at = time(); } $sharing->amount = $platform_money; if (!$sharing->save()) { \Yii::error(['<====== 订单号:' . $order->order_no .' SAAS 服务商分账详情,服务商id: ' . $wechat_config['sp_mch_id'] . ',入库失败 =====>', $sharing->errors[0]]); } } } else { SharingReceiver::updateAll([ 'is_delete' => 1 ], [ 'store_id' => $order->store_id, 'account' => $wechat_config['sp_mch_id'], 'order_no' => $order->order_no, 'from' => SharingReceiver::FROM_SERVICE_PROVIDER, 'is_delete' => 0 ]); } /***** 服务商分账结束 *****/ } /** * 抽用金额为0的情况下调用,解冻商户金额 * @return void */ public function yunstReceiver($order) { $store_id = $order->store_id; $amount =0; //查询协议号 $stroe_cusid = Store::findOne($store_id)->cusid; $merchant =new Merchant(); $param['cusid'] = $stroe_cusid; // $param['cusid'] = '552290050728X3L';//进件商户号 测试用 $param['protocolType'] = '2'; $res = $merchant->protocolStaus($order->store_id,$param); debug_log('我是协议状态查询'); debug_log($res); $protocolNo = ''; if($res['subCode'] == 'SUCCESS'){ debug_log('我是协议号'); debug_log($res['data']['protocolNo']); $protocolNo = $res['data']['protocolNo']; } debug_log('怎么不查了'); debug_log($protocolNo); debug_log($order->pay_price *100); debug_log($amount *100); debug_log($store_id); debug_log('/index.php/yunst/notify/' . $store_id); debug_log('???'); $data["bizOrderNo"] = $order->order_no;//服务商抽佣商户订单号 // $data["bizUserId"] = 'XDQXCJSZPJYB';//卖方 bizUserId 测试用 也就是store_number // $data["authorizedCustId"] = "082207111000028";//被授权方客户号 测试用 $oldConf = Option::get(OptionSetting::SAAS_YUNST_SETTING, 0, 'saas')['value']; if ($oldConf){ $oldConf = json_decode($oldConf, true); $data["bizUserId"] = Store::findOne($store_id)->store_number;//也就是store_number $data['authorizedCustId']= $oldConf['customer_number']; // $authorizedCustId = $merchant_info->sub_mch_id; // $data['bizUserId'] = $store->store_number; // $data['cusid'] = $authorizedCustId; } $data["protocolNo"] = $protocolNo;//协议号 $amount_info = round($order->pay_price *100 - round(($order->pay_price * 0.003),2) *100,2);//100 * 100 - round(100 * 0.003, 2) * 100 = 10000 - 30 = 9970 $data["amount"] = $amount_info;//解冻金额//9970 //平台因为垫付手续费所以扣除手续费 $data["commAmount"] =round($amount *100 - round(($order->pay_price * 0.003),2) *100,2);//抽佣金额30 $data["commRatio"] = '';//抽佣比例 // $data["notifyUrl"] = pay_notify_url('yunst/notify', $store_id);//通知地址 $data["notifyUrl"] = '/index.php/yunst/notify/' . $store_id;//通知地址 $data["remark"] = '';//备注 debug_log('我是分账请求参数'); debug_log($data); $order_yunst = new OrderYunst(); $res_return = $order_yunst->servicerReturnComm($data,$store_id); debug_log('我是yunst分账接口'); debug_log($res_return); if($res_return['subCode'] == 'SUCCESS'){ debug_log($res_return['data']); debug_log($res_return['data']['payStatus']); if (($res_return['data']['payStatus'] == '4') || ($res_return['data']['payStatus'] == '99')){ debug_log('我是yunst分账接口返回'); debug_log($order['id']); debug_log($order->id); return false; }else{ debug_log('我是yunst分账接口返回3'); debug_log($order['id']); debug_log($order->id); debug_log($res_return); return true; ; } }else{ debug_log('我是yunst分账接口返回2'); debug_log($order['id']); debug_log($order->id); debug_log($res_return); return false; } } /** * 点餐回调 */ public function FoodNotify($res) { $order = FoodOrder::findOne([ 'order_no' => $res['out_trade_no'], ]); if (!$order) { return; } if ($order->is_pay == 1) { echo "订单已支付"; return; } $order->is_pay = 1; $order->pay_time = time(); $order->pay_type = $this->pay_type; $order->transaction_id = $res['transaction_id']; if ($order->save()) { try { if ($order->is_use_platform_mch == 1) { $store = Store::findOne($order->store_id); $profit = $order->pay_price * $store->transfer_profit / 100; $price = $order->pay_price - $profit; Store::addMoney($store, $price, '用户点餐下单', $order->id, $order->user_id); } } catch (\Exception $e) { // Todo } //商盟订单 $this->addReceiver($order); sleep(10); $event = new OrderEvent(); $event->wechatProfitSharing($order); // 支付完成之后,相关的操作 $form = new OrderComplete(); $form->order_id = $order->id; $form->order_type = 1; $form->notify(); echo 'success'; return; } else { echo "支付失败"; return; } } /** * 商盟会员卡支付回调 */ public function BusinessMemberOrderNotify($res) { \Yii::error(['<====== 订单号:'.$res['out_trade_no'],'--------------------']); $order = BusinessMemberOrder::findOne([ 'order_no' => $res['out_trade_no'], 'is_delete'=>0 ]); if (!$order) { return; } if ($order->is_pay == 1) { echo "订单已支付"; return; } $time = time(); $order->begin_time = $time; if($order->member_type == 'month'){ $order->end_time = $time + 30 * 24 * 3600; $addTime = 30 * 24 * 3600; }elseif($order->member_type == 'quarter'){ $order->end_time = $time + 90 * 24 * 3600; $addTime = 90 * 24 * 3600; }elseif($order->member_type == 'year'){ $order->end_time = $time + 365 * 24 * 3600; $addTime = 365 * 24 * 3600; }elseif($order->member_type == 'perpetual'){ $order->begin_time = 0; $order->end_time = 0; $addTime = 0; } $order->is_pay = 1; $order->pay_time = time(); $order->pay_type = $this->pay_type; $memberId = $order->member_id; $saas_id = $order->saas_id; if ($order->save()) { $rightInfo = BusinessMember::find()->where(['id'=>$memberId,'is_delete'=>0])->asArray()->one(); // $rightIds = json_decode($rightInfo['right_ids'],true); $rightIds = []; if (strpos($rightInfo['right_ids'], '1') !== false) { $rightIds[] = 1; } if (strpos($rightInfo['right_ids'], '2') !== false) { $rightIds[] = 2; } if (strpos($rightInfo['right_ids'], '3') !== false) { $rightIds[] = 3; } if (strpos($rightInfo['right_ids'], '4') !== false) { $rightIds[] = 4; } if (strpos($rightInfo['right_ids'], '5') !== false) { $rightIds[] = 5; } if (strpos($rightInfo['right_ids'], '6') !== false) { $rightIds[] = 6; } // foreach ($rightIds as $rid) { // $duration = BusinessRightDuration::find()->where(['right_id'=>$rid,'saas_id'=>$saas_id,'is_delete'=>0])->one(); // if($duration->expire_time != 0){ // if($addTime == 0){ // $duration->expire_time = 0; // } // } // } $saasInfo = SaasUser::find()->where(['id'=>$saas_id,'is_delete'=>0])->asArray()->one(); foreach($rightIds as $rid){ //权限时间 $this->rightDuration($saas_id,$rid,$addTime,BusinessRightDuration::FROM_CARD); //如果购买的会员卡有分消提现 if($rid == 2){ if($saasInfo['parent_id'] > 0){ $saas_parent_id = $saasInfo['parent_id']; $level = 1; do { if($level == 1){ if(($rightInfo['commission_one'] > 0) && ($saasInfo['parent_id'] > 0)){ $rebate = sprintf("%.2f", ($rightInfo['commission_one'] / 100) * $order->pay_price ); $source = 1; //一级分账 }else{ break; } } if($level == 2){ if($rightInfo['commission_two'] > 0){ $rebate = sprintf("%.2f", ($rightInfo['commission_two'] / 100) * $order->pay_price ); $source = 2; //二级分账 }else{ break; } } if($level == 3){ if($rightInfo['commission_three'] > 0){ $rebate = sprintf("%.2f", ($rightInfo['commission_three'] / 100) * $order->pay_price ); $source = 3; //三级分账 }else{ break; } } $type = 0; //类型 0--佣金 1--提现 $order->share_price += $rebate; $order->save(); SaasShareMoney::set($rebate,$saas_parent_id, $order->id, $type, $source, 0, 0); $saas_parent_id = $this->saasCommission($saas_parent_id,$rebate); if(!$saas_parent_id || $saas_parent_id <= 0){ break; } $level++; } while($level <=3); } } //招商入驻 if($rid == 3){ // $this->storeInfo($saasInfo,$addTime); } //代理 if($rid == 4){ $this->proxyInfo($saasInfo,$addTime); } //聚合供应链 开通云仓 跟店铺有冲突暂时去掉等需求确定 // if($rid == 6){ // $this->cloudInfo($saasInfo,$addTime); // } } echo 'success'; return; } else { //$t->rollBack(); echo "支付失败"; return; } } public function ptActivityOrderNotify($message) { $order = PtActivityOrder::findOne(['order_no' => $message['out_trade_no']]); if (!$order) { return; } if ($order->is_pay == 1) { echo "订单已支付"; return; } $order->is_pay = 1; $order->pay_time = time(); $order->pay_type = $this->pay_type; $order->trade_status = 0; $order->transaction_id = $message['transaction_id']; if ($order->save()) { if ($order->head_integral > 0) { $res = AccountLog::saveLog($order->user_id, floatval($order->head_integral), AccountLog::TYPE_INTEGRAL, AccountLog::LOG_TYPE_EXPEND, 3, $order->id, "商城拼团开团支付积分,订单号为:{$order->order_no}。"); if (!$res) { debug_log('开团积分不足' . json_encode($res), 'ptOrderLog.log'); } $order->head_integral_status = 1; $order->save(); } //调用消息队列 $pt_number = $order->pt_number ?: $order->id; //判断是团长开团 $is_first_order = false; if ($pt_number === $order->id) { $is_first_order = true; } $order->pt_number && $order = PtActivityOrder::findOne($order->pt_number); $order_detail = PtActivityOrderDetail::find()->where(['order_id' => $pt_number])->select('goods_id, activity_id')->asArray()->one(); if (!empty($order) && !empty($order_detail)) { $pt_activity_goods = PtActivityGoods::findOne([ 'activity_id' => $order_detail['activity_id'], 'goods_id' => $order_detail['goods_id'], 'is_delete' => 0 ]); if ($pt_activity_goods) { $pt_activity = PtActivity::findOne(['id' => $pt_activity_goods->activity_id, 'is_delete' => 0]); if ($pt_activity) { $query = PtActivityOrder::find()->where(['trade_status' => 0, 'is_pay' => 1]) ->andWhere(['OR', ['id' => $pt_number], ['pt_number' => $pt_number]]); if($pt_activity->party_type == 0){ $pt_order = $query->select('id')->column(); if ($pt_activity->party_size <= count($pt_order)) { queue_push(new CreatedPtOrderJob(['order_id' => ($pt_number ?: $order->id)])); } } if($pt_activity->party_type == 1){ $pt_order = $query->all(); $goodsCount = 0; foreach ($pt_order as $o) { $odgc = PtActivityOrderDetail::find()->where(['order_id' => $o['id'], 'is_delete' => 0])->sum('num'); $goodsCount += (int)$odgc; } if($pt_activity->party_goods_count <= $goodsCount){ queue_push(new CreatedPtOrderJob(['order_id' => ($pt_number ?: $order->id)])); } } //判断是团长开团 if ($is_first_order) { $delay = $pt_activity->split_time * 60 * 60; queue_push(new CancelPtOrderJob(['order_id' => $order->id, 'store_id' => $order->store_id]), $delay); } } } } } } //用户添加佣金 private function saasCommission($saas_id,$price){ $saasInfo = SaasUser::findOne(['id' =>$saas_id,'is_delete'=>0]); if(!$saasInfo){ return false; } $saasInfo->price += $price; $saasInfo->total_price += $price; $saasInfo->save(); return isset($saasInfo['parent_id']) ? $saasInfo['parent_id']: 0; } public function AdoptCostOrderNotify ($res){ $t = \Yii::$app->db->beginTransaction(); $order = AdoptCostOrder::findOne([ 'order_no' => $res['out_trade_no'], ]); if ($order->is_pay == 1) { $t->rollBack(); echo "订单已支付"; return; } $order->is_pay = 1; $order->pay_time = time(); $order->pay_type = $this->pay_type; if ($order->order_type == 1) { $order->trade_status = AdoptCostOrder::ORDER_FLOW_NO_SEND; } else{ $order->trade_status = AdoptCostOrder::ORDER_FLOW_CONFIRM; $adopt_order = AdoptOrderInfo::findOne(['order_id' => $order->order_id, 'store_id' => $order->store_id]); if ($adopt_order->pick_method == AdoptOrderInfo::ORDER_FLOW_NO_PICK) { $adopt_order->pick_method = AdoptOrderInfo::ORDER_FLOW_OTHER_PICK; $adopt_order->pick_time = time(); if (!$adopt_order->save()) { $t->rollBack(); echo "支付失败"; return; } } } $order->is_delete = 0; $order->transaction_id = $res['transaction_id']; if ($order->save()) { $t->commit(); $form = new OrderComplete(); $form->order_id = $order->id; $form->order_type = 0; $form->adoptOrderCostNotify(); try { if (\Yii::$app->prod_is_dandianpu() && !Store::hasIncoming($order->store_id)) { $store = Store::findOne($order->store_id); $profit = $order->pay_price * $store->transfer_profit / 100; $price = $order->pay_price - $profit; Store::addMoney($store, $price, '用户认养订单', $order->id, $order->user_id); } } catch (\Exception $e) { // Todo } echo 'success'; return; } else { $t->rollBack(); echo "支付失败"; return; } } //权限时间 private function rightDuration($saas_id,$rid,$addTime,$from = 3){ $duration = BusinessRightDuration::find()->where(['right_id'=>$rid,'saas_id'=>$saas_id,'is_delete'=>0])->one(); if(!$duration){ $duration = new BusinessRightDuration(); $duration->saas_id = $saas_id; $duration->right_id = $rid; $duration->created_at = time(); $duration->expire_time = ($addTime == 0) ? 0 : time()+ $addTime; $duration->is_delete = 0; $duration->from = $from; $duration->save(); }else{ if($duration->expire_time > 0){ $expire_time = $duration->expire_time; //如果已经过期从当前时间开始 if($duration->expire_time <= time()){ $expire_time = time(); } $duration->expire_time = ($addTime == 0) ? 0 : $expire_time + $addTime; $duration->save(); } } } //代理 private function proxyInfo($saasInfo,$addTime){ $proxy = Admin::find()->where(['type'=>Admin::ADMIN_TYPE_DEFAULT,'saas_user_id'=>$saasInfo['id']])->one(); if(!$proxy){ //不存在就创建 $proxy = new Admin(); $proxy->type = Admin::ADMIN_TYPE_BD_AGENT; $proxy->saas_user_id = $saasInfo['id']; $proxy->username = $saasInfo['mobile']."_p"; $proxy->access_token = \Yii::$app->security->generateRandomString(); $proxy->password = \Yii::$app->security->generatePasswordHash(substr($saasInfo['mobile'],-6)); $proxy->mobile = $saasInfo['mobile']; $proxy->expire_time = ($addTime == 0) ? 0 : time()+$addTime; $proxy->save(); }else{ if($proxy->expire_time > 0){ $proxy->expire_time = ($addTime == 0) ? 0 : time()+$addTime; $proxy->save(); } } } //招商入驻 private function storeInfo($saasInfo,$addTime){ //先创建store 用于绑定商户信息 // 判断是否已经存在 //$admin = Admin::find()->where(['type'=>Admin::ADMIN_TYPE_STORE, 'is_delete' => 0,'saas_user_id'=>$saasInfo['id']])->one(); $admin = Admin::find()->where(['type'=>Admin::ADMIN_TYPE_STORE, 'is_delete' => 0,'mobile'=>$saasInfo['mobile']])->one(); if(!$admin){ $admin = new Admin(); $admin->access_token = \Yii::$app->security->generateRandomString(); $admin->username = $saasInfo['mobile']."_s"; $admin->password = \Yii::$app->security->generatePasswordHash(substr($saasInfo['mobile'],-6)); $admin->mobile = $saasInfo['mobile']; $admin->type = Admin::ADMIN_TYPE_STORE; $admin->saas_user_id = $saasInfo['id']; $admin->expire_time = ($addTime == 0) ? 0 : time()+$addTime; $admin->save(); }else{ if($admin->expire_time > 0){ if($admin->expire_time < time() ){ $admin->expire_time = ($addTime == 0) ? 0 : time()+$addTime; }else{ $admin->expire_time = ($addTime == 0) ? 0 : $admin->expire_time + $addTime; } $admin->expire_time = ($addTime == 0) ? 0 : time()+$addTime; $admin->save(); } if($admin->saas_user_id == 0){ $admin->saas_user_id = $saasInfo['id']; $admin->save(); } } $store = Store::find()->where(['name'=>$saasInfo['mobile']."_s",'is_delete' => 0,'admin_id'=>$admin->id])->one(); if(!$store){ $store = new Store(); $store->name = $saasInfo['mobile']."_s"; $store->admin_id = $admin->id; $store->store_admin = $saasInfo['id']; $store->end_time = ($addTime == 0) ? 0 : time()+$addTime; if ($store->save()) { $initStore = new StoreForm(); $initStore->initStorageConfig($store->id); $admin->type_id = $store->id; $admin->store_id = $store->id; $admin->save(); // 设置商城名称 Option::set('name', $saasInfo['mobile']."_s", $store->id, 'store'); // 初始化DIY页面 // 初始化diy模板 $is = NewDiyTemplate::find() ->where([ 'store_id' => $store->id, 'is_delete' => 0, 'type' => 100 ])->asArray()->one(); if (!$is) { $initStore->initDiyTemplate($store->id); } } }else{ if($store->end_time > 0){ if($store->end_time < time() ){ $store->end_time = ($addTime == 0) ? 0 : time()+$addTime; }else{ $store->end_time = ($addTime == 0) ? 0 : $store->end_time+$addTime; } $store->save(); } } } /** * @param Order $order * 微信分账支付回调时添加分账接收方并计算相关分账数额 */ private function getBusiness($saas_id = 0) { $time = time(); // 判断是否有三级分销权限 $share = BusinessRightDuration::find()->where([ 'is_delete' => 0, 'saas_id' => $saas_id, 'right_id' => [1, 2, 3] ])->andWhere([ 'or', [ '>', 'expire_time', $time ], ['expire_time' => 0] ])->asArray()->all(); $share_right = array_unique(array_column($share, 'right_id')); // $self_num = 0; // if (in_array(1, $share_right)) { // $memberInfo = BusinessMemberOrder::find()->where(['saas_id'=>$saas_id, 'is_pay' => 1])->andWhere(['or', ["<=","begin_time", $time], ['begin_time' => 0]])->andWhere(['or', [">","end_time",$time], ['end_time' => 0]])->asArray()->all(); // if(!$memberInfo) { // $self_num = 0; // } else { // $memberIds = array_unique(array_column($memberInfo, 'member_id')); // $memberInfo = BusinessMember::find()->where(['id'=>$memberIds, 'is_delete'=>0, 'give_self' => 1])->asArray()->all(); // //开启自购返利 // if($memberInfo){ // //获取返利比例 // $self_num = max(array_unique(array_column($memberInfo, 'self_info'))); // } // } // } return [ 'is_share' => in_array(2, $share_right) ? 1 : 0, 'self_num' => in_array(1, $share_right) ? 100 : 0, 'shop_referrer' => in_array(3, $share_right) ? 1 : 0, ]; } /** * 抖品信息回调 */ public function videoGoodsShare($order) { try { $video_share = VideoGoodsShare::find()->where(['order_id' => $order->id, 'is_pay' => 0, 'is_send' => 0])->all(); foreach ($video_share as $item) { $item->is_pay = 1; if (!$item->save()) { throw new \Exception(json_encode($item->errors)); } } } catch (\Exception $e) { \Yii::error("抖品分佣回调结果失败" . $e->getMessage()); } } //https://opendocs.alipay.com/open/033p25 //同步券核销状态 public function OrderVoucherUse($model) { try { $coupon = UserCoupon::findOne($model->use_coupon_id); if (empty($coupon['voucher_code_id'])) { return true; } $alipay_code = AlipayVoucherCode::findOne($coupon['voucher_code_id']); $order_voucher = ActivityOrdervoucher::findOne($alipay_code->activity_ordervoucher_id); if (empty($alipay_code) || empty($order_voucher)) { return true; } $order_no = OrderNo::ALIPAY_VOUCHAR_CODE; $data = [ 'activity_id' => $order_voucher->alipay_activity_id, 'biz_dt' => date('Y-m-d H:i:s'), 'voucher_code' => $alipay_code->voucher_code, 'trade_channel' => 'WX_TRADE_CHANNEL', 'trade_no' => $model->alipay_trade_no, 'total_fee' => $model->total_price ]; $form = new AlipayThirdForm(); $result = $form->AlipayMarketingActivityOrdervoucherUse($data); $file_name = \Yii::$app->runtimePath . '/logs/app_order_voucherUse.log'; file_put_contents($file_name, "\r\n" . '[核销结果推送][' . date('Y-m-d H:i:s') . ']' . json_encode($result), FILE_APPEND); if ($result['code'] === 0) { $alipay_code->status = 1; $alipay_code->order_no = $order_no; $alipay_code->save(); } } catch (\Exception $e) { return [ 'code' => 1, 'msg' => $e->getMessage() ]; } } }