Notify.php 17.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
<?php
namespace app\mobile\controller;

use think\Db;
use app\common\controller\Api;
use app\mobile\model\CourseOrder;
use app\mobile\model\SecretOrder;
use app\mobile\model\ScoreOrder;
use app\mobile\model\PackageOrder;
use app\mobile\model\RechargeOrder;
use app\mobile\model\User;
use addons\qiniu\library\Auth;
use app\common\model\Attachment;

/**
 * 异步接口
 */
class Notify extends Api
{
	protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 课程---------------------------------------------------------------------
     * @ApiInternal
     */
    public function notifyCourse()
    {
        $paytype = $this->request->param('paytype');
        $pay = \addons\epay\library\Service::checkNotify($paytype);
        if (!$pay) {
            echo '签名错误';
            return;
        }
        $data = $pay->verify();
        try {
            $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
            $out_trade_no = $data['out_trade_no'];
            // 处理订单
            $this->handleCourseOrder($out_trade_no,$payamount,$paytype);
        } catch (Exception $e) {
        }
        echo $pay->success();
    }

    /**
     * 课程-零元支付
     * @ApiInternal
     */
    public function notifyCourseZero($out_trade_no,$payamount,$paytype)
    {
        Db::startTrans();
        try {
            $this->handleCourseOrder($out_trade_no,$payamount,$paytype);
            Db::commit();
        } catch (\think\exception\PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
            return false;
        } catch (\think\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
            return false;
        }
        return true;
    }

    /**
     * 课程-处理订单
     * @ApiInternal
     */
    private function handleCourseOrder($out_trade_no,$payamount,$paytype){
        // 处理订单逻辑
        $order = CourseOrder::get(['order_sn'=>$out_trade_no,'pay_price'=>$payamount,'pay_type'=>$paytype]);
//        $order = CourseOrder::get(['order_sn'=>$out_trade_no,'pay_type'=>$paytype]);
        if($order && $order['pay_status'] != '1'){
            $order->save(['pay_status'=>'1','pay_time'=>time()]);
            // 学习人数加1
            Db::name('mobile_course')->where('id',$order['course_id'])->setInc('study_num_real');
        }
        return true;
    }

    /**
     * 密卷-----------------------------------------------------------------------
     * @ApiInternal
     */
    public function notifySecret()
    {
        $paytype = $this->request->param('paytype');
        $pay = \addons\epay\library\Service::checkNotify($paytype);
        if (!$pay) {
            echo '签名错误';
            return;
        }
        $data = $pay->verify();
        try {
            $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
            $out_trade_no = $data['out_trade_no'];

            //处理订单
            $this->handleSecretOrder($out_trade_no,$payamount,$paytype);
        } catch (Exception $e) {
        }
        echo $pay->success();
    }

    /**
     * 密卷-零元支付
     * @ApiInternal
     */
    public function notifySecretZero($out_trade_no,$payamount,$paytype)
    {
        Db::startTrans();
        try {
            $this->handleSecretOrder($out_trade_no,$payamount,$paytype);
            Db::commit();
        } catch (\think\exception\PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
            return false;
        } catch (\think\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
            return false;
        }
        return true;
    }

    /**
     * 密卷-处理订单
     * @ApiInternal
     */
    private function handleSecretOrder($out_trade_no,$payamount,$paytype){
        // 处理订单逻辑
        $order = SecretOrder::get(['order_sn'=>$out_trade_no,'pay_price'=>$payamount,'pay_type'=>$paytype]);
//        $order = SecretOrder::get(['order_sn'=>$out_trade_no,'pay_type'=>$paytype]);
        if($order && $order['pay_status'] != '1'){
            $order->save(['pay_status'=>'1','pay_time'=>time()]);
            // 购买量加1
            Db::name('mobile_secret')->where('id',$order['course_id'])->setInc('buy_num_real');
        }
        return true;
    }

    /**
     * 积分----------------------------------------------------------------------
     * @ApiInternal
     */
    public function notifyScore()
    {
        $paytype = $this->request->param('paytype');
        $pay = \addons\epay\library\Service::checkNotify($paytype);
        if (!$pay) {
            echo '签名错误';
            return;
        }
        $data = $pay->verify();
        try {
            $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
            $out_trade_no = $data['out_trade_no'];

            // 处理订单
            $this->handleScoreOrder($out_trade_no,$payamount,$paytype);
        } catch (Exception $e) {
        }
        echo $pay->success();
    }

    /**
     * 积分-零元支付
     * @ApiInternal
     */
    public function notifyScoreZero($out_trade_no,$payamount,$paytype)
    {
        Db::startTrans();
        try {
            $this->handleScoreOrder($out_trade_no,$payamount,$paytype);
            Db::commit();
        } catch (\think\exception\PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
            return false;
        } catch (\think\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
            return false;
        }
        return true;
    }

