getBalanceByUid($uid); // 判断是不是增减 $scoreUpdate = ['score'=>DB::raw('score+'.$score),'update_time'=>time()]; // 如果是扣减(因为扣减是负数,所以需要转成正数处理) if( $score < 0 ) { // 判断余额 if( $balance < ($score*-1) ) return ['error'=>'积分不足']; // 结果 $scoreUpdate['use_score'] = DB::raw('use_score+'.($score*-1)); } // 积分记录 $Record = (new Record()); // 记录数据组合 $payData['custom_uid'] = $uid; $payData['order_id'] = $orderId; $payData['status'] = 1; $payData['score'] = $score; $payData['balance'] = $balance + $score; $payData['buy_type'] = $buyType; $payData['description'] = $desc ? $desc :((string) $Record->getBuyType($buyType,'name')); $payData['pay_type'] = $payType; $payData['pay_time'] = time(); // 减少用户的余额,增加用户余额支出 $result = $this->updateCustomScore($uid,$scoreUpdate); // 如果支付失败 if( !$result ) return ['error'=>'积分增减失败']; // 写入余额记录 $payId = $Record->add($payData); // 如果支付失败 if( !$payId ) ['error'=>'积分记录失败']; // 告知成功 return $payId; } /** * 获取用户积分余额缓存key * * @param int $uid 用户ID * */ private function getScoreCacheKey($uid){ // 查询数据库获取数据 $key = "custom:score:uid:".$uid; // 返回配置数据 return $key; } /** * 获取用户积分余额信息 * * @param int $uid 用户ID * */ public function getBalanceByUid($uid){ // 查询数据库获取数据 $balance = $this->getCustomScore($uid); // 返回配置数据 return isset($balance['score']) ? $balance['score'] : 0; } /** * 获取用户积分账户余额信息 * 如果没有余额账户,将创建对应的账户 * * @param int $uid 用户ID * * @return array 积分信息 * */ public function getCustomScore($uid){ // 缓存key $key = $this->getScoreCacheKey($uid); // 从缓存读取 $cash = cache($key,[]); // 如果缓存有值的话 if( $cash ) return $cash; // 查询数据 $cash = $this->query()->where([['custom_uid','=',$uid]])->first(['score','use_score']); // 如果没有数据,创建账号 $cash = $cash ? $cash->toArray() : $this->createCustomScore($uid); // 存入缓存6小时 cache([$key=>$cash],now()->addHours(6)); // 返回查询结果 return $cash; } /** * 修改用户积分账户数据 * * @param int $uid 用户ID * @param array $editData 需要修改的数据 * * @return mixed 修改结果 * */ public function updateCustomScore($uid,$editData=[]){ // 尝试执行 try { // 执行修改后返回数据 $result = $this->query()->where([['custom_uid','=',$uid]])->update($editData); // 修改成功后,删除缓存 if( $result ) cache([$this->getScoreCacheKey($uid)=>null],-5); // 返回结果 return $result; } catch (\Throwable $th) { // 如果失败的话,返回默认数据 return 0; } } /** * 创建账号 * * @param int $uid 用户ID * @param array $values 需要修改的数据 * */ public function createCustomScore($uid){ // 如果没有余额信息的话,需要新增账户,默认数据 $cash = ['score'=>0,'use_score'=>0]; // 尝试执行 try { $result = $this->query()->insert(['custom_uid'=>$uid,'insert_time'=>time(),'update_time'=>time()]); // 如果成功 if( $result ) return $cash; } catch (\Throwable $th) { // 如果失败的话,返回默认数据 return $cash; } // 返回用户积分数据,默认都是账户积分为0 return $cash; } }