1. 程式人生 > >微信支付/支付寶支付封裝函式(tp5)

微信支付/支付寶支付封裝函式(tp5)

/**
 *
 * @author lsw
 ${PARAM_DOC}
 * @access public ${NAME}
#if (${TYPE_HINT} != "void") * @return ${TYPE_HINT}
#end
${THROWS_DOC}
*/
<?php
namespace Pay;

use think\Config;

vendor ('Pay.alipay.pagepay.service.AlipayTradeService');
vendor ('Pay.alipay.pagepay.buildermodel.AlipayTradePagePayContentBuilder');
vendor ('Pay.wxpay.lib.WxPay#Api');
vendor ('Pay.wxpay.example.WxPay#NativePay');
vendor ('Pay.wxpay.example.WxPay#JsApiPay');
vendor ('Pay.wxpay.lib.WxPay#Api#php');
vendor ('Pay.wxpay.lib.WxPay#Notify#php');
vendor ('Pay.alipay.aop.AopClient');

class pay{

    //全域性阿里配置引數
    public $alipay_config = null;
    public $weixin_config = null;
    public function __construct()
    {
        $this->alipay_config = Config::get('alipay_config');
        $this->weixin_config = Config::get ('weixin_config');
    }

    /**
     * 電腦手機支付寶支付類
     * @author lsw
     * @param $trade_no 訂單引數
     * @param $name     訂單名稱
     * @param $price    訂單金錢
     * @param $body  內容
     * @param $return_url 同步回撥地址
     * @param $notify_url 非同步回撥地址
     * @access public Alipay
     * @throws \Exception
     */
    public function Alipay($trade_no,$name,$price,$body='')
    {

        //商戶訂單號,商戶網站訂單系統中唯一訂單號,必填
        $out_trade_no = trim($trade_no);
        //訂單名稱,必填
        $subject = trim($name);
        //付款金額,必填
        $total_amount = trim($price);
        //商品描述,可空
        $body = trim($body);
        //構造引數
        $payRequestBuilder = new \AlipayTradePagePayContentBuilder();
        $payRequestBuilder->setBody($body);
        $payRequestBuilder->setSubject($subject);
        $payRequestBuilder->setTotalAmount($total_amount);
        $payRequestBuilder->setOutTradeNo($out_trade_no);
        $aop = new \AlipayTradeService($this->alipay_config);

        /**
         * pagePay 電腦網站支付請求
         * @param $builder 業務引數,使用buildmodel中的物件生成。
         * @param $return_url 同步跳轉地址,公網可以訪問
         * @param $notify_url 非同步通知地址,公網可以訪問
         * @return $response 支付寶返回的資訊
         */
        $aop->pagePay($payRequestBuilder,$this->alipay_config['return_url'],$this->alipay_config['notify_url']);
        echo '支付跳轉中';

    }

