支付宝当面付与网页支付,一个php文件搞定

最近项目中有使用到支付宝的支付, 原本按照设计,应使用支付宝当面付模块,但是支付宝当面付不能在网站上使用。所以又改用网页支付。以免小伙伴被网上的‘拿来主义’误导。

功能包括:支付宝当面付,支付宝网站支付。

当面付功能均已通过沙盒测试,可放心使用。 TP5框架, 支付类放在extend/payment目录下。


 *
 * @DateTime 2018-11-16 10:43:44
 * 支付宝支付类
 */
class Alipay {

	//是否沙盒环境
	public $is_sandbox = false;
	//沙盒地址
	private $sandurl = 'https://openapi.alipaydev.com/gateway.do';
	//正式地址
	private $url = 'https://openapi.alipay.com/gateway.do';
	//appid
	private $appid ;
	//商户应用私钥
	private $rsaPrivateKey = '商户设置的私钥';

	//支付宝公钥 验签使用
	private $alipayPublicKey= '支付宝自动生成的公钥';

	private $payment_id;

	private $charset = 'utf-8';

	public function __construct(){
		 
		$payment = Db::name('payment')->where('code', 'alipay')->find();
		$json = json_decode($payment['json'], true);
		$this->appid = $json['appid'];
		$this->payment_id = $payment['id'];
		 
	}