    /**
     * 积分-处理订单
     * @ApiInternal
     */
    private function handleScoreOrder($out_trade_no,$payamount,$paytype){
        // 处理订单逻辑
        $order = ScoreOrder::get(['order_sn'=>$out_trade_no,'pay_price'=>$payamount,'pay_type'=>$paytype]);
//        $order = ScoreOrder::get(['order_sn'=>$out_trade_no,'pay_type'=>$paytype]);
        if($order && $order['pay_status'] != '1'){
            $order->save(['pay_status'=>'1','pay_time'=>time()]);
            // 增加积分
            \app\common\model\User::score($order['score'],$order['user_id'],'充值积分');
        }
        return true;
    }

    /**
     * 企业套餐---------------------------------------------------------------------
     * @ApiInternal
     */
    public function notifyPackage()
    {
        $paytype = $this->request->param('paytype');
        $pay = \addons\epay\library\Service::checkNotify($paytype);
        if (!$pay) {
            echo '签名错误';
            return;
        }
        $data = $pay->verify();
        try {
            $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
            $out_trade_no = $data['out_trade_no'];

            // 处理订单逻辑
            $this->handlePackageOrder($out_trade_no,$payamount,$paytype);
        } catch (Exception $e) {
        }
        echo $pay->success();
    }

    /**
     * 企业套餐-零元支付
     * @ApiInternal
     */
    public function notifyPackageZero($out_trade_no,$payamount,$paytype)
    {
        Db::startTrans();
        try {
            $this->handlePackageOrder($out_trade_no,$payamount,$paytype);
            Db::commit();
        } catch (\think\exception\PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
            return false;
        } catch (\think\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
            return false;
        }
        return true;
    }

    /**
     * 企业套餐-处理订单
     * @ApiInternal
     */
    private function handlePackageOrder($out_trade_no,$payamount,$paytype){
        // 处理订单逻辑
        $order = PackageOrder::get(['order_sn'=>$out_trade_no,'pay_price'=>$payamount,'pay_type'=>$paytype]);
//        $order = PackageOrder::get(['order_sn'=>$out_trade_no,'pay_type'=>$paytype]);
        if($order && $order['pay_status'] != '1'){
            $order->save(['pay_status'=>'1','pay_time'=>time()]);
            foreach ($order['package'] as $v){
                // 购买量加1
                Db::name('mobile_package')->where('id',$v['package_id'])->setInc('buy_num_real');
            }
        }
        return true;
    }

    /**
     * 七牛云音频转码通知回调
     * @ApiInternal
     */
    public function notifyQiniuAvthumb()
    {
        if($this->request->isPost()) {
            $arr = $this->request->param();
            // 判断七牛云回调code是否为完成
            if(isset($arr['code']) && $arr['code'] == 0) {
                $url = '/' . $arr['items'][0]['key'];
                $info = Attachment::get(['url'=>$url]);
                if(!$info){
                    $params = array(
                        'admin_id'    => 0,
                        'user_id'     => 0,
                        'filesize'    => 0,
                        'imagewidth'  => 0,
                        'imageheight' => 0,
                        'imagetype'   => 'pcm',
                        'imageframes' => 0,
                        'mimetype'    => 'application/octet-stream',
                        'extparam'    => '',
                        'url'         => $url,
                        'uploadtime'  => time(),
                        'storage'     => 'qiniu'
                    );
                    Attachment::create($params);
                }
                return json(['ret' => 'success', 'code' => 1, 'data' => ['url' => $url]]);
            }
            return json(['ret' => 'failed']);
        }
    }

    /**
     * ios内购支付调试接口
     *
     * @ApiTitle    (ios内购支付调试接口)
     * @ApiSummary  (ios内购支付调试接口)
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="order_sn", type="string", required=true, description="订单号")
     * @ApiParams   (name="apple_receipt", type="string", required=true, description="ios支付成功返回的凭证数据")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
        'code':'1',
        'msg':'返回成功',
        "data": {
        }
    })
     *
     */
    public function iosCheck(){
        // 苹果内购的验证收据,由客户端传过来
        $apple_receipt = input("post.apple_receipt", "");
        $out_trade_no = input("post.order_sn", "");
        $jsonData = ["receipt-data"=>$apple_receipt];

        $jsonData1 = json_encode($jsonData);
        $response = $this->http_post_data($jsonData1, true);
        if($response->status==21007) {
            $response = $this->http_post_data($jsonData1, false);
        }else if ($response->status==21008) {
            $response = $this->http_post_data($jsonData1, true);
        }
        if($response->status == 0){
            // 允许名单数组
            $bundlelist=['com.zhanghao.GMAT'];
            $bundleid= $response->receipt->bundle_id;
            if($bundleid && in_array($bundleid,$bundlelist)) {
                // 最近交易
                if($response->receipt->in_app && !empty($response->receipt->in_app)){
                    // 获取本次购买的信息
                    $in_app = end($response->receipt->in_app);
                    // 产品ID
                    $product_id = $in_app->product_id;
                    if($product_id && !empty($product_id)){
                        // 产品ID数组
                        $productids = [
                            "com.zhanghao.GMAT_12",
                            "com.zhanghao.GMAT_73",
                            "com.zhanghao.GMAT_113",
                            "com.zhanghao.GMAT_288",
                            "com.zhanghao.GMAT_488",
                            "com.zhanghao.GMAT_798"
                        ];
                        if(in_array($product_id, $productids)){
                            // 查询该比交易是否已经成功
                            $transaction_id = $in_app->transaction_id;// 本次购买苹果内购的唯一标识,相当于订单号
                            $transactionWhere['transaction_id'] = $transaction_id;
                            $transactionWhere['pay_status'] = 1;
                            $havePay = RechargeOrder::where($transactionWhere)->find();
                            !empty($havePay) && $this->error('已经支付过了');
                            $haveOrder = RechargeOrder::where('order_sn',$out_trade_no)->find();
                            empty($haveOrder) && $this->error('订单不存在');
                            // 主动购买会有订单号
                            $order = RechargeOrder::where(['order_sn'=>$out_trade_no,'pay_status'=>0])->find();
                            if(!empty($order)){
                                //这里做逻辑处理
                                Db::startTrans();
                                $result = $order->isUpdate(true)->save([
                                    'pay_status' => 1,
                                    'pay_time' => time(),
                                    'transaction_id' => $transaction_id,
                                    'product_id' => $product_id,
                                ]);
                                // 增加用户余额
                                $user = User::field('id,money')->where('id', $order['user_id'])->find();
                                $result_user = User::where('id', $order['user_id'])->setInc('money', $order['money']);
                                // 增加余额变动记录
                                $result_money_log = \app\common\model\MoneyLog::create([
                                    'user_id' => $order['user_id'],
                                    'money' => $order['money'],
                                    'before' => $user['money'],
                                    'after' => $user['money'] + $order['money'],
                                    'memo' => '苹果内购充值余额',
                                    'createtime' => time()
                                ]);
                                if (!$result || !$result_user || !$result_money_log) {
                                    Db::rollback();
                                    $this->error('订单处理失败');
                                }
                                Db::commit();
                            }
                            $this->success('支付成功');
                        } else{
                            $this->error('非法product_id');
                        }
                    }else{
                        $this->error('produce_id不存在伪造充值');
                    }
                }else{
                    $this->error('伪造充值');
                }
            }else{
                $this->error('凭据bundleid不在白名单之内');
            }
        }else{
            $code = $response->status;
            $messagearr[21000] = "App Store无法读取你提供的JSON数据";
            $messagearr[21002] = "收据数据不符合格式";
            $messagearr[21003] = "收据无法被验证";
            $messagearr[21004] = "你提供的共享密钥和账户的共享密钥不一致";
            $messagearr[21005] = "收据服务器当前不可用";
            $messagearr[21006] = "收据是有效的,但订阅服务已经过期。当收到这个信息时,解码后的收据信息也包含在返回内容中";
            $messagearr[21007] = "收据信息是测试用(sandbox),但却被发送到产品环境中验证";
            $messagearr[21008] = "收据信息是产品环境中使用,但却被发送到测试环境中验证";
            $this->error($messagearr[$code]);
        }
    }

    /**
     * curl请求苹果app_store验证地址
     * @param $data_string      验证字符串
     * @param $istest           是否是测试地址 true正式地址 false测试地址
     * @return mixed
     */
    private function http_post_data($data_string, $istest) {
        if ($istest) {
            // 正式验证地址
            $url = 'https://buy.itunes.apple.com/verifyReceipt';
        } else {
            // 测试验证地址
            $url = 'https://sandbox.itunes.apple.com/verifyReceipt';
        }
        $curl_handle=curl_init();
        curl_setopt($curl_handle,CURLOPT_URL, $url);
        curl_setopt($curl_handle,CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl_handle,CURLOPT_HEADER, 0);
        curl_setopt($curl_handle,CURLOPT_POST, true);
        curl_setopt($curl_handle,CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($curl_handle,CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($curl_handle,CURLOPT_SSL_VERIFYPEER, 0);
        $response_json =curl_exec($curl_handle);
        $response =json_decode($response_json);
        curl_close($curl_handle);
        return $response;
    }

}