Thinkphp微信支付

jianfly.com 2019-01-31 1713次浏览

1.php代码:WeipayController.class.php

<?php
namespace Home\Controller;
use Think\Controller;
class WeipayController extends Controller {
    //查询列表
    public function zhifu_ajax(){
        $orderid = I("post.orderid");
        $code_url = $this->index($orderid);//生成二维码
        if ($code_url) {
            echo '{"type":"1","code_url":"';
            echo $code_url;
            echo '"}';
            return false;
        } else {
            $this->ajaxReturn(array("type" => "0", "code_url" => ""));
        }
    }
     public function index($orderid){
        $order=M("Orders");
        $mass=$order->where(array("id"=>$orderid))->find();
        $sj=md5(rand(0,100000));
        $ip=$_SERVER["REMOTE_ADDR"];
        //获取订单号头部
        $title = '微信支付';
        $shujiu=array(
            "appid"=>'wxcb822d10a8e7****', //公众账号ID
            "attach"=>"在线微信支付",
            "mch_id"=>1480111852, //商户号
            "nonce_str"=>$sj, //随机字符串
            "body"=>"溧阳市*****", //商品描述
            "out_trade_no"=>$orderid, //商户订单号
            "total_fee"=>$mass["money"]*100, //总金额
            "spbill_create_ip"=>$ip, //终端IP
            "notify_url"=>"http://www.jianfly.com/Weipay/notifyurl", //通知地址
            "trade_type"=>"NATIVE", //交易类型
        );
         ksort($shujiu);
         $buff=$this->url($shujiu);
         $key=$buff."key=ABCDEFGHIJKLMNOPQRSTUVWXYZ******";
         $xmla="<xml>
           <appid>wxcb822d10a8e7****</appid>
           <attach>在线微信支付</attach>
           <body>溧阳市*****</body>
           <mch_id>1480111852</mch_id>
           <nonce_str>".$sj."</nonce_str>
           <notify_url>http://www.jianfly.com/Weipay/notifyurl</notify_url>
           <out_trade_no>".$orderid."</out_trade_no>
           <spbill_create_ip>".$ip."</spbill_create_ip>
           <total_fee>".($mass["money"]*100)."</total_fee>
           <trade_type>NATIVE</trade_type>
           <sign>".strtoupper(md5($key))."</sign>
           </xml>";
        $url="https://api.mch.weixin.qq.com/pay/unifiedorder";
        //微信订单支付key
        //M("order")->where(array("c_order_id"=>$orderid,'host'=>$host))->save(array("key"=>$sj));
        $datawei=$this->postXmlCurl($xmla,$url);
        $all=json_decode(json_encode(simplexml_load_string($datawei, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
       

        if($all['return_code']=="SUCCESS" && $all['result_code']=="SUCCESS"){
            return $all['code_url'];
        }else {
            $this->ajaxReturn($all);
        }
     }
    public function notifyurl(){
       
       

        $postArr =$GLOBALS['HTTP_RAW_POST_DATA'];
        $postObj = simplexml_load_string($postArr );
        $arr=json_decode(json_encode(simplexml_load_string($postArr, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        

        $orderid=$postObj->out_trade_no;

        //开始测试
        //test = json_encode($arr);
        //M('article')->add(array('content'=>$test , 'title'=>'微信异步测试'.$orderid, 'description'=>$postObj->out_trade_no));

        //$host_id = substr($postObj->out_trade_no,0,1);
        //$host = M('hosts')->where(array('id'=>$host_id))->getField('host');
        $money=$arr['total_fee'];
        //其他数据
        M('orders')->where('id='.$orderid)->save(array('state'=>'1'));
        //$order=M("Orders")->where(array("id"=>$orderid))->find();
        //判断是pc端还是微信端
        
        $type = 1;
        
        //异步通知给来源网站
        //notify_url:异步地址,orderid订单id,noti_type 0交易成功返回1退款成功返回
        $noti_type = 0;
        $this->backNotify('http://www.jianfly.com/Weiay/notifyurl',$orderid,$type,$noti_type);
        //开启事务,完成1修改订单状态2添加用户消费记录3判断用户等级
        //M()->startTrans();
        //修改支付中心的订单状态
        //$data['state'] = 1;
        //$data['pay_time'] = date("Y-m-d H:m:s");
        //\Think\Log::record($data['trade_no']."商户的订单号",'WARN');//订单id
        /*$change_status = M("order")->where(array('c_order_id'=>$orderid,'host'=>$host))->save($data);
        if($change_status){
            //添加消费记录
            $map['order_id'] = $orderid;
            $map['uid'] = $order['uid'];
            $map['pay_time'] = $data['pay_time'];
            $map['payment'] = $money;
            $map['host'] = $host;
            $map['type'] = 1;
            $add_pay = M('order_log')->add($map);
            if($add_pay){
                // \Think\Log::record("添加消费记录的次数",'WARN');//订单id
                M()->commit(); 
            }else{
                M()->rollback();
            }
        }else{
            M()->rollback();
        }*/
        
    }
    private static function postXmlCurl($xml, $url, $useCert = false, $second = 30)
    {
        $ch = curl_init();
        //设置超时
        curl_setopt($ch, CURLOPT_TIMEOUT, $second);
        curl_setopt($ch,CURLOPT_URL, $url);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);//严格校验
        //设置header
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        //post提交方式
        if($xml){
            curl_setopt($ch, CURLOPT_POST, TRUE);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        }
        //运行curl
        $data = curl_exec($ch);
        //返回结果
        if($data){
            curl_close($ch);
            return $data;
        }
    }
    //支付成功异步通知给来源网站
    //$type=1表示pc端微信支付成功进行回调,$type=0表示wap端微信支付成功进行回调
    public function backNotify($url,$orderid,$type,$noti_type){
        $responder['orderid'] = $orderid;
        $responder['noti_type'] = $noti_type;
        $ch = curl_init();
        //设置超时
        curl_setopt($ch,CURLOPT_URL, $url);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);//严格校验
        //设置header
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $responder);
        if($type){
            curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'); 
        }else{
            curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1'); 
        }
       
        //运行curl
        $data = curl_exec($ch);
        curl_close($ch);

    }
    // 判断微信支付是否成功
    public function weixin_ajax(){
        $order_id = I('get.order_id');
        $where['order_id'] = $order_id;
        $result = D('OrderInfo')->getOrder($where);
        if($result['pay_status'] == 2){
            $a = array();
            $a['status'] = 1;
            $a['order_sn'] = $result["order_sn"];
            $this->ajaxReturn($a);
        }else{
            $a = array();
            $a['status'] = 0;
            $this->ajaxReturn($a);
        }
    }
    // 微信支付失败后订单重新支付
    public function fail_ajax(){
        $order_id = I('get.id');
        $where['order_id'] = $order_id;
        $result = D('OrderInfo')->getOrder($where);
        if($result['pay_status'] == 0){
            $a = array();
            $a['status'] = 1;
            $a['order_sn'] = $result['order_sn'];
            $this->ajaxReturn($a);
        }else{
            $a = array();
            $a['status'] = 0;
            $this->ajaxReturn($a);
        }
    }
     // 微信支付获取订单状态,判断是否支付成功,完成跳转
    public function getStatus(){
        $orderid = I('get.orderid');
        $host = I('get.host');
        $order = M('order')->where(array('c_order_id'=>$orderid,'host'=>$host))->field('status,back_url')->find();
        if($order['status'] == 0){
            $this->ajaxReturn(array('status'=>0));
        }else{
            $this->ajaxReturn(array('status'=>1,'back_url'=>$order['back_url']));
        }
    }
    public function url($erwei){
        $buff='';
        foreach ($erwei as $k => $v)
        {
            $buff .= $k . '=' . $v . '&';
        }
        // $buff = htmlspecialchars($buff);
        return $buff;
    }

 }

2.html与js

<a href="javaScript:void(0)" onclick="weipay({$vo.id})">微信支付</a>
 <div id="qrcode_area"></div><!--这里是二维码-->
    <script>
        //微信支付
        //@param id 订单id
        function weipay( id ) {
            //跳微信
            $("#qrcode_area").html("");
            $.ajax({
                url: '{:U("/Weipay/zhifu_ajax")}',
                type: 'POST',
                dataType:'JSON',
                data: {"orderid":id },
                success: function(data){
                    console.log(data);
                    if(data.type=="1"){
                        jQuery("#qrcode_area").qrcode({ text: data.code_url });
                    }else{

                        alert("系统繁忙,请稍后重试");
                    }
                },
                error: function(){
                    alert("系统繁忙,请稍后重试");
                }
            }); 
            $('.wechat_pay').show();
            return false;
        }
    </script>
 <script src="__TMPL__/Public/Js/jquery.qrcode.min.js"></script>

3.js插件

jquery.qrcode.min.js