<?php
/**
 * @copyright   Copyright (c) 2017 https://www.sapixx.com All rights reserved.
 * @license     Licensed (http://www.apache.org/licenses/LICENSE-2.0).
 * @author      pillar<ltmn@qq.com>
 * 支付回调通知
 */
namespace app\allwin\controller\api\v4;
use app\allwin\controller\api\Base;
use app\allwin\model\AllwinEcard;
use app\allwin\model\AllwinEcardOrder;
use app\common\facade\Inform;
use app\common\facade\WechatPay;
use app\allwin\model\Bank;
use app\allwin\model\BankBill;
use filter\Filter;
use Exception;

class Ecardnotify extends Base{

    /**
     * 购买商品通知
     * @return void
     */
    public function goods(){
        try{
            $response = WechatPay::doPay($this->miniapp_id)->handlePaidNotify(function ($message,$fail) {
                $result = AllwinEcardOrder::where(['status'=>0,'paid_at'=>0,'order_no' => Filter::filter_escape($message['out_trade_no'])])->find();
                if (empty($result)) {
                    return true;
                }
                if ($message['return_code'] === 'SUCCESS') {
                    if ($message['result_code'] === 'SUCCESS') {
                        $sub_mchid  = $message['sub_mch_id'] ?? '';
                        $ispay = WechatPay::doPay($this->miniapp_id,false,$sub_mchid)->order->queryByOutTradeNumber($result->order_no);
                        if ($ispay['return_code'] === 'SUCCESS') {
                            if ($ispay['result_code'] === 'SUCCESS') {
                                if ($ispay['trade_state'] === 'SUCCESS') {
                                    AllwinEcardOrder::where(['id' => $result->id])->update(['status' => 1,'paid_at' => 1,'paid_time' => strtotime($ispay['time_end']),'paid_no' => $ispay['transaction_id']]);
                                    //会员卡
                                    $ecard = AllwinEcard::where(['member_miniapp_id' => $this->miniapp_id])->find();
                                    //增加帐单
                                    BankBill::add(['miniapp_id'=>$this->miniapp_id,'store_id' => 0,'money' => -$result->amount,'uid'=>$result->uid,'pay_uid' => $result->uid], '微信支付[购买会员卡]');
                                    //增加积分
                                    Bank::rePoints($this->miniapp_id, $result->user_id,intval($result->amount));
                                    //申请者微信通知
                                    Inform::sms($result->user_id,$this->miniapp_id,['title' =>'业务进展通知','type' => '会员卡','content' =>'您已成功购买'.$ecard['title']]);
                                    return true;
                                }
                            }
                        }
                    }
                }
                return $fail('通信失败,请稍后再通知我');
            });
            $response->send();
        }catch (Exception $e) {
            $this->error('页面不存在');
        }
    }
}