PayController.php 6.1 KB
<?php

namespace api\index\controller;

use cmf\controller\HomeBaseController;
use EasyWeChat\Foundation\Application;
use EasyWeChat\Payment\Order;
use think\Db;

/**
 * 微信支付,退款,提现DEMO
 * Class PayController
 * @package app\portal\controller
 */
class PayController extends HomeBaseController
{
    protected $options;

    function _initialize()
    {
        parent::_initialize();
        $this->options = [
            'app_id' => 'wxd7010deb3b696146',
            'secret' => '282f4cc8536523076c9d16af6331ffb6',
            'payment' => [
                'merchant_id' => '1563087351',
                'key' => 'P1GSxsjA4Ts3g6V95FVE49bNQLClGckS',
                'cert_path' => ROOT_PATH.'public/wechat/cert/apiclient_cert.pem', // XXX: 绝对路径!!!!
                'key_path' => ROOT_PATH.'public/wechat/cert/apiclient_key.pem',      // XXX: 绝对路径!!!!
                'notify_url' => '',      // XXX: 绝对路径!!!!
            ]
        ];
    }

    /**
     * 微信支付
     * @param $data
     * @return mixed
     */
    public function index($data)
    {
        $attributes = [
            'trade_type' => 'NATIVE',
            'body' => '废品回收',
            'detail' => '站内充值',
            'out_trade_no' => $data['num'],
            'total_fee' => $data['total']*100, // 单位:分
            'notify_url' => cmf_api_url('index/pay/notify', '', '', true), // 支付结果通知网址,如果不设置则会使用配置里的默认地址
            'openid' => $data['openid'], // trade_type=JSAPI,此参数必传,用户在商户appid下的唯一标识,
        ];
        $order = new Order($attributes);

        $app = new Application($this->options);
        $payment = $app->payment;
        $result = $payment->prepare($order);
        if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS') {
            return $result->code_url;
        } else {
            $this->error('支付参数错误', '', $result);
        }
    }

    /**
     * 支付回调
     * @throws \EasyWeChat\Core\Exceptions\FaultException
     */
    public function notify()
    {
        cache('nnn', 111);
        $app = new Application($this->options);
        $response = $app->payment->handleNotify(function ($notify, $successful) {
            cache('notify', $notify);
            cache('successful', $successful);
            /*这里是支付回调逻辑处理,一下是DEMO*/

            // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
            $out_trade_no=$notify->out_trade_no;
            $order = Db::name('order')->where('num',$out_trade_no)->find();
            if (!$order) { // 如果订单不存在
                return 'Order not exist.'; // 告诉微信,我已经处理完了,订单没找到,别再通知我了
            }
            // 如果订单存在
            // 检查订单是否已经更新过支付状态
            if ($order['pay_time']>0) {
                return true;
            }
            // 用户是否支付成功
            if ($successful) {
                //添加我的积分记录
                $update['pay_time']=time();
                $update['status'] = 2;
                $arr = Db::name('pay')
                    ->where('id',$order['pay_id'])
                    ->field('integral')
                    ->find();
                $res['user_id'] = $order['user_id'];
                $res['total'] = $arr['integral'];
                $res['create_time'] = time();
                $res['type'] = 1;
                Db::name('detail')
                    ->insertGetId($res);
                //修改我的信息中的当前积分
                $list = Db::name('integral')
                    ->where('user_id',$order['user_id'])
                    ->find();
                $now_integral = $list['now_integral'] + $res['total'];
                $add_total = $list['add_total'] + $res['total'];
                Db::name('integral')
                    ->where('user_id',$order['user_id'])
                    ->update(['now_integral'=>$now_integral,'add_total'=>$add_total]);
            } else { // 用户支付失败
                $update['status']=1;
            }
            Db::name('order')->where('num',$out_trade_no)->update($update);

            return true; // 返回处理完成
        });

        $response->send();
    }


    /**
     * 查询订单
     */
    public function checkOrder()
    {
        $app = new Application($this->options);
        $payment = $app->payment;
        $orderNo = "2018080397545210";//商户系统内部的订单号(out_trade_no)
        $result = $payment->query($orderNo);
        var_dump($result);
    }


    /**
     * 生成签名DEMO
     * @return string
     */
    public function getSignatureDemo()
    {
        $timeStamp = time();
        $randomStr = cmf_random_string(8);
        $arithmetic['timeStamp'] = $timeStamp;
        $arithmetic['randomStr'] = $randomStr;
        $signature = arithmetic($arithmetic);
        $notifyParam = array('t' => $timeStamp, 'r' => $randomStr, 's' => $signature);
        $url = url('your url 表达式', $notifyParam, true, true);
        return $url;
    }


    /**
     * 微信提现
     * @param $data
     * @return mixed
     */
    public function tixian($data)
    {
        $app = new Application($this->options);
        $merchantPay = $app->merchant_pay;
        $merchantPayData = [
            'partner_trade_no' => cmf_get_order_sn(), //随机字符串作为订单号,跟红包和支付一个概念。
            'openid' => $data['openid'], //收款人的openid
            'check_name' => 'NO_CHECK',  //文档中有三种校验实名的方法 NO_CHECK OPTION_CHECK FORCE_CHECK
            're_user_name'=>'',     //OPTION_CHECK FORCE_CHECK 校验实名的时候必须提交
            'amount' => (1-0.006)*$data['total']*100,  //单位为分
            'desc' => '提现到零钱',
            'spbill_create_ip' => '192.168.0.1',  //发起交易的IP地址
        ];
        $result = $merchantPay->send($merchantPayData);
        return $result;
    }
}