    /**
     * jsapi支付介面
     * @author lsw
     * @param $trade_no
     * @param $name
     * @param $money
     * @param $body
     * @access public WxJspay
     * @return mixed
     * @throws \WxPayException
     */
    public function WxJspay($trade_no,$name,$money,$body)
    {

        //①、獲取使用者openid
        $tools = new \JsApiPay();
        $openId = $tools->GetOpenid();
        //②、統一下單
        $input = new \WxPayUnifiedOrder();
        $input->SetBody($name);
        $input->SetAttach($body);
        $input->SetOut_trade_no($trade_no);
        $input->SetTotal_fee($money);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetNotify_url( $this->weixin_config['notify_url']);
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openId);
        $order = \WxPayApi::unifiedOrder($input);
        $data['jsApiParameters'] = $tools->GetJsApiParameters($order);
        $data['editAddress'] = $tools->GetEditAddressParameters();
        return $data;
    }
    /**
     * 微信二維碼碼支付
     * @author lsw
     * @param $trade_no 訂單號
     * @param $name     名稱
     * @param $body     備註
     * @param $money    錢
     * @access public Wxpay
     * @return string
     */
    public function Wxpay($trade_no,$name,$money,$body)
    {
        //模式一
        $notify = new \NativePay();
        $input = new \WxPayUnifiedOrder();
        $input->SetBody($name);
        $input->SetAttach($body);
        $input->SetOut_trade_no($trade_no);
        $input->SetTotal_fee($money);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetNotify_url($this->weixin_config['notify_url']);
        $input->SetTrade_type("NATIVE");
        $input->SetProduct_id("123456789");
        $result = $notify->GetPayUrl($input);
        return  'http://paysdk.weixin.qq.com/example/qrcode.php?data='.urlencode($result["code_url"]);
    }

    /**
     * 支付寶支付成功驗證
     * @author lsw
     * @param $arr
     * @access public check
     * @return bool
     * @throws \Exception
     */
    public function check($arr)
    {
        $alipaySevice = new \AlipayTradeService($this->alipay_config);
        return $alipaySevice->check($arr);
    }


    public function Queryorder($transaction_id)
    {
        $input = new \WxPayOrderQuery();
        $input->SetTransaction_id($transaction_id);
        $result = \WxPayApi::orderQuery($input);
        if(array_key_exists("return_code", $result) && array_key_exists("result_code", $result) && $result["return_code"] == "SUCCESS" && $result["result_code"] == "SUCCESS")
        {
            return $result;
        }
        return false;
    }

    /**
     * 微信驗證訂單完整性
     * @author lsw
     * @param $data
     * @access public NotifyProcess
     * @return bool
     */
    public function NotifyProcess($data)
    {
        if(!array_key_exists("transaction_id", $data)){
            echo "輸入引數不正確";
            return false;
        }
        //查詢訂單,判斷訂單真實性
        if($result = $this->Queryorder($data->transaction_id)){
           return $result;
        }else{
            return FALSE;
        }
    }

    /**
     * 微信返回app引數
     * @author lsw
     * @param $order_sn
     * @param $name
     * @param $body
     * @param $price
     * @param string $openId
     * @param string $product_id
     * @access public unifiedorder
     * @return array
     * @throws \WxPayException
     */
    public function unifiedorder($order_sn,$name,$body,$price,$openId='', $product_id='')
    {
        //統一下單
        $input = new \WxPayUnifiedOrder();
        $input->SetBody($name);
        $input->SetAttach($body);
        $input->SetOut_trade_no($order_sn);
        $input->SetTotal_fee(($price*100));
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetNotify_url($this->weixin_config['notify_url']);
        $input->SetTrade_type("APP");
        $input->SetOpenid($openId);
        $input->SetProduct_id($product_id);
        $result = \WxPayApi::unifiedOrder($input);
        //二次加密
        $resultModel = new \WxPayUnifiedOrder();
        $resultModel->values = [
            'appid' =>$result['appid'],
            'partnerid' =>$result['mch_id'],
            'package' =>'Sign=WXPay',
            'prepayid' =>$result['prepay_id'],
            'noncestr' =>$result['nonce_str'],
            'timestamp' =>time (),
        ];
        $data = [
            'sign'=>$resultModel->MakeSign (),
            'order_sn'=>$order_sn,
            'trade_type'=>'APP',
            'appid'=>$result['appid'],
            'mch_id'=>$result['mch_id'],
            'package'=>'Sign=WXPay',
            'prepay_id'=>$result['prepay_id'],
            'nonce_str'=>$result['nonce_str'],
            'timestamp'=>$resultModel->values['timestamp'],
        ];
        return $data;
    }

    public function json($arr) {
        $str = json_encode($arr);
        $search = "#\\\u([0-9a-f]+)#ie";
        $replace = "iconv('UCS-2', 'UTF-8', pack('H4', '\\1'))";
        return preg_replace($search, $replace, $str);
    }
    /**
     * 支付寶返回app引數
     * @author lsw
     * @param $name
     * @param $order_sn
     * @param $price
     * @access public return_alipay_app
     * @return string
     */
    public function return_alipay_app($name,$order_sn,$price)
    {
        $private_path =  Config::get ('alipay_config.merchant_private_key');//私鑰路徑
        //構造業務請求引數的集合(訂單資訊)
        $content = array();
        $content['subject'] = $name;
        $content['out_trade_no'] = $order_sn;
//        $content['timeout_express'] = "".$time."";
        $content['total_amount'] = $price;
        $content['product_code'] = "QUICK_MSECURITY_PAY";//銷售產品碼,固定值

        $con = json_encode($content, JSON_UNESCAPED_UNICODE);//$content是biz_content的值,將之轉化成json字串
        //公共引數
        $Client = new \AopClient();//例項化支付寶sdk裡面的AopClient類,下單時需要的操作,都在這個類裡面
        $param['app_id'] = Config::get ('alipay_config.app_id');
        $param['method'] = 'alipay.trade.app.pay';//介面名稱,固定值
        $param['charset'] = 'utf-8';//請求使用的編碼格式
        $param['sign_type'] = 'RSA2';//商戶生成簽名字串所使用的簽名演算法型別
        $param['format'] = 'JSON';//商戶生成簽名字串所使用的簽名演算法型別
        $param['timestamp'] = date("Y-m-d H:i:s");//傳送請求的時間
        $param['version'] = '1.0';//呼叫的介面版本,固定為:1.0
        $param['notify_url'] = Config::get ('alipay_config.notify_url');
        $param['biz_content'] = $con;//業務請求引數的集合,長度不限,json格式,即前面一步得到的
        $paramStr = $Client->getSignContent($param);//組裝請求籤名引數
        $sign = $Client->alonersaSign($paramStr, $private_path, 'RSA2', false);//生成簽名
        $param['sign'] = urlencode($sign);
        $param['order_str'] = $Client->getSignContentUrlencode($param);//最終請求引數
        $param['a_sign'] = $sign;
        $param['a_order_str'] = urldecode ($param['order_str']);//最終請求引數
        return $param;
    }
}