当前位置: 首页 > 工具软件 > wechat4u.js > 使用案例 >

Thinkphp对接支付宝和微信支付接口封装类

姚洲
2023-12-01

最近开发的一套支付系统,需要对接支付宝和微信支付的主流接口,支付宝有沙箱测试环境和沙箱测试账号,对接非常方便,最想吐槽的就是微信支付,连测试商户账号都不提供,叫你自己申请正式的商户,而且申请非常麻烦,没有正规的企业公司资质,个人开发者根本申请不到。如果不是在公司里上班,建议大家还是别折腾微信支付的了,麻烦!
我的支付接口代码都是整合在extend扩展目录里,这样封装方便后期维护和在其他项目里直接使用:
直接分享代码给大家,里面有详细注释,只要不是很菜的程序员,相信都能看得懂,这里就不多做解释了。

支付宝封装类Alipay.php

<?php
namespace pay;
use \think\Db;
 
/**
 * 支付宝支付类
 */
class Alipay {
	//是否沙盒环境
	private $is_sandbox = false;
	//沙盒地址
	private $sandurl = 'https://openapi.alipaydev.com/gateway.do';
	//正式地址
	private $apiurl  = 'https://openapi.alipay.com/gateway.do';
	//网关地址(设置为公有,外部需要调用)
	public $gateway;
	//支付宝的APPID
	private $appid;
	//应用私钥
	private $rsaPrivateKey = '商户设置的私钥';
	//支付宝公钥
	private $alipayPublicKey= '支付宝自动生成的公钥';
	private $charset = 'utf-8';
	private $scope;
	private $auth_code;
	
	public function setAppid($appid)
    {
        $this->appid = $appid;
    }
	
	public function setRsaPrivateKey($rsaPrivateKey)
    {
        $this->rsaPrivateKey = $rsaPrivateKey;
    }
	