	/**
	 * @author     mselect <[email protected]>
	 *
	 * @DateTime 2018-11-16 10:57:51
	 * 发起支付
	 */
	public function pay($order_id){

		$time = time();
		if($this->is_sandbox){
			$url = $this->sandurl;
			$this->appid = '2016092000556490';
			$this->rsaPrivateKey = 'MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCOjfeHwjuAakHIiEbpqGz1aGJQPeOme15v/LFp5Kb8eZ/5kwHLyslGcSizeAIdWK/O80FmvdYOCbcGRMXC2rZ3WT1i4wuHRO0+pWx78gr2AmW7UiKFHQB+XC14AGOywIC/yDPHy7HRdaulx/Hc0PwCZkSE+oMN7aUeg0+eLq0GdGccYlDuhUzHI0liq0OW/sCJaizjW7XXo88TBa+9p1UJQZYhUN1n7W71sk04ipPwd5jhbTlPadS28jqiRE2YZEi/Kv1NHktAzUX61i/XxAUrdYAJ98m+GmqKLIC1aGyzXkuoBRXGyHcKe3JScoEJGHZi7OacK0Dz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4R5m2ja3FmbUq/AKqLHuzw4acoMH4FTJTKFKxf/+/AtRQBawkvat+C4duExwHGKGOyJGPdrwbd1DWmqZZ3hE2zaMT/rTZSjC3M4zi8JBwhKnJN8t6I7Ms07mOv0KQyzMm8Jwchk12bQtBrhAmaxnSTmUbSlC';
			$this->alipayPublicKey = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjo33h8I7gGpByIhG6ahs9WhiUD3jpnteb/yxaeSm/Hmf+ZMBy8rJRnEos3gCHVivzvNBZr3WDgm3BkTFwtq2d1k9YuMLh0TtPqVse/IK9gJlu1IihR0AflwteABjssCAv8gzx8ux0XWrpcfx3ND8AmZEhPqDDe2lHoNPni6tBnRnHGJQ7oVMxyNJYqtDlv7AiWos41u116PPEwWvvadVCUGWIVDdZ+1u9bJNOIqT8HeY4W05T2nUtvI6okRNmGRIvyr9TR5LQM1F+tYv18QFK3WACffJvhpqiiyAtWhss15LqAUVxsh3CntyUnKBCRh2YuzmnCtA88bTjRSCbIdIRQIDAQAB';
		}else {
			$url = $this->url;
		}
		$notify_url = '异步回调';
		$order = Db::name('order')->where('id', $order_id)->find();

		//请求参数的集合 json_encode
		$biz_content = [
			'out_trade_no' => $order['order_unique'],
			//'seller_id' => ''
			'total_amount' => $order['real_total_fee'],
			//'discountable_amount' => '',
			'subject' => $order['body'],
			//'goods_detail' => '',
			//'body' => $order['body'],
			//'operator_id' => '',
			//'store_id' => '',
			//'disable_pay_channels' => '',
			//'enable_pay_channels' => '',
			//'terminal_id'=> '',
			//'extend_params' => '',
			//'timeout_express' => '',
			//'settle_info' => '',
			//'business_params' => '',
			//'qr_code_timeout_express' => '',
 		];

 		//参数
		$param = [
			'app_id' => $this->appid,						//支付宝分配给开发者的应用ID
			'method' => 'alipay.trade.precreate',						//接口名称
			//'format' => 'JSON',						//紧支持JSON
			'charset' => 'utf-8',					//请求使用的编码格式
			'sign_type' => 'RSA2',						//商户生成签名字符串所使用的签名算法类型,目前支持RSA2和RSA,推荐使用RSA2
			'sign' => '',								//商户请求参数的签名串
			'timestamp' => date('Y-m-d H:i:s', $time),							//发送请求的时间,格式"yyyy-MM-dd HH:mm:ss"
			'version' => '1.0',								//调用的接口版本,固定为1.0
			'notify_url' => $notify_url,								//支付宝服务器主动通知商户服务器里指定的页面http/https路径
			//'app_auth_token' => '',						//app_auth_token
			'biz_content' => json_encode($biz_content),							//请求参数的集合,最大长度不限,除公共参数外所有请求参数都必须放在这个参数中传递,具体参照各产品快速接入文档
		];

		//组合生成签名参数
		$signdata = [];
		$signdata['app_id'] = $param['app_id'];
		$signdata['method'] = $param['method'];
		$signdata['charset'] = $param['charset'];
		$signdata['sign_type'] = $param['sign_type'];
		$signdata['timestamp'] = $param['timestamp'];
		$signdata['version'] = $param['version'];
		$signdata['notify_url'] = $param['notify_url'];
		$signdata['biz_content'] = $param['biz_content'];
		//生成签名
		$sign = $this->generateSign($signdata, 'RSA2');
		$param['sign'] = $sign;

		$content = $this->curlPost($url,$param);
		//file_put_contents('alipay.log', $content, FILE_APPEND);
		$return  = json_decode($content, true);
		
		$return = $return['alipay_trade_precreate_response'];
		if($return['code'] == 10000){
			$out_trade_no = $return['out_trade_no'];
			if($out_trade_no != $order['order_unique']){
				return ['code' => -1, 'msg' => '返回订单号错误'];
			}

			//生成成功
			$qr_code = $return['qr_code'];
			$data = [];
			$data['order_id'] = $order_id;
			$data['code_url'] = $qr_code;
			return ['code' => 1 , 'msg' => '成功' , 'data' => $data];

		}else {
			file_put_contents('alipay.log', 'err code:' . $return['code'] . ', err msg:' . $return['msg'] . '\r\n', FILE_APPEND);
			return ['code' => -1 , 'msg' => 'err_code:' . $return['code'] . ',err_msg:' . $return['msg']];
		}

	}


	/**
	 * @author     mselect <[email protected]>
	 *
	 * @DateTime 2018-11-16 13:36:17 { function_description }
	 * 支付宝支付通知
	 *
	 * @param        $data   The data
	 */
	public function notify($data){

		//验签
		//组合验签数据
		$param = $data;
		unset($param['sign']);
		unset($param['sign_type']);

		$rst = $this->rsaCheck($param, $data['sign'] , $data['sign_type']);
		if($rst){
			//查询订单状态
			$order = Db::name("order")->where('order_unique', $data['out_trade_no'])->where('status', -1)->find();
			if(!empty($order)){	

				//$rst = $this->orderquery($order, 'TRADE_SUCCESS');
				$rst = true;
				if($rst){
					$time = time();
					 Db::startTrans();

						try {
							//修改订单状态
							$order_data = [];
							$order_data['status'] =1;
							$order_data['pay_time'] = $time;
							$order_data['trade_no'] = $data['trade_no'];
							$order_data['payment_id'] = $this->payment_id;
							$rst = Db::name('order')->where('id', $order['id'])->update($order_data);

							if($order['type'] == 1){

								//赛事

								//修改报名用户表状态
								$ordermh =  Db::name('order_match')->where('order_id',$order['id'])->find();
								$rst = Db::name('match_member')->where('id', $ordermh['mhmember_id'])->update(['status'=>1]);

								$match_member = Db::name('match_member')->where('id', $ordermh['mhmember_id'])->find();
								$match = Db::name('match')->where('id', $match_member['match_id'])->find();

								//match 表报名总人数+1
								$rst = Db::name('match')->where('id', $match['id'])->setInc('order_count');
								
								//添加赛事报名记录
								$log_mm = [];
								$log_mm['match_id'] = $match_member['match_id'];
								$log_mm['member_id'] = $match_member['member_id'];
								$log_mm['create_time'] = $time;
								$log_mm['content'] = '[赛事]报名赛事:' .$match['title'] . ', 支付成功';
								$rst = Db::name('log_match_member')->insertGetId($log_mm);

								//添加订单日志
								$log_order = [];
								$log_order['order_id'] = $order['id'];
								$log_order['content'] = "[赛事]报名赛事:" . $match['title'] . ', 支付成功';
								$log_order['create_time'] = $time;
								$rst = Db::name('log_order')->insertGetId($log_order);

								//添加平台资金日志
								$log_money = [];
								$log_money['type'] = $order['venue_id'] == -1 ? 2 : 1;
								$log_money['money'] = $order['real_total_fee'];
								$log_money['content'] = '[赛事] 用户ID:'.$order['member_id'].' , 报名赛事:' . $match['title'] . ', 赛事ID:' . $match['id'] . ', 支付:' . $order['real_total_fee'];
								$rst = Db::name('log_money')->insertGetId($log_money);

								if($order['venue_id'] >0 ){
									//添加场馆资金日志
									$lvm = [];
									$lvm['type'] = 2;
									$lvm['venue_id'] = $order['venue_id'];
									$lvm['money'] = $order['real_total_fee'];
									$lvm['content'] = '[赛事] 用户ID:' . $order['member_id'] . ', 报名赛事:' .$match['title'] . ', 赛事ID:' . $match['id'] . ', 支付:' . $order['real_total_fee'];
									$rst = Db::name('log_venue_money')->insertGetId($lvm);
								}
							}else if ($order['type'] == 2){

								//代金券
								//修改用户代金券表
								$ordercp = Db::name('order_coupon')->where('order_id', $order['id'])->find();
								//生成唯一码
								$extra = cmf_create_rand_str(9);
								$rst = Db::name('coupon_member')->where('id', $ordercp['cpnmember_id'])->update(['status' =>1, 'extra'=>$extra ]);
									
								$coupon_member = Db::name('coupon_member')->where('id', $ordercp['cpnmember_id'])->find();
								$coupon = Db::name('venue_coupon')->where('id', $coupon_member['coupon_id'])->find();
								//添加代金券领取记录
								$log_cm = [];
								$log_cm['coupon_id'] = $coupon_member['coupon_id'];
								$log_cm['member_id'] = $coupon_member['member_id'];
								$log_cm['create_time'] = $time;
								$log_cm['content'] = '[代金券]购买代金券:' . $coupon['title'] . ', 已支付';
								$rst = Db::name('log_coupon_member')->insertGetId($log_cm);

								//添加订单记录
								$log_order = [];
								$log_order['order_id'] = $order['id'];
								$log_order['content'] = '[代金券]购买代金券:' . $coupon['title'] . ', 已支付' ;
								$log_order['create_time'] = $time;
								$rst = Db::name('log_order')->insertGetId($log_order);

								//添加平台资金日志
								$log_money = [];
								$log_money['type'] = 3;
								$log_money['money'] = $order['real_total_fee'];
								$log_money['content'] = '[代金券]用户ID:' . $order['member_id'] . ', 购买代金券:' .$coupon['title'] . ', 代金券ID:' .$coupon['id'] . ', 支付:' . $order['real_total_fee'];
								$log_money['create_time'] = $time;
								$rst = Db::name('log_money')->insertGetId($log_money);

								if($order['venue_id'] > 0 ){
									//添加场馆资金记录
									$log_vm = [];
									$log_vm['type'] = 1;
									$log_vm['money'] = $order['real_total_fee'];
									$log_vm['content'] = '[代金券]用户ID:' . $order['member_id'] . ', 购买代金券:' .$coupon['title'] . ', 代金券ID:' .$coupon['id'] . ', 支付:' . $order['real_total_fee'];
									$log_vm['create_time'] = $time;
									$rst = Db::name('log_venue_money')->insertGetId($log_vm);
								}

							}

							Db::commit();
						}catch(\Exception $e){
							Db::rollback();
							file_put_contents('alipaynotify.log', '支付通知数据库操作错误:' . $e->getMessage() . '\r\n', FILE_APPEND);
							exit;
						}


						if($order['type'] ==1 ){
							//发送成功短信通知
							$yunxin = new Yunxin;
							$arr = [];
							$arr[] = $match_member['name'];
							$arr[] = $match['title'];
							$arr[] = date("Y年m月d日H:i", $match['mhstart']);
							$arr[] = $match_member['idno'];
							$yunxin->sendSMSTemplate( 9294589, [$match_member['telephone']], $arr);
						}

						echo  "success";exit;
				}else {
					file_put_contents('alipaynotify.log', '查询订单状态错误\r\n', FILE_APPEND);
				}

			}else {
				file_put_contents('alipaynotify.log', '未找到相应订单\r\n' , FILE_APPEND );
				exit;
			}
		}else {
			file_put_contents('alipaynotify.log', '验签失败\r\n' , FILE_APPEND );
			exit;
		}
	}


	/**
	 * @author     mselect <[email protected]>
	 *
	 * @DateTime 2018-11-16 13:39:15
	 * 支付查询接口
	 * 
	 * @param  order  
	 * @param  status  要验证的状态  WAIT_BUYER_PAY-交易创建等待买家付款 TRADE_CLOSED-未付款交易超时关闭或支付完成后全额退款  TRADE_SUCCESS-交易支付成功 TRADE_FINISHED-交易结束不可退款
	 */
	public function orderquery($order , $status){

		$time = time();
		$url = '';
		$biz_content = [
			'out_trade_no' => $order['order_unique'],
			'trade_no' => $order['trade_no'],
			//'org_pid' => '',
		];

		$param = [
			'app_id' => $this->appid,
			'method' => 'alipay.trade.query',
			'charset' => 'utf-8',
			'sign_type' => 'RSA2',
			'sign' => '',
			'timestamp' => date('Y-m-d H:i:s', $time),
			'version' => '1.0',
			'biz_content' => json_encode($biz_content),
		];

		//组合签名数组
		$signdata = [];
		$signdata['app_id'] = $param['app_id'];
		$signdata['method'] = $param['method'];
		$signdata['charset'] = $param['charset'];
		$signdata['sign_type'] = $param['sign_type'];
		$signdata['timestamp'] = $param['timestamp'];
		$signdata['version'] = $param['version'];
		$signdata['biz_content'] = $param['biz_content'];

		//生成签名
		$sign = $this->generateSign($signdata, 'RSA2');
		$param['sign'] = $sign;

		$content = $this->curlPost($url,$param);
		$return  = json_decode($content, true);

		if($return['code'] == 10000){

			if($return['trade_status'] == $status){
				return true;
			}else {
				return false;
			}
		}else {
			return false;
		}
	}

	public function generateSign($params, $signType = "RSA") {
        return $this->sign($this->getSignContent($params), $signType);
    }

     public function getSignContent($params) {
        ksort($params);
        $stringToBeSigned = "";
        $i = 0;
        foreach ($params as $k => $v) {
            if (false === $this->checkEmpty($v) && "@" != substr($v, 0, 1)) {
                // 转换成目标字符集
                $v = $this->characet($v, $this->charset);
                if ($i == 0) {
                    $stringToBeSigned .= "$k" . "=" . "$v";
                } else {
                    $stringToBeSigned .= "&" . "$k" . "=" . "$v";
                }
                $i++;
            }
        }
        unset ($k, $v);
        return $stringToBeSigned;
    }

