微信支付开放接口部分

<?php


namespace app\api\controller;


use alisms\SendSms;
use think\Db;
//use wxappletpay\Pay;

class Index
{

//    const KEY_LENGTH_BYTE = 32;  //ApiV3Key,长度应为32个字节
    const AUTH_TAG_LENGTH_BYTE = 16;

    public function getToken()
    {
        $openId = input("post.openId");
        if (!empty($openId)) {
            if (redis()->exists(md5($openId))) {
                $data['token'] = md5($openId);
                $data['expire'] = redis()->get(md5($openId));

            } else {
                $this->setToken($openId);
                $data['token'] = md5($openId);
                $data['expire'] = redis()->get(md5($openId));
            }
            return jsonSuccess($data);

        } else {
            return jsonFail('非法操作');
        }
    }

    private function setToken($openId)
    {
        $expire = time() + 7200;
        redis()->set(md5($openId), $expire, 3600 * 2);
    }

    //获取小程序openid
    public function WxGetOpenidByCode()
    {
        $code = $_REQUEST['code'];//获取code
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=" . config('WxAppletPay.appid') . "&secret=" . config('WxAppletPay.secret') . "&js_code=$code&grant_type=authorization_code";
        //通过code换取网页授权access_token
        $weixin = file_get_contents($url);
        $jsondecode = json_decode($weixin); //对JSON格式的字符串进行编码
        $array = get_object_vars($jsondecode);//转换成数组
        return jsonSuccess($array);

//
    }
    public function decryptToString($associatedData, $nonceStr, $ciphertext,$aesKey)
    {
        $ciphertext = \base64_decode($ciphertext);
        if (strlen($ciphertext) <= self::AUTH_TAG_LENGTH_BYTE) {
            return false;
        }

        // ext-sodium (default installed on >= PHP 7.2)
        if (function_exists('\sodium_crypto_aead_aes256gcm_is_available') && \sodium_crypto_aead_aes256gcm_is_available()) {
            return \sodium_crypto_aead_aes256gcm_decrypt($ciphertext, $associatedData, $nonceStr, $aesKey);
        }

        // ext-libsodium (need install libsodium-php 1.x via pecl)
        if (function_exists('\Sodium\crypto_aead_aes256gcm_is_available') && \Sodium\crypto_aead_aes256gcm_is_available()) {
            return \Sodium\crypto_aead_aes256gcm_decrypt($ciphertext, $associatedData, $nonceStr, $aesKey);
        }

        // openssl (PHP >= 7.1 support AEAD)
        if (PHP_VERSION_ID >= 70100 && in_array('aes-256-gcm', \openssl_get_cipher_methods())) {
            $ctext = substr($ciphertext, 0, -self::AUTH_TAG_LENGTH_BYTE);
            $authTag = substr($ciphertext, -self::AUTH_TAG_LENGTH_BYTE);

            return \openssl_decrypt($ctext, 'aes-256-gcm', $aesKey, \OPENSSL_RAW_DATA, $nonceStr, $authTag, $associatedData);
        }
        file_put_contents("wxpay.log",json_encode("'AEAD_AES_256_GCM需要PHP 7.1以上或者安装libsodium-php'")."\n\r",FILE_APPEND);
    }