	public function setAlipayPublicKey($alipayPublicKey)
    {
        $this->alipayPublicKey = $alipayPublicKey;
    }
	public function setScope($scope)
    {
        $this->scope = $scope;
    }
	public function setAuthCode($authCode)
    {
        $this->auth_code = $authCode;
    }
	//构造方法
	public function __construct($account=null){
	    if($account!=null){
    		//如果是沙箱测试
    		if($this->is_sandbox){
    			$this->gateway = $this->sandurl;
    			$this->appid = '2021000117612368';
    			$this->rsaPrivateKey ='MIIEowIBAAKCAQEAgAWVzlJRyrsZQyoVSjInQQZa2NtOlhLpH5osB04qB3PglUP5PdObbgBoq5xZFHeYfw7GBQzqKxGsHu3CPB7Y+SZyBZcORDtcMY9Nmul0GMn5hNqM40hpl1TfAbkkXcuSzAZTZ0n3VkRhUYbhphNlcYFFPPjaqhm0o+VJ1SZ8N6lEcvvSVSL89gTcAjlGfFVxanFpWtvu8tAQLuFQoK/B72yFsjbn+TnmW9v34DSiGvRKz4xlw7qFpOVyNxgrmN1JH1IMwkI0fW2juBdSmu3N1oB7ok5D9WgWFqvNkvWfQcnojwaCNa5/gXPKUgsVgU+LsreZa0Gy1K0JDxgGPcjQXwIDAQABAoIBAD3JdEnFtTARKNofn3LVzdg2RvZOshkAO39DG2jTMrmyFXw0+D/8txFaJSpeJSgZqIH6EVwypXnv55Bt08bMZI+rHHDSPNJ1i8NnlF7luWCValXSXRj8w+mDzrW4M3MJY2oQy4QYUMVT71w3qwRKbDVh3JbWzEI4cdSAPygekOkTmtY7C8rg/CKkL1IK8KX8qCSRfMzIH2dKenxffgANxprXVaucf+d/dwbwtcyIRNOYN3cxRrSXPnUNSyUvJ8IJc96zCMLXqU4LmBgI2OvC8t3OPkp35CTUNC/7L9VsTNL1p7NFxVbbAkBXLbbnp7Tcw8PPuEpSJJLOhxvYLGDI/xECgYEAyrH9pB6xxAdnkBLHYn2geWSnAfi+VCq+cfpqLCsffgDl5S5NiE2T2lbOy7uJ1fypjt24jimBhriBf4yqo8CeL/FmD9zw23/wfwXAyixP+UXy3nt6M9DxEG+bFA59hN6XgXCHVMkVCzPC2dmN+DucpXYJdcqaFVTJDm40InE96o0CgYEAobBen5q3KK7mMA8nR0NpLfLGEh+QEAOCUJjHBebLaG3GD3RWk4ScO7hTkH5cFZfM72RpEo6iDuXSCQQu6Tu08RD88LEP6vwOncNwsylJt3yFSvrYq+O2pUXRYsP4ZomzyA55zGCJhGYW/7wG1G0DfXw4EbVB65QqBYT5ICc2QZsCgYEAwVxwoXrijCWgJvGzIQLE7mkVZK0dK/+ms+Z2GHJ+1V4X8bxtHCUdccEz/2iFQgyI2BAtefigZptmdf4D3rjmbsfzXBih8FMpYpNjabpCBIM1AAZ8+idNgCdnogd8uB78Gu/1Oe2lVI1pSRbf9zku4y0qMyM2QDkkn86Dj4PF1BUCgYASkBEM+dI1VX8P3W2A/PhCUjDzO7RqYjy/zAptXwXTQ2cNtymJXhwhrxPI7vjbccYRZdG6U62/UBtA9b39AOHRG0Yuy+Ur8SwsaJezufXAnwceiJX/hfEeIFndoOoPu5dsTF0nXZ3sGVxil8+g67MO4Qf+4HRk+2mnoJCJZHcSKQKBgD7fWkvqEJ27ii5orxRmrVcmHGArOwN/w1nY7vAfWu8kScp/EDhbMWt+AvH2XFZJhmo2wxSkBamFMAK2kKT7WTviTiERF2iPFnv23Lm1shKTiR5Gz2fIfTDFwYyyhHo2qkKsyIntWp1eW/1m1HxU/oHR/uB6MnmG+jjmY7Jz5mxg';
				$this->alipayPublicKey = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAs9AE75V+F242HcN/SlcGUxUNv3zGpXjai4u2ZMkOL1nolr4/v4BGEsE8tLaYq6lecG/of5taQ27WbWXB5PMB3s6emesTEn5yvZPh/HqmKACHi7js+Dtu123J/z0DyCukMm1ZHJe7jT9VEU9w4gIdNi64VxdaRF3ZMT6DXnboUEegyRKGmJc58h+O30P/UYqdCW/Gl+380o80e6Fs0rX33AixkNTRNgnQ3n2er1Nrqan/9sfUCnqqxgpc1+GTT+vyn3x4Xwvch2pRIkcK4BFCrWVVMKVXx/icj1njTVwWm1KYrXDVYrxf4ZLgpMHyW3SfhnXFKuxvSYnvm5EHjxtNEQIDAQAB';
			}else{
    			$this->gateway = $this->apiurl;
    			$this->appid = $account['appid'];
    			$this->rsaPrivateKey = $account['privateKey'];
    			$this->alipayPublicKey = $account['publicKey'];
    		}
	    }
	}
	/**
	 *
	 * 1.发起电脑网站支付
	 * $params 传输的数据
	 */
	public function pcPay($params){
		//商品名称
		$subject=isset($params['subject']) && !empty($params['subject']) ? $params['subject'] : "购买商品";
		//请求参数
        $requestConfigs = array(
            'out_trade_no'=>$params['pay_id'],//唯一标识,订单编号(必须)
            'product_code'=>'FAST_INSTANT_TRADE_PAY',
            'total_amount'=>$params['money'], //付款金额,单位:元
            'subject'=>$subject,  //订单标题
			"timeout_express" =>"5m",//该笔订单允许的最晚付款时间,逾期将关闭交易。取值范围:1m~15d。m-分钟,h-小时,d-天
        );
        $commonConfigs = array(
            //公共参数
            'app_id' => $this->appid,
            'method' => 'alipay.trade.page.pay',//接口名称
            'format' => 'JSON',
            'return_url' => $params['return_url'],//同步通知地址
            'charset'=>$this->charset,
            'sign_type'=>'RSA2',
            'timestamp'=>date('Y-m-d H:i:s'),
            'version'=>'1.0',
            'notify_url' => $params['notify_url'],//异步通知地址
            'biz_content'=>json_encode($requestConfigs),
        );
        $commonConfigs["sign"] = $this->generateSign($commonConfigs, $commonConfigs['sign_type']);
        return $this->buildRequestForm($this->gateway,$commonConfigs);
	}
	/**
	 *
	 * 2.发起手机网站支付
	 * $params 传输的数据
	 */
	public function wapPay($params){
		//商品名称
		$subject=isset($params['subject']) && !empty($params['subject']) ? $params['subject'] : "购买商品";
		//请求参数
        $requestConfigs = array(
            'out_trade_no'=>$params['pay_id'],//唯一标识,订单编号(必须)
            'product_code'=>'QUICK_WAP_WAY',
            'total_amount'=>$params['money'], //付款金额,单位:元
            'subject'=>$subject,  //订单标题
			"timeout_express" =>"5m",//该笔订单允许的最晚付款时间,逾期将关闭交易。取值范围:1m~15d。m-分钟,h-小时,d-天
        );
        $commonConfigs = array(
            //公共参数
            'app_id' => $this->appid,
            'method' => 'alipay.trade.wap.pay',//接口名称
            'format' => 'JSON',
            'return_url' => $params['return_url'],//同步通知地址
            'charset'=>$this->charset,
            'sign_type'=>'RSA2',
            'timestamp'=>date('Y-m-d H:i:s'),
            'version'=>'1.0',
            'notify_url' => $params['notify_url'],//异步通知地址
            'biz_content'=>json_encode($requestConfigs),
        );
        $commonConfigs["sign"] = $this->generateSign($commonConfigs, $commonConfigs['sign_type']);
        return $commonConfigs;
	}
	/**
	 *
	 * 3.发起当面付
	 * $params 传输的数据
	 */
	public function facePay($params){
		//商品名称
		$subject=isset($params['subject']) && !empty($params['subject']) ? $params['subject'] : "购买商品";
		//请求参数的集合,参考https://mp.csdn.net/editor/html/113599448
		$biz_content = [
			"scene" => "bar_code",//支付场景 条码支付,取值:bar_code 声波支付,取值:wave_code(必须)
			"out_trade_no" => $params['pay_id'],//唯一标识,订单编号(必须)
			//"auth_code" => $params['auth_code'],//支付授权码(商户签约模式时,为必须参数)
			"total_amount" => $params['money'],//订单金额(可选)
			"subject" => $subject,//商品名称
			//"seller_id" => '',	//如果该值为空,则默认为商户签约账号对应的支付宝用户ID	
			"timeout_express" =>"5m",//该笔订单允许的最晚付款时间,逾期将关闭交易。取值范围:1m~15d。m-分钟,h-小时,d-天
 		];
 		//公共请求参数
		$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' => $params['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;
		//echo "<pre>";
		//var_dump($param);die;
		//发起请求
		$content = $this->file_post($this->gateway,$param);
		$alipayData  = json_decode($content, true);	
		//公共响应参数
		$responseData = $alipayData['alipay_trade_precreate_response'];
		if($responseData['code'] == 10000){
			//生成成功,返回结果给前端
			$data = [];
			$data['out_trade_no'] = $responseData['out_trade_no'];
			$data['qr_code'] = $responseData['qr_code'];
			return ['code' => 1 , 'msg' => '成功' , 'data' => $data];
 
		}else {
			//file_put_contents(LOG_PATH .'alipayFacepay.log', 'err code:' . $responseData['code'] . ', err msg:' . $responseData['msg'] . '\r\n', FILE_APPEND);
			return ['code' => 0 , 'msg' => '错误码:' . $responseData['code'] . ',错误信息:' . $responseData['msg']];
		}
	}
	/**
	 *
	 * 4.发起APP付(JSAPI)
	 * $params 传输的数据
	 */
	public function appPay($params){
		//商品名称
		$subject=isset($params['subject']) && !empty($params['subject']) ? $params['subject'] : "购买商品";
		//请求参数
        $requestConfigs = array(
            'out_trade_no'=>$params['pay_id'],//唯一标识,订单编号(必须)
            'total_amount'=>$params['money'], //付款金额,单位:元
            'subject'=>$subject,  //订单标题
            'product_code'=>'QUICK_MSECURITY_PAY', //销售产品码,商家和支付宝签约的产品码,为固定值QUICK_MSECURITY_PAY
            'timeout_express'=>'5m',//该笔订单允许的最晚付款时间,逾期将关闭交易。取值范围:1m~15d。m-分钟,h-小时,d-天,1c-当天(1c-当天的情况下,无论交易何时创建,都在0点关闭)。 该参数数值不接受小数点, 如 1.5h,可转换为 90m。
			//'store_id'=>'', //商户门店编号。该参数用于请求参数中以区分各门店,非必传项。
			//'extend_params'=>array(
			//	'sys_service_provider_id'=>''//系统商编号,该参数作为系统商返佣数据提取的依据,请填写系统商签约协议的PID
			// )
        );
        $commonConfigs = array(
            //公共参数
            'app_id' => $this->appid,
            'method' => 'alipay.trade.app.pay',//接口名称
            'format' => 'JSON',
            'charset'=>$this->charset,
            'sign_type'=>'RSA2',
            'timestamp'=>date('Y-m-d H:i:s'),
            'version'=>'1.0',
            'notify_url' => $params['notify_url'],//异步通知地址
            'biz_content'=>json_encode($requestConfigs),
        );
        $commonConfigs["sign"] = $this->generateSign($commonConfigs, $commonConfigs['sign_type']);
        return http_build_query($commonConfigs);
	} 
	/**
	 *
	 * 5.支付查询接口 
	 * @param  data   支付宝响应的参数集合
	 * @param  status 要验证的状态  
	 * WAIT_BUYER_PAY 交易创建等待买家付款 
	 * TRADE_CLOSED   未付款交易超时关闭或支付完成后全额退款  
	 * TRADE_SUCCESS  交易支付成功 
	 * TRADE_FINISHED 交易结束不可退款
	 */
	public function orderquery($data , $status){
		$biz_content = [
			'out_trade_no' => $data['out_trade_no'],
			'trade_no' => $data['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->file_post($this->gateway,$param);
		$alipayData  = json_decode($content, true);	
		//公共响应参数
		$responseData = $alipayData['alipay_trade_query_response'];
		if($responseData['code'] == 10000){
			if($responseData['trade_status'] == $status){
				return true;
			}else {
				return false;
			}
		}else {
			return false;
		}
	}
	/**
     * 6.获取用户信息
     * @return array
     */
    public function doGetUserInfo($token)
    {
        $commonConfigs = array(
            //公共参数
            'app_id' => $this->appid,
            'method' => 'alipay.user.info.share',//接口名称
            'format' => 'JSON',
            'charset'=>$this->charset,
            'sign_type'=>'RSA2',
            'timestamp'=>date('Y-m-d H:i:s'),
            'version'=>'1.0',
            'auth_token'=>$token,
        );
        $commonConfigs["sign"] = $this->generateSign($commonConfigs, $commonConfigs['sign_type']);
        $result = $this->file_post('https://openapi.alipay.com/gateway.do?charset='.$this->charset,$commonConfigs);
        return json_decode($result,true);
    }
	/**
	 * 支付宝异步通知
	 * @param $data 通知的数据
	 */
	public function notify($data){
		$falg=false;
		$param = $data;
		//不参与签名
		unset($param['sign']);
		unset($param['sign_type']);
		$rst = $this->rsaCheck($param, $data['sign'] , $data['sign_type']);
		if(!$rst){
			//file_put_contents(LOG_PATH .'alipaynotify.log', '验签失败\r\n' , FILE_APPEND );
			return false;
		}
		//查询支付订单状态
		try{
			$rst = $this->orderquery($data, 'TRADE_SUCCESS');
		} catch (\Exception $e) {
			//printLog("查询支付订单状态失败:".$e);
		}
		if($rst){
			$falg=true;
		}else {
			//file_put_contents(LOG_PATH .'alipaynotify.log', '查询订单状态错误\r\n', FILE_APPEND);
			$falg=false;
		}
		return $falg;
	}
	/**
     * 获取access_token和user_id
     * @return array
     */
    public function doAuth()
    {
        $commonConfigs = array(
            //公共参数
            'app_id' => $this->appid,
            'method' => 'alipay.system.oauth.token',//接口名称
            'format' => 'JSON',
            'charset'=>$this->charset,
            'sign_type'=>'RSA2',
            'timestamp'=>date('Y-m-d H:i:s'),
            'version'=>'1.0',
            'grant_type'=>'authorization_code',
            'code'=>$this->auth_code,
        );
        $commonConfigs["sign"] = $this->generateSign($commonConfigs, $commonConfigs['sign_type']);
        $result = $this->file_post('https://openapi.alipay.com/gateway.do?charset='.$this->charset,$commonConfigs);
        return json_decode($result,true);
    }
	/**
     * 获取access_token和user_id
     */
    public function getToken()
    {
        //通过code获得access_token和user_id
        if (!isset($_GET['auth_code'])){
            //触发返回code码
           	$scheme = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']=='on' ? 'https://' : 'http://';
            $baseUrl = urlencode($scheme.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']);
            if($_SERVER['QUERY_STRING']) $baseUrl = $baseUrl.'?'.$_SERVER['QUERY_STRING'];
            $url = $this->createAuthUrlForCode($baseUrl);
            Header("Location: $url");
            exit();
        } else {
            //获取code码,以获取openid
            $this->setAuthCode($_GET['auth_code']);
            return $this->doAuth();
        }
    }
	/**
     * 构造获取token的url连接
     * @param string $redirectUrl 服务器回跳的url,需要url编码
     * @return 返回构造好的url
     */
    protected function createAuthUrlForCode($redirectUrl)
    {
        $urlObj["app_id"] = $this->appid;
        $urlObj["redirect_uri"] = "$redirectUrl";
        $urlObj["scope"] = $this->scope;
        $urlObj["state"] = 123456;
        $bizString = $this->ToUrlParams($urlObj);
        return "https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?".$bizString;
    }
	/**
     * 拼接签名字符串
     * @param array $urlObj
     * @return 返回已经拼接好的字符串
     */
    protected function ToUrlParams($urlObj)
    {
        $buff = "";
        foreach ($urlObj as $k => $v)
        {
            if($k != "sign") $buff .= $k . "=" . $v . "&";
        }
        $buff = trim($buff, "&");
        return $buff;
    }
	protected function generateSign($params, $signType = "RSA") {
        return $this->sign($this->getSignContent($params), $signType);
    }
 
    protected 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
     */
    protected 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是否非空
      */
    protected function checkEmpty($value) {
        if (!isset($value))
            return true;
        if ($value === null)
            return true;
        if (trim($value) === "")
            return true;
        return false;
    }
    /**
     *
     * 签名函数
     */
    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_ALGO_SHA256是php5.4.8以上版本才支持
            openssl_sign($data, $sign, $res, version_compare(PHP_VERSION,'5.4.0', '<') ? SHA256 : OPENSSL_ALGO_SHA256); 
        } else {
            openssl_sign($data, $sign, $res);
        }
        $sign = base64_encode($sign);
        return $sign;
    }
    /**
     *
     * 验签函数(用于查询支付宝数据)
     */
    protected 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;
    }	
	/**
	 * file_get_contents发送post请求
	 * @param url       请求地址
	 * @param postData  要传递的post数据
	 */
	protected function file_post($url, $post_data) {
		$postdata = http_build_query($post_data);
		$options = array('http' => array('method' => 'POST', 'header' => 'Content-type:application/x-www-form-urlencoded', 'content' => $postdata, 'timeout' => 300
		// 超时时间(单位:s)
		));
		$context = stream_context_create($options);
		$result = file_get_contents($url, false, $context);
		//去空格
		$result = trim($result);
		//转换字符编码
		$result = mb_convert_encoding($result, 'utf-8', 'UTF-8,GBK,GB2312,BIG5');
		//解决返回的json字符串中返回了BOM头的不可见字符(某些编辑器默认会加上BOM头)
		$result = trim($result,chr(239).chr(187).chr(191));
		return $result;
	}
	/**
	 * curl发送post请求
	 * @param url       请求地址
	 * @param postData  要传递的post数据
	 */	
	protected function curl_post($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;
    }
	/**
     * 建立请求,以表单HTML形式构造(默认)
	 * @param $url 请求地址
     * @param $params 请求参数数组
     * @return 提交表单HTML文本
     */
    protected function buildRequestForm($url,$params) {
 
        $sHtml = "正在跳转至支付页面...<form id='alipaysubmit' name='alipaysubmit' action='".$url."?charset=".$this->charset."' method='POST'>";
		foreach($params as $key=>$val){
            if (false === $this->checkEmpty($val)) {
                $val = str_replace("'","&apos;",$val);
                $sHtml.= "<input type='hidden' name='".$key."' value='".$val."'/>";
            }	
		}
        //submit按钮控件请不要含有name属性
        $sHtml = $sHtml."<input type='submit' value='ok' style='display:none;''></form>";
        $sHtml = $sHtml."<script>document.forms['alipaysubmit'].submit();</script>";
        return $sHtml;
    }
}
?>

