• php微信支付代码


    <?php  
     
        /**
     *微信下单
     */
     function wxorders(){
            ini_set("display_errors", "On");
            error_reporting(E_ALL | E_STRICT);
      $kilometre = $_POST['kilometre'];
      $km = $kilometre/1000;//米数转化成公里
            if(empty($_POST['session_key'])){
                $msg['status'] = 'error';
                $msg['msg'] = 'session_key 不能为空';
                echo json_encode($msg);exit();
            }
      //提交订单
      $data = array(
       'start_address'=>$_POST['startLoca'],//出发地址
       'end_address'=>$_POST['destLoca'],//目的地
       'start_time'=>strtotime(str_replace('.','-',$_POST['startTime'])),//开始时间
       'end_time'=>strtotime(str_replace('.','-',$_POST['endTime'])),//结束时间
       'km'=>$km,//公里数
       'seat'=>$_POST['seat'],//座位
       'borad_price'=>$_POST['basicPrice'],//上车价
       'per_km'=>$_POST['perKiloPrice'],//每公里单价
       'total_price'=>$_POST['cost'],//总价钱
       'contact'=>$_POST['name'],//联系人名
       'mobile'=>$_POST['phone'],//联系电话
       'status'=>'1',//状态
       'create_time'=>time(),//提交时间
       'type'=>$_POST['type'],//租车类型  小bus 大巴等
       'kelala'=>$_POST['session_key'],//标识符
       );
      $total_price = $_POST['cost'];//总价赋值
            //插入订单记录,此处状态为待付款
      $id = $this->baseModel->add('orders',$data);
            //根据标识符查询当前账号的openid
            $kelala = $_POST['session_key'];//用户的唯一标识
            $user = $this->baseModel->getRow('user','*',array('kelala'=>$kelala));
            if(empty($user)){
                $msg['status'] = 'error';
                $msg['msg'] = '用户信息不能为空';
                echo json_encode($msg);exit();
            }
            if(empty($user['openid'])){
                $msg['status'] = 'error';
                $msg['msg'] = 'openid不能为空';
                echo json_encode($msg);exit();
            }
         //调用下单接口  $res为新订单的id
      $r = $this->wxpay($total_price,$user['openid'],$id);
            // if(empty($r['prepay_id'])){
            //     $msg['status'] = 'error';
            //     $msg['msg'] = '微信调起失败';
            //     $msg['data'] = $r;
            //     echo json_encode($msg);exit();
            // }
            //这里是返回给前端的参数,也是这篇代码的最后一句,返回之后,前端就可以调用微信支付弹出框了
            echo json_encode($r);exit();
     }

        /**
        *微信下单
        *@param total_price 下单金额 单位为/元
        *@return 这一步返回prepay_id
        *@param $id为新订单的id
        */
        function wxpay($total_price,$openid,$id){
            //拼接商品订单号
            $body = '测试商品';
            //这个是订单号,也是一个订单的唯一标识,支付成功会返回过来
            $out_trade_no = date("YmdHis") . rand(100, 999);
            // //更新微信返回的订单号
            $this->baseModel->updateById('orders',array('out_trade_no'=>$out_trade_no),$id);
              $order = [
                'appid'=>'',
                'mch_id'=>'1499532322',//这个是商户id,是在商户平台绑定银行卡后的id,给谁付钱就是谁的商户id
                'openid'=>$openid,
                'nonce_str'=>$this->rand2(10),
                'body'=>'测试商品',
                'out_trade_no'=>$out_trade_no,//商户唯一订单号,可包含字母序
                'total_fee'=>(string)$total_price*100,//订单金额,单位/分所以乘以100
                'spbill_create_ip'=>$_SERVER['REMOTE_ADDR'],
                //产生订单号的服务器IP
                'notify_url'=>'https://www.kelalazuche.com/notice',//接受微信异步通知地址
                'trade_type'=>'JSAPI',//交易类型
            ];
            //MD5处理,默认支持MD5
            // $sign = md5($sign);
            $order['sign'] = $this->getSign($order);
            //转换成一维XML格式
            $xml = '<xml>';
            foreach($order as $k=>$v){
                $xml.='<'.$k.'><![CDATA['.$v.']]></'.$k.'>';
            }
            $xml.='</xml>';
            $KEY = '12ed7bd47d66f4ef7865f79b2194a94b';//加密的字符串
            //CURL会话
            $ch = curl_init();
            // 设置curl允许执行的最长秒数
            curl_setopt($ch, CURLOPT_TIMEOUT, 3);
            curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
            curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
            // 获取的信息以文件流的形式返回,而不是直接输出。
            curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
            //发送一个常规的POST请求。
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_URL, 'https://api.mch.weixin.qq.com/pay/unifiedorder');
            //要传送的所有数据
            curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
            // 执行操作
            $response = curl_exec($ch);
            //将xml格式的$response 转成数组
            $response = json_decode( json_encode( simplexml_load_string($response, 'SimpleXMLElement', LIBXML_NOCDATA) ), true );
            if($response['return_code'] == "SUCCESS" && $response['result_code'] == "SUCCESS"){
                //根据微信支付返回的结果进行二次签名
                //二次签名所需的随机字符串
                $order["nonceStr"] = $this->rand2(10);//随机字符串
                //二次签名所需的时间戳
                $order['timeStamp'] = time()."";
                //二次签名剩余参数的补充
                $secondSignArray = array(
                        "appId"=>$order['appid'],
                        "nonceStr"=>$order['nonceStr'],
                        //"package"=>"Sign=WXPay",
                        "package"=>"prepay_id=".$response['prepay_id'],
                        "signType"=>"MD5",
                        "timeStamp"=>$order['timeStamp'],
                );
                $data = $secondSignArray;
                $recharge_num = $order["out_trade_no"];
                $data['paySign'] =  $this->makeSign($secondSignArray,$KEY);
                $data['prepay_id'] = $response['prepay_id'];
                $data['out_trade_no'] = $out_trade_no;
               
                // $output = array('data'=>$data ,'info'=>"success" ,'code'=>"200" ,'order_number'=>$recharge_num);
                // return($output);
                return $data;
            }else{
                //返回错误信息
                $output = array('data'=>false ,'info'=>"error" ,'code'=>"100" ,'order_number'=>false);
                echo json_encode($output);exit();
            }
            // return $response;
        }

        /**
        *生成签名算法
        */
        function getSign($array)
        {  
            //这个是在平台自己设置的,一个32位的字符串,应该是秘钥(私钥)什么的
            $pay_key = "12ed7bd47d66f4ef7865f79b2194a94b";
            unset($array['sign']);
            ksort($array);
            $stringA = urldecode(http_build_query($array));
            $stringSignTemp="$stringA&key=".$pay_key;
            return strtoupper(md5($stringSignTemp));
        }

        /**
        *生成不重复的字符串
        *@param $len 字符串长度
        *@return 随机字符串
        */
        function rand2($len)
           {
              $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
              $string=time();
              for(;$len>=1;$len--)
              {
                  $position=rand()%strlen($chars);
                  $position2=rand()%strlen($string);
                  $string=substr_replace($string,substr($chars,$position,1),$position2,0);
             }
             return $string;
        }

        /**
         * 生成签名, $KEY就是支付key
         * @return 签名
         */
        function MakeSign( $params,$KEY){
            //签名步骤一:按字典序排序数组参数
            ksort($params);
            $string = $this->ToUrlParams($params);  //参数进行拼接key=value&k=v
            //签名步骤二:在string后加入KEY
            $string = $string . "&key=".$KEY;
            //签名步骤三:MD5加密
            $string = md5($string);
            //签名步骤四:所有字符转为大写
            $result = strtoupper($string);
            return $result;
        }

         function ToUrlParams( $params ){
            $string = '';
            if( !empty($params) ){
                $array = array();
                foreach( $params as $key => $value ){
                    $array[] = $key.'='.$value;
                }
                $string = implode("&",$array);
            }
            return $string;
        }
         function xml2array($xml){
            $p = xml_parser_create();
            xml_parse_into_struct($p, $xml, $vals, $index);
            xml_parser_free($p);
            $data = "";
            foreach ($index as $key=>$value) {
                if($key == 'xml' || $key == 'XML') continue;
                $tag = $vals[$value[0]]['tag'];
                $value = $vals[$value[0]]['value'];
                $data[$tag] = $value;
            }
            return $data;
        }

        /**
        *发送请求的代码
        */
        function http_request($url,$data = null,$headers=array())
        {
            $curl = curl_init();
            if( count($headers) >= 1 ){
                curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
            }
            curl_setopt($curl, CURLOPT_URL, $url);
       
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
       
            if (!empty($data)){
                curl_setopt($curl, CURLOPT_POST, 1);
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            }
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            $output = curl_exec($curl);
            curl_close($curl);
            return $output;
        }
  • 相关阅读:
    初学java-基础
    初学java-基础
    HYPER-V 实现管理器远程管理虚拟机
    zeromq rpc原型
    haproxy+keepalived
    [转]序列化悍将Protobuf-Net,入门动手实录
    RabbitMQ的几种应用场景
    redis数据类型及使用场景
    [转]DDD领域驱动设计基本理论知识总结
    Centos 下编译安装Redis
  • 原文地址:https://www.cnblogs.com/ayanboke/p/8624733.html
Copyright © 2020-2023  润新知