Active.php 6.0 KB
<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Activity;
use app\common\model\Card;
use app\common\model\TradeOrder;
use app\common\model\User;
use app\common\model\UserCard;
use EasyWeChat\Factory;
use think\Config;
use think\Db;

/**
 * 活动接口
 * @ApiWeigh (98)
 */
class Active extends Api
{
    protected $noNeedLogin = ['index','notify'];
    protected $noNeedRight = ['*'];

    /**
     * @ApiTitle (活动首页)
     * @ApiMethod (POST)
     * @ApiRoute  (/api/active/index)
     * @ApiReturnParams (name="code", type="integer", required=true, sample="1")
     * @ApiReturnParams (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回")
     * @ApiReturn   ({
    "code":"状态码",
    "msg": "提示消息",
    })
     */
    public function index(){
        $activity = new Activity();
        $card = new Card();
        $data['active'] = collection($activity->order('createtime','desc')->select())->toArray();
        $data['card'] = collection($card->select())->toArray();
        $this->success('获取成功',$data);
    }

    /**
     * 订单支付
     *
     * @ApiTitle    (活动充值)
     * @ApiSummary  (活动充值)
     * @ApiMethod   (POST)
     * @ApiRoute  (/api/active/pay)
     * @ApiParams   (name="card_id", type="integer", required=false, description="卡片ID")
     * @ApiParams   (name="id", type="integer", required=false, description="充值ID(1=1000,2=2000,3=3000)")
     * @ApiParams   (name="money", type="integer", required=false, description="输入金额")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码")
     * @ApiReturnParams   (name="msg", type="string", required=true, description="提示语")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回")
     * @ApiReturn   ({
    "code":"状态码",
    "msg": "提示消息"
    })
     */
    public function pay(){
        $user_id = $this->auth->id;
        $id = $this->request->param('id');
        $card_id = $this->request->param('card_id');
        $money = $this->request->param('money');
        $model = new Card();
        if (!empty($id)){
            //获取当前充值金额的折扣
            $find = $model->where('id',$id)->field('money,discount')->find();
            $pay = round($find['money']*$find['discount'],2);
            $total_fee = $find['money'];
        }else{
            $pay = $money;
            $total_fee = $money;
        }
        $order = new TradeOrder();
        $order_sn = get_order_sn('C');
        $status = 1;
        if ($pay < 0){
            $status = 2;
        }
        $orderdata = [
            'type'=> 1,
            'order_sn'=>$order_sn,
            'user_id'=>$user_id,
            'card_id'=> $card_id,
            'pay_fee'=>$pay,
            'total_fee'=>$total_fee,
            'status'=> $status,
            'createtime'=>time()
        ];
        //halt($orderdata);
        $order->allowField(true)->save($orderdata);
        //dump($res);exit();
        $config = Config::get('wxchat')['pay'];
        //开始掉起微信支付
        $config = [
            // 必要配置
            'app_id'             => $config['app_id'],
            'mch_id'             => $config['mch_id'],
            'key'                => $config['key'],   // API v2 密钥 (注意: 是v2密钥 是v2密钥 是v2密钥)

            'notify_url' => url('notify', '', '', true),     // 你也可以在下单时单独设置来想覆盖它
        ];
        $app = Factory::payment($config);
        $openid=Db::name('third')->where(['user_id'=>$this->auth->id])->value('openid');
        $result = $app->order->unify([
            'body' => '余额充值',
            'out_trade_no' => $order_sn,
            'total_fee' => $pay*100 ,
            'spbill_create_ip' => '123.12.12.123', // 可选,如不传该参数,SDK 将会自动获取相应 IP 地址
            'notify_url' => url('notify', '', '', true),     // 你也可以在下单时单独设置来想覆盖它
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'openid' => $openid,
        ]);
        if ($result['return_code'] === 'SUCCESS' && $result['result_code'] === 'SUCCESS') {
            $jssdk = $app->jssdk;
            $json = $jssdk->bridgeConfig($result['prepay_id'], false);
            $this->success('', $json);
        } else {
            $this->error('支付错误');
        }
    }

    /**
     * @ApiTitle (支付回调)
     */
    public function notify(){
        \think\Log::init([
            'type'  =>  'File',
            'path'  =>  LOG_PATH.'logs/oderpay.log'
        ]);
        $param =input();
        \think\Log::write($param);
        $config = Config::get('wxchat')['pay'];
        //开始掉起微信支付
        $config = [
            // 必要配置
            'app_id'             => $config['app_id'],
            'mch_id'             => $config['mch_id'],
            'key'                => $config['key'],   // API v2 密钥 (注意: 是v2密钥 是v2密钥 是v2密钥)

        ];
        $app = Factory::payment($config);
        $response = $app->handlePaidNotify(function ($message,$fail){
            $out_trade_no = $message['out_trade_no'];
            $order = (new TradeOrder())->where('order_sn',$out_trade_no)->find();
            if (!$order || $order['status'] > 1){
                return true;
            }
            $data['transaction_id'] = $message['transaction_id'];
            $data['pay_type'] = 2;
            $data['paytime'] = time();
            $data['updatetime'] = time();
            $data['status'] = 2;
             $order->save($data,['id'=>$order['id']]);
            $user = new User();
            $memo = '活动充值';
            $userCard = new UserCard();
            $user::money($order['total_fee'],$order['user_id'],$memo,$out_trade_no,2);
            $userCard->setCard($order['id']);
            return true;
        });
        $response->send();
    }


}