微信支付封装类Weinxinpay.php

<?php
namespace pay;
use \think\Db;
 
/**
 * 微信支付类
 */
class Weinxinpay {
	//是否沙盒环境
	private $is_sandbox = false;
	//沙盒地址
	private $sandurl = 'https://api.mch.weixin.qq.com/sandboxnew/pay';
	//正式地址
	private $apiurl  = 'https://api.mch.weixin.qq.com/pay';
	private $mchid;//微信支付分配的商户账号PartnerID 通过微信支付商户资料审核后邮件发送
    private $appid;//微信支付分配的公众账号ID(企业号corpid即为此appid)
	private $appkey;//微信支付申请对应的公众号的APP Key
    private $apikey;//微信支付分配的商户密钥
	private $wapname;//wap网站名
	private $wapurl; //wap网站域名(网址)  
	//网关地址
	private $gateway;
	//构造方法
	public function __construct($account=null){
	    if($account!=null){
			$this->mchid = $account['mchid'];
			$this->appid = $account['appid'];
			$this->apikey = $account['apikey'];
			if(isset($account['appkey'])){
				$this->appkey = $account['appkey'];
			}
			if(isset($account['wapname'])){
				$this->wapname = $account['wapname'];
			}
			if(isset($account['wapurl'])){
				$this->wapurl = $account['wapurl'];
			}
	    }
		//如果是沙箱测试
    	if($this->is_sandbox){
			$this->gateway = $this->sandurl;
		}else{
			$this->gateway = $this->apiurl;
		}
	}
	/**
	 *
	 * 1.发起原生支付
	 * $params 传输的数据
	 */
	public function nativePay($params){
		//商品名称
		$subject=isset($params['subject']) && !empty($params['subject']) ? $params['subject'] : "购买商品";
		$config = array(
            'mch_id' => $this->mchid,
            'appid' => $this->appid,
            'key' => $this->apikey,
        );
        $unified = array(
            'appid' => $config['appid'],
            'attach' => 'pay', //商家数据包,原样返回,如果填写中文,请注意转换为utf-8
            'body' => $subject,//商品名称(商品简单描述)
            'mch_id' => $config['mch_id'],
            'nonce_str' => self::createNonceStr(),//随机字符串,长度要求在32位以内
            'notify_url' => $params['notify_url'],//异步通知地址
            'out_trade_no'=> $params['pay_id'],//唯一标识,订单编号(必须)
            'spbill_create_ip' => $_SERVER['REMOTE_ADDR'],
            'total_fee' => floatval($params['money']) * 100,//订单金额,单位 转为分
            'trade_type' => 'NATIVE',
        );
        $unified['sign'] = self::getSign($unified, $config['key']);
        $responseXml = self::curl_post($this->gateway.'/unifiedorder', self::arrayToXml($unified));
		//禁止引用外部xml实体
		libxml_disable_entity_loader(true);        
        $unifiedOrder = simplexml_load_string($responseXml, 'SimpleXMLElement', LIBXML_NOCDATA);
        if ($unifiedOrder === false) {
            die('parse xml error');
        }
        if ($unifiedOrder->return_code != 'SUCCESS') {
            die($unifiedOrder->return_msg);
        }
        if ($unifiedOrder->result_code != 'SUCCESS') {
            die($unifiedOrder->err_code);
        }
        $codeUrl = (array)($unifiedOrder->code_url);
        if(!$codeUrl[0]) exit('get code_url error');
		$timestamp=time();//付款时间
        $arr = array(
            "appId" => $config['appid'],
            "timeStamp" => "$timestamp",//这里是字符串的时间戳,不是int,所以需加引号
            "nonceStr" => self::createNonceStr(),//随机字符串,长度要求在32位以内
            "package" => "prepay_id=" . $unifiedOrder->prepay_id,
            "signType" => 'MD5',
            "code_url" => $codeUrl[0],
        );
        $arr['paySign'] = self::getSign($arr, $config['key']);
        return $arr;
	}
	/**
	 *
	 * 2.发起公众号支付
	 * $openId
	 * $params 传输的数据
	 */
	public function jsapiPay($openId,$params){	
		//商品名称
		$subject=isset($params['subject']) && !empty($params['subject']) ? $params['subject'] : "购买商品";		
		$config = array(
            'mch_id' => $this->mchid,
            'appid' => $this->appid,
            'key' => $this->apikey,
        );
        //$orderName = iconv('GBK','UTF-8',$orderName);
        $unified = array(
            'appid' => $config['appid'],
            'attach' => 'pay', //商家数据包,原样返回,如果填写中文,请注意转换为utf-8
            'body' => $subject,//商品名称(商品简单描述)
            'mch_id' => $config['mch_id'],
            'nonce_str' => self::createNonceStr(),//随机字符串,长度要求在32位以内
            'notify_url' => $params['notify_url'],//异步通知地址
            'openid' => $openid, //rade_type=JSAPI,此参数必传
            'out_trade_no' => $params['pay_id'],//唯一标识,订单编号(必须)
            'spbill_create_ip' => $_SERVER['REMOTE_ADDR'],
            'total_fee' => floatval($params['money']) * 100,//订单金额,单位 转为分
            'trade_type' => 'JSAPI',
        );
        $unified['sign'] = self::getSign($unified, $config['key']);
        $responseXml = self::curl_post($this->gateway.'/unifiedorder', self::arrayToXml($unified));
		//禁止引用外部xml实体
		libxml_disable_entity_loader(true);	    
        $unifiedOrder = simplexml_load_string($responseXml, 'SimpleXMLElement', LIBXML_NOCDATA);
        if ($unifiedOrder === false) {
            die('parse xml error');
        }
        if ($unifiedOrder->return_code != 'SUCCESS') {
            die($unifiedOrder->return_msg);
        }
        if ($unifiedOrder->result_code != 'SUCCESS') {
            die($unifiedOrder->err_code);
        }
		$timestamp=time();//付款时间
        $arr = array(
            "appId" => $config['appid'],
            "timeStamp" => "$timestamp",//这里是字符串的时间戳,不是int,所以需加引号
            "nonceStr" => self::createNonceStr(),//随机字符串,长度要求在32位以内
            "package" => "prepay_id=" . $unifiedOrder->prepay_id,
            "signType" => 'MD5',
        );
        $arr['paySign'] = self::getSign($arr, $config['key']);
        return $arr;
	}
	/**
	 *
	 * 3.发起H5支付
	 * $params 传输的数据
	 */
	public function h5Pay($params){	
		//商品名称
		$subject=isset($params['subject']) && !empty($params['subject']) ? $params['subject'] : "购买商品";
		$config = array(
            'mch_id' => $this->mchid,
            'appid' => $this->appid,
            'key' => $this->apikey,
        );
        $scene_info = array(
            'h5_info' =>array(
                'type'=>'Wap',
                'wap_url'=>$this->wapurl,
                'wap_name'=>$this->wapname,
            )
        );
        $unified = array(
            'appid' => $config['appid'],
            'attach' => 'pay',//商家数据包,原样返回,如果填写中文,请注意转换为utf-8
            'body' => $subject,//商品名称(商品简单描述)
            'mch_id' => $config['mch_id'],
            'nonce_str' => self::createNonceStr(),//随机字符串,长度要求在32位以内
            'notify_url' => $params['notify_url'],//异步通知地址
            'out_trade_no' => $params['pay_id'],//唯一标识,订单编号(必须)
            'spbill_create_ip' => $_SERVER['REMOTE_ADDR'],
            'total_fee' => floatval($params['money']) * 100,//订单金额,单位 转为分
            'trade_type' => 'MWEB',
            'scene_info'=>json_encode($scene_info)
        );
        $unified['sign'] = self::getSign($unified, $config['key']);
        $responseXml = self::curl_post($this->gateway.'/unifiedorder', self::arrayToXml($unified));
        $unifiedOrder = simplexml_load_string($responseXml, 'SimpleXMLElement', LIBXML_NOCDATA);
        if ($unifiedOrder->return_code != 'SUCCESS') {
            die($unifiedOrder->return_msg);
        }
        if($unifiedOrder->mweb_url){
            return $unifiedOrder->mweb_url.'&redirect_url='.urlencode($params['return_url']);
        }
        exit('error');
	}
	/**
	 * 异步通知
	 * @param $data 通知的数据
	 */
	public function notify()
    {
        $config = array(
            'mch_id' => $this->mchid,
            'appid' => $this->appid,
            'key' => $this->apikey,
        );
        $postStr = file_get_contents('php://input');
		//禁止引用外部xml实体
		libxml_disable_entity_loader(true);        
        $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
        if ($postObj === false) {
            die('parse xml error');
        }
        if ($postObj->return_code != 'SUCCESS') {
            die($postObj->return_msg);
        }
        if ($postObj->result_code != 'SUCCESS') {
            die($postObj->err_code);
        }
        $arr = (array)$postObj;
        unset($arr['sign']);
        if (self::getSign($arr, $config['key']) == $postObj->sign) {
            echo '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
            return $arr;
        }
    }
	/**
     * 通过跳转获取用户的openid,跳转流程如下:
     * 1、设置自己需要调回的url及其其他参数,跳转到微信服务器https://open.weixin.qq.com/connect/oauth2/authorize
     * 2、微信服务处理完成之后会跳转回用户redirect_uri地址,此时会带上一些参数,如:code
     * @return 用户的openid
     */
    public function getOpenid()
    {
        //通过code获得openid
        if (!isset($_GET['code'])){
            //触发返回code码
            $scheme = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']=='on' ? 'https://' : 'http://';
			$uri = $_SERVER['PHP_SELF'].$_SERVER['QUERY_STRING'];
			if($_SERVER['REQUEST_URI']) $uri = $_SERVER['REQUEST_URI'];
            $baseUrl = urlencode($scheme.$_SERVER['HTTP_HOST'].$uri);
            $url = $this->createOauthUrlForCode($baseUrl);
            Header("Location: $url");
            exit();
        } else {
            //获取code码,以获取openid
            $code = $_GET['code'];
            $openid = $this->getOpenidFromMp($code);
            return $openid;
        }
    }
	/**
     * 通过code从工作平台获取openid机器access_token
     * @param string $code 微信跳转回来带上的code
     * @return openid
     */
    public function getOpenidFromMp($code)
    {
        $url = $this->createOauthUrlForOpenid($code);
        $res = self::curl_get($url);
        //取出openid
        $data = json_decode($res,true);
        $this->data = $data;
        $openid = $data['openid'];
        return $openid;
    }
    /**
     * 构造获取open和access_toke的url地址
     * @param string $code,微信跳转带回的code
     * @return 请求的url
     */
    private function createOauthUrlForOpenid($code)
    {
        $urlObj["appid"] = $this->appid;
        $urlObj["secret"] = $this->appkey;
        $urlObj["code"] = $code;
        $urlObj["grant_type"] = "authorization_code";
        $bizString = $this->ToUrlParams($urlObj);
        return "https://api.weixin.qq.com/sns/oauth2/access_token?".$bizString;
    }
	/**
     * 构造获取code的url连接
     * @param string $redirectUrl 微信服务器回跳的url,需要url编码
     * @return 返回构造好的url
     */
    private function createOauthUrlForCode($redirectUrl)
    {
        $urlObj["appid"] = $this->appid;
        $urlObj["redirect_uri"] = "$redirectUrl";
        $urlObj["response_type"] = "code";
        $urlObj["scope"] = "snsapi_base";
        $urlObj["state"] = "STATE"."#wechat_redirect";
        $bizString = $this->ToUrlParams($urlObj);
        return "https://open.weixin.qq.com/connect/oauth2/authorize?".$bizString;
    }
	protected static function createNonceStr($length = 16)
    {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $str = '';
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }
	/**
     * 拼接签名字符串
     * @param array $urlObj
     * @return 返回已经拼接好的字符串
     */
    private function ToUrlParams($urlObj)
    {
        $buff = "";
        foreach ($urlObj as $k => $v)
        {
            if($k != "sign") $buff .= $k . "=" . $v . "&";
        }
        $buff = trim($buff, "&");
        return $buff;
    }
	/**
     * 获取签名
     */
    protected static function getSign($params, $key)
    {
        ksort($params, SORT_STRING);
        $unSignParaString = self::formatQueryParaMap($params, false);
        $signStr = strtoupper(md5($unSignParaString . "&key=" . $key));
        return $signStr;
    }
    protected static function formatQueryParaMap($paraMap, $urlEncode = false)
    {
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v) {
            if (null != $v && "null" != $v) {
                if ($urlEncode) {
                    $v = urlencode($v);
                }
                $buff .= $k . "=" . $v . "&";
            }
        }
        $reqPar = '';
        if (strlen($buff) > 0) {
            $reqPar = substr($buff, 0, strlen($buff) - 1);
        }
        return $reqPar;
    }
	protected static function arrayToXml($arr)
    {
        $xml = "<xml>";
        foreach ($arr as $key => $val) {
            if (is_numeric($val)) {
                $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
            } else
                $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
        }
        $xml .= "</xml>";
        return $xml;
    }
	/**
	 * file_get_contents发送post请求
	 * @param url       请求地址
	 * @param postData  要传递的post数据
	 */
	protected function file_post($url, $post_data) {
		$postdata = http_build_query($post_data);
		$options = array('http' => array('method' => 'POST', 'header' => 'Content-type:application/x-www-form-urlencoded', 'content' => $postdata, 'timeout' => 300
		// 超时时间(单位:s)
		));
		$context = stream_context_create($options);
		$result = file_get_contents($url, false, $context);
		//去空格
		$result = trim($result);
		//转换字符编码
		$result = mb_convert_encoding($result, 'utf-8', 'UTF-8,GBK,GB2312,BIG5');
		//解决返回的json字符串中返回了BOM头的不可见字符(某些编辑器默认会加上BOM头)
		$result = trim($result,chr(239).chr(187).chr(191));
		return $result;
	}
	public static function curl_get($url = '', $options = array())
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        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;
    }
	/**
	 * curl发送post请求
	 * @param url       请求地址
	 * @param postData  要传递的post数据
	 */	
	protected function curl_post($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;
    }
	/**
     * 建立请求,以表单HTML形式构造(默认)
	 * @param $url 请求地址
     * @param $params 请求参数数组
     * @return 提交表单HTML文本
     */
    protected function buildRequestForm($url,$params) {
 
        $sHtml = "正在跳转至支付页面...<form id='alipaysubmit' name='alipaysubmit' action='".$url."?charset=".$this->charset."' method='POST'>";
		foreach($params as $key=>$val){
            if (false === $this->checkEmpty($val)) {
                $val = str_replace("'","&apos;",$val);
                $sHtml.= "<input type='hidden' name='".$key."' value='".$val."'/>";
            }	
		}
        //submit按钮控件请不要含有name属性
        $sHtml = $sHtml."<input type='submit' value='ok' style='display:none;''></form>";
        $sHtml = $sHtml."<script>document.forms['alipaysubmit'].submit();</script>";
        return $sHtml;
    }
}
?>
 类似资料: