像大家写代码经常遇到这种问题都是怎么解决的呢

s4160415

问题描述

以下代码中 , 分别在开始和结尾出现了两次 switch ($paytype) 判断,如何进行优化代码,只需一次判断呢

 public function returnNotify()
    {
        $paytype = $this->request->param('paytype');
        $config = config('pay');
        switch ($paytype) {
            case 'wechat':
                $pay = Pay::wechat($config);
                try {
                    $res = $pay->callback();
                } catch (\Exception $e) {
                    $this->writeJson(0, '验签错误');
                }
                $res = $res->resource;
                $res = $res['ciphertext'];
                $out_trade_no = $res['out_trade_no'];
                $attach = $res['attach'];
                $mchid = $res['mchid'];
                $transaction_id = $res['transaction_id'];
                $openid = $res['payer']['openid'] ?? '';
                break;
            case 'alipay':
                $pay = Pay::alipay($config);
                try {
                    $res = $pay->callback();
                } catch (\Exception $e) {
                    $this->writeJson(0, $e->getMessage());
                }
                $out_trade_no = $res->out_trade_no;
                $attach = $res->passback_params;
                break;
            case 'balance':
                $out_trade_no = $this->request->param('out_trade_no');
                $attach = $this->request->param('attach');
                break;
            default:
                $this->writeJson(0, '支付类型错误');
        }

        switch ($attach) {
            case 'goods':
                $order = GoodsOrders::where(['order_sn' => $out_trade_no, 'status' => 1])->find();
                if (!$order) {
                    $this->writeJson(0, '订单不存在');
                }
                $order->status = 2;
                $order->paytime = time();
                $order->goods->sales += 1;
                if (empty($order->user->first_buy_goods_time)) {
                    //如果是第一次买精品区
                    $order->user->first_buy_goods_time = time();
                    #给自己增加贡献值
                    UserService::changeUserGoodsDevote($order->goods->spec->devote, $order->user_id, '购买精品区商品');
                    if ($order->user->parent) {
                        $parent = $order->user->parent;
                        #给上级反贡献值
                        UserService::changeUserGoodsDevote($order->goods->spec->devote, $parent->id, '好友购买精品商品');
                    }
                }
                if ($order->user->parent) {
                    $parent = $order->user->parent;
                    #给上级反推荐奖
                    if ($parent->goods_quota > 0) {
                        $money = $order->pay_amount * 0.2;
                        if ($money > $parent->goods_quota) {
                            $money = $parent->goods_quota;
                        }
                        UserService::changeUserGoodsQuota(-$money, $parent->id, '精品区推荐分红扣除');
                        UserService::changeUserMoney($money, $parent->id, '精品区推荐奖');
                    }
                }
                #给自己增加精品区分红额度
                UserService::changeUserGoodsQuota($order->goods->spec->quota, $order->user_id, '购买商品奖励');
                $order->together(['goods', 'user'])->save();
                break;
            case 'super':
                $order = SuperOrders::where(['order_sn' => $out_trade_no, 'status' => 1])->find();
                if (!$order) {
                    $this->writeJson(0, '订单不存在');
                }
                $supply_price = 0;
                foreach ($order->detail as $item) {
                    $supply_price += $item->spec->supply_price;
                }
                $order->status = 2;
                $order->supply_price = $supply_price;
                $order->paytime = time();
                #给自己增加优选区分红额度
                UserService::changeUserSuperQuota($order->pay_amount * 1.3, $order->user_id, '购买优选商品');
                if ($order->user->parent) {
                    $parent = $order->user->parent;
                    #给上级反推荐奖
                    UserService::changeUserMoney($order->pay_amount * 0.01, $parent->id, '优选区推荐奖');
                }
                $order->save();
                break;
            case 'shop':
                $order = ShopOrders::where(['order_sn' => $out_trade_no, 'status' => 1])->find();
                if (!$order) {
                    $this->writeJson(0, '订单不存在');
                }
                $order->status = 2;
                $order->paytime = time();
                $order->save();
                #给自己增加消费者分红额度
                UserService::changeUserShopQuota($order->pay_amount * 4, $order->user_id, '购买商家优惠券');
                #增加商家分红额度
                UserService::changeUserShopQuota($order->pay_amount, $order->shop->user_id, '用户购买优惠券');
                #5%分给 商家推广员
                UserService::changeUserMoney($order->pay_amount * 0.05, $order->shop->parent->id, '推广员商铺订单提成');
                #5%分给 推荐人
                UserService::changeUserMoney($order->pay_amount * 0.05, $order->shop->user->parent->id, '下级商铺订单提成');
                break;
            case 'recharge':
                $order = UserRechargeLog::where(['order_sn' => $out_trade_no, 'status' => 1])->find();
                $order->status = 2;
                $order->paytime = time();
                $order->save();
                #增加余额
                UserService::changeUserMoney($order->amount, $order->user_id, ($paytype == 'alipay' ? '支付宝' : '微信') . '充值余额');
                break;
            default:
                $this->writeJson(0, '回调错误');
        }

        switch ($paytype) {
            case 'wechat':
                if ($order->pay_source == 'wechatmini') {
                    #默认发货
                    Platform::uploadShippingInfo($transaction_id, $mchid, $openid);
                }
                $pay->success();
                break;
            case 'alipay':
                $pay->success();
                break;
            case 'balance':
                return true;
            default:
                $this->writeJson(0, '支付类型错误');
        }

    }