    //支付成功的回调 第二个代码块配置👇
    public function notify_url()
    {
        $result = file_get_contents('php://input'); //input("post.");
//        file_put_contents("wxpay.log",json_encode($result)."\n\r",FILE_APPEND);
//        $headers = array();
//        foreach ($_SERVER as $key => $value) {
//            if ('HTTP_' == substr($key, 0, 5)) {
//                $headers[str_replace('_', '-', substr($key, 5))] = $value;
//            }
//        }
//        file_put_contents("wxheaders.log",json_encode($headers)."\n\r",FILE_APPEND);
        $arr_post = json_decode($result,true);
        $wxpay = config('WxAppletPay');
//解密
        $ciphertext=$this->decryptToString($arr_post['resource']['associated_data'],$arr_post['resource']['nonce'],$arr_post['resource']['ciphertext'],$wxpay['apiv3']);
//转数组
        $restext = json_decode($ciphertext,true);
//
        if(!empty($restext['out_trade_no']) && isset($restext['trade_state']) && $restext['trade_state']=='SUCCESS')
        {
            //成功回调
//            var_dump($restext);
            file_put_contents("wxpayjson.log",json_encode($restext)."\n\r",FILE_APPEND);
            if (db('order')->where(['pay_status' => 1 ,'transaction_id' => $restext['transaction_id'],'order_no' => $restext['out_trade_no']])->value("cardno")) return "SUCCESS";  //return "SUCCESS"  就不会在重复回调
            Db::startTrans();
            try {
                //事务逻辑
                $cardno = db('order')->where('order_no', $restext['out_trade_no'])->value("cardno");
                db('order')->where('order_no', $restext['out_trade_no'])->update(['pay_status' => 1 ,'transaction_id' => $restext['transaction_id']]);
                db('clubinfo')->where('cardno', $cardno)->update(['pay_status' => 1,'transaction_id' => $restext['transaction_id']]);
                Db::commit();
                $smsData = Db::name("order")
                    ->alias("o")
                    ->join('clubinfo c', 'o.cardno=c.cardno')
                    ->join('memberinfo m', 'c.cardno=m.cardno')
                    ->join('cardinfo card', 'c.cardid=card.cardid')
                    ->field('m.phone,m.membername as username,card.cardname as company,c.startdate,c.enddate')
                    ->where(['o.order_no' => $restext['out_trade_no'], 'm.issub' => 0])
                    ->find();
                $phone = $smsData['phone'];
                unset($smsData['phone']);
                $smsData['orderno'] = $restext['out_trade_no'];

                $this->paySuccessSendSms($phone, $smsData);

                $cardno = db('order')->where('order_no', $restext['out_trade_no'])->value("cardno");
                $push_data = db('clubinfo')->where('cardno', $cardno)->find();
                $push_data['member'] = db('memberinfo')->where("cardno", $cardno)->select();
                $send_data['uid'] = "all";
                $send_data['pushType'] = "add";
                $send_data['data'] = $push_data;
                $push = controller("push/Index");
                $push->send_push($send_data);
                http_response_code(200);
                return json(['code' => 'SUCCESS', 'message' => '']);
                //事务提交
            } catch (\Exception $e) {
                trace(request()->url() . ":" . json_encode($e), 'api');
                Db::rollback();
                //事务回滚
            }
            http_response_code(500);
            return json(['code' => "FAIL", 'message' => ''],500);
        }
    }

    public function paySuccessSendSms($mobile, $templateParam)
    {
        //判断是否ajax提交

        //获取mobile参数

        if (!preg_match("/^1[3456789]\d{9}$/", $mobile)) {
            return jsonFail("手机号不正确");
        }

        //实例化类
        $send = new SendSms();
        //调用类里面send方法 send()方法需要俩个参数;
        //发送短信~
        $result = $send->send($mobile, $templateParam, config('AliSms.paySuccessTemplateCode'));
        //是否成功
        if ($result) {
            //返回
            return jsonSuccess('', '发送成功!');
        } else {
            return jsonFail("发送短信失败");
        }

    }

    public function user_play()
    {
        if (request()->isPost()) {
            $postData = input('post.');
            if (empty($postData['cardno'])||empty($postData['membername'])||empty($postData['machine_num'])) return jsonFail('参数错误');
            $find1 = db('card_play_num')->where('cardno', $postData['cardno'])->find();
            $find2 = db('member_play_num')->where('cardno', $postData['cardno'])->where('membername', $postData['membername'])->find();
            if ($find1) {
                $logFind = db('play_log')->where('cardno',$postData['cardno'])->whereTime('c_time', 'today')->find();
                if (!$logFind){
                    db('card_play_num')->where('cardno', $postData['cardno'])->setInc('play_num');
                }

            } else {
                db('card_play_num')->insert(['cardno' => $postData['cardno']]);
            }
            if ($find2) {
                $logFind = db('play_log')->where('cardno',$postData['cardno'])->where('membername', $postData['membername'])->whereTime('c_time', 'today')->find();
                if (!$logFind){
                    db('member_play_num')->where('cardno', $postData['cardno'])->where('membername', $postData['membername'])->setInc('play_num');
                }
            } else {
                db('member_play_num')->insert(['cardno' => $postData['cardno'], 'membername' => $postData['membername']]);
            }
            $result = db('play_log')->insert($postData);
            if ($result) return $this->success();

            return $this->fail();
        }
        return $this->fail();
    }

    public function test()
    {
        $ret = db('play_log')->whereTime('c_time', 'today')->find();
        var_dump(!$ret);
    }

    public function fail($data = null)
    {
        $result = [];
        if (!isset($data['code'])) {
            $result['code'] = 5000;
        } else {
            $result['code'] = $data['code'];
        }
        if (!isset($data['msg'])) {
            $result['msg'] = '失败';
        } else {
            $result['msg'] = $data['msg'];
        }
        if (!isset($data['data'])) {
            $result['data'] = '';
        } else {
            $result['data'] = $data['data'];
        }
        return json($result);
    }

    public function success($data = null)
    {
        $result = [];
        if (!isset($data['code'])) {
            $result['code'] = 10000;
        } else {
            $result['code'] = $data['code'];
        }
        if (!isset($data['msg'])) {
            $result['msg'] = '成功';
        } else {
            $result['msg'] = $data['msg'];
        }
        if (!isset($data['data'])) {
            $result['data'] = '';
        } else {
            $result['data'] = $data['data'];
        }
        return json($result);
    }
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值