<?php
/**
 * Created by ${PRODUCT_NAME}
 * User: JianJia.Zhou
 * DateTime: 2021/8/16 23:14
 * @description
 */

namespace App\Http\Controllers;

use App\Models\UserVip;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Exceptions\Exception;

class PaymentController extends Controller
{
    public function notice()
    {
        $app = Factory::payment(config('wechat.payment.default'));
        $response = $app->handlePaidNotify(function ($message, $fail) {
            // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
            $order = UserVip::where('order_id', $message['out_trade_no'])->first();

            if (!$order) { // 如果订单不存在
                return true;
            }
            if ($message['return_code'] === 'SUCCESS') {
                if ($message['result_code'] === 'SUCCESS') {
                    $order->pay_at = time(); // 更新支付时间为当前时间
                    $order->status = 1;
                }elseif ($message['result_code'] === 'FAIL') {
                    $order->status = 2;
                }
            } else {
                return $fail('通信失败，请稍后再通知我');
            }

            $order->save();
            return true;
        });
        return $response;

    }
}