265 1 0
1个回答

yuyu

AI的回答
您的代码看起来是一个处理支付通知回调的函数,它根据支付类型和附加信息执行不同的操作。为了优化这段代码,我们可以从以下几个方面进行改进:

  1. 错误处理和日志记录

    • 当前的错误处理只是简单地返回了错误信息,但没有记录日志。在生产环境中,记录日志对于排查问题至关重要。
    • 可以考虑使用统一的错误处理机制,如自定义异常类,以便更好地管理和记录错误信息。
  2. 代码复用

    • 代码中多次使用了类似的查询和更新逻辑,例如查询订单、更新订单状态等。这些操作可以封装成单独的函数或方法,以减少代码重复。
  3. 数据库操作优化

    • 在更新订单状态时,可以考虑使用数据库事务来确保数据的一致性。
    • 如果订单查询和更新操作频繁,可以考虑使用缓存来减少数据库访问次数。
  4. 代码结构和可读性

    • 当前的代码结构较为冗长,可以通过提取方法和使用更清晰的变量名来提高可读性。
    • 尽量避免在代码中直接使用硬编码的字符串或数字,而是使用常量或配置文件来管理这些值。
  5. 安全性

    • 在处理支付回调时,应验证回调数据的完整性和真实性,以防止恶意请求。
    • 对于敏感操作(如修改用户余额),应确保有相应的权限验证和审计机制。

基于以上建议,以下是一个简化后的代码示例,仅作为优化思路的参考:

public function returnNotify()
{
    $paytype = $this->request->param('paytype');
    $config = config('pay');
    $attach = $this->getAttachData($paytype); // 提取附加数据

    if (!$attach) {
        $this->writeJson(0, '回调错误');
        return;
    }

    $order = $this->getOrderByAttach($attach); // 根据附加数据获取订单
    if (!$order) {
        $this->writeJson(0, '订单不存在');
        return;
    }

    $this->updateOrderStatus($order, $paytype); // 更新订单状态

    $this->handleUserQuotaAndMoney($order, $attach); // 处理用户分红和余额

    $this->handlePaySuccess($paytype); // 处理支付成功逻辑

    return true;
}

private function getAttachData($paytype)
{
    // 根据支付类型提取附加数据逻辑...
}

private function getOrderByAttach($attach)
{
    // 根据附加数据获取订单逻辑...
}

private function updateOrderStatus($order, $paytype)
{
    // 更新订单状态逻辑...
}

private function handleUserQuotaAndMoney($order, $attach)
{
    // 处理用户分红和余额逻辑...
}

private function handlePaySuccess($paytype)
{
    // 处理支付成功逻辑...
}

请注意,上述代码仅为示例,并未包含具体的实现细节。在实际优化过程中,您需要根据您的业务逻辑和框架特性进行具体的调整和优化。同时,确保在修改代码后进行充分的测试,以确保功能的正确性和稳定性。

  • 暂无评论
×
🔝