    /**
     * 转换字符集编码
     * @param $data
     * @param $targetCharset
     * @return string
     */
    function characet($data, $targetCharset) {
        if (!empty($data)) {
            $fileType = $this->charset;
            if (strcasecmp($fileType, $targetCharset) != 0) {
                $data = mb_convert_encoding($data, $targetCharset, $fileType);
                //$data = iconv($fileType, $targetCharset.'//IGNORE', $data);
            }
        }
        return $data;
    }


     /**
     * 校验$value是否非空
     *  if not set ,return true;
     *    if is null , return true;
     **/
    protected function checkEmpty($value) {
        if (!isset($value))
            return true;
        if ($value === null)
            return true;
        if (trim($value) === "")
            return true;
        return false;
    }


    /**
     * @author     mselect <[email protected]>
     *
     * @DateTime 2018-11-16 12:05:26
     * 签名函数
     *
     * @param        $data      The data
     * @param      string  $signType  The sign type
     *
     * @return       ( description_of_the_return_value )
     */
    protected function sign($data, $signType = "RSA") {
        $priKey=$this->rsaPrivateKey;
        $res = "-----BEGIN RSA PRIVATE KEY-----\n" .
            wordwrap($priKey, 64, "\n", true) .
            "\n-----END RSA PRIVATE KEY-----";
        ($res) or die('您使用的私钥格式错误,请检查RSA私钥配置');
        if ("RSA2" == $signType) {
            openssl_sign($data, $sign, $res, version_compare(PHP_VERSION,'5.4.0', '<') ? SHA256 : OPENSSL_ALGO_SHA256); //OPENSSL_ALGO_SHA256是php5.4.8以上版本才支持
        } else {
            openssl_sign($data, $sign, $res);
        }
        $sign = base64_encode($sign);
        return $sign;
    }

    /**
     * @author     mselect <[email protected]>
     *
     * @DateTime 2018-11-16 12:06:12
     * 验签函数
     *
     * @param        $data        The data    带签名数据
     * @param        $sign        The sign	要校对的签名结果
     * @param      string  $type        The type
     *
     * @return       ( description_of_the_return_value )
     */
    public function rsaCheck($data, $sign,$type = 'RSA'){
    	$public_key = $this->alipayPublicKey;
    	$search = [
            "-----BEGIN PUBLIC KEY-----",
            "-----END PUBLIC KEY-----",
            "\n",
            "\r",
            "\r\n"
        ];
        $public_key=str_replace($search,"",$public_key);
        $public_key=$search[0] . PHP_EOL . wordwrap($public_key, 64, "\n", true) . PHP_EOL . $search[1];
        $res=openssl_get_publickey($public_key);
        if($res)
        {
            if($type == 'RSA'){
                $result = (bool)openssl_verify($this->getSignContent($data), base64_decode($sign), $res);
            }elseif($type == 'RSA2'){
                $result = (bool)openssl_verify($this->getSignContent($data), base64_decode($sign), $res,OPENSSL_ALGO_SHA256);
            }
            openssl_free_key($res);
        }else{
            return false;
        }
        return true;
    }

    public function curlPost($url = '', $postData = '', $options = array())
    {
        if (is_array($postData)) {
            $postData = http_build_query($postData);
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30); //设置cURL允许执行的最长秒数
        if (!empty($options)) {
            curl_setopt_array($ch, $options);
        }
        //https请求 不验证证书和host
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }


    /**
     * @author     mselect <[email protected]>
     *
     * @DateTime 2018-11-19 15:03:28
     * PC网站支付
     */
    public function pagepay($order_id){

    	if($this->is_sandbox){
    		$url = $this->sandurl;
			$this->appid = '2016092000556490';
			$this->rsaPrivateKey = 'MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCOjfeHwjuAakHIiEbpqGz1aGJQPeOme15v/LFp5Kb8eZ/5kwHLyslGcSizeAIdWK/O80FmvdYOCbcGRMXC2rZ3WT1i4wuHRO0+pWx78gr2AmW7UiKFHQB+XC14AGOywIC/yDPHy7HRdaulx/Hc0PwCZkSE+oMN7aUeg0+eLq0GdGccYlDuhUzHI0liq0OW/sCJaizjW7XXo88TBa+9p1UJQZYhUN1n7W71sk04ipPwd5jhbTlPadS28jqiRE2YZEi/Kv1NHktAzUX61i/XxAUrdYAJ98m+GmqKLIC1aGyzXkuoBRXGyHcKe3JScoEJGHZi7OacK0DzxtONFIJsh0hFAgMBAAECggEBAI23lNzhu0VuXPd+gwDG74sIurQK0sYu3zN1gupC5b8ZKnByNNbkQjRFSrEgHPoPsLeMHPiGwMYz4j/ZHsEXrU346Y3lKRDQ9QnSaobNmRf4Sipu/OJYcqUr/gfOW07ZESWXYeK+HYid8oZcv5VGLUI1aOjKIn82QXCUGhKnVFuU1+g1o1U7/xRAw5aRA7B3ixZoJD5Ti+ILB5WBtbfALe37EcCmri64ZWAtBnGKNxP9q6gnQkv8GSjv7bwf30nUkPc86IZQ89nftpTSIqTgb9KJa8NGUCdpuylmFcUlLaWuh0fFfx2gDk74qiLvWV9O+smuz9Led3gwMirSOyERMAECgYEA7e4LwMLXf6qhNaeYNESMPYJ1bvSCo1zM4ef4kGTxiKWRVnNUnT1nNkZmz3cXviZ+tvcu4LhlVLPoQfWVOMx3SFndSNNHhIkdXRODx0zieXC1+W+j/tRmo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F+tYv18QFK3WACffJvhpqiiyAtWhss15LqAUVxsh3CntyUnKBCRh2YuzmnCtA88bTjRSCbIdIRQIDAQAB';
    	}else {
    		$url = $this->url;
    	}
    	$order = Db::name('order')->where('id' , $order_id)->find();
    	if($order['type'] ==1 ){
    		
    		$return_url = cmf_url('user/match/mindex', '', true, true);
    	}elseif($order['type'] ==2 ) {
    		$return_url = cmf_url('user/order/index', '', true, true);
    	}
    	$notify_url = '异步回调地址';
    	$time = time();

    	$biz_content = [
    		'out_trade_no' => $order['order_unique'],
    		'product_code' => 'FAST_INSTANT_TRADE_PAY',
    		'total_amount' => $order['real_total_fee'],
    		'subject' => $order['body'],
    		//'body' => '',
    		//'goods_detail' => '',
    		//'passback_params' => '',
    		//'extend_params' => '',
    		//'goods_type' => '',
    		//'timeout_express' => '',
    		//'enable_pay_channels' => '',
    		//'disable_pay_channels' => '',
    		//'auth_token' => '',
    		//'qr_pay_mode' => '',
    		//'qrcode_width' => '',
    	];

    	//生成参数
    	$param = [
    		'app_id' => $this->appid,
    		'method' => 'alipay.trade.page.pay',
    		//'format' => 'JSON',
    		'return_url' => $return_url,
    		'charset' => 'utf-8',
    		'sign_type' => 'RSA2',
    		'sign' => '',
    		'timestamp' => date('Y-m-d H:i:s', $time),
    		'version' => '1.0',
    		'notify_url' => $notify_url,
    		'biz_content' => json_encode($biz_content),
    	];
    	 
    	//组合签名数组
		$signdata = [];
		$signdata['app_id'] = $param['app_id'];
		$signdata['method'] = $param['method'];
		$signdata['return_url'] = $param['return_url'];
		$signdata['charset'] = $param['charset'];
		$signdata['sign_type'] = $param['sign_type'];
		$signdata['timestamp'] = $param['timestamp'];
		$signdata['version'] = $param['version'];
		$signdata['notify_url'] = $param['notify_url'];
		$signdata['biz_content'] = $param['biz_content'];
		$sign = $this->generateSign($signdata, 'RSA2');
		$param['sign'] = $sign;

		$data = [];
		$data['param'] = $param;
		$data['url'] = $url;

		return ['code' => 1 , 'msg' => '成功', 'data' => $data];

    }

}

?>

欢迎访问: http://www.kevink.club 查看更多内容

你可能感兴趣的:(PHP)