欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

PHP微信H5支付开发实例

程序员文章站 2022-07-06 10:56:38
最近由于业务所需,对接了微信h5支付,然而微信支付对这块并没有现成的demo可用,所以就必须自己老老实实对照开发文档去写咯!但这对于刚接触的童鞋来说,坑多多少少还是有的,所...

最近由于业务所需,对接了微信h5支付,然而微信支付对这块并没有现成的demo可用,所以就必须自己老老实实对照开发文档去写咯!但这对于刚接触的童鞋来说,坑多多少少还是有的,所以寻思着把自己的经验分享出来,毕竟现成的用的还是多巴适的嘛!

好了,官方文档的那一套就不多说了,详情见官方文档

在这里,我主要分成了三个文件:wxpay.config.php(支付配置文件)、weixin.class.php(支付类)以及paymentcontroller.class.php(支付文件)。

首先,wxpay.config.php配置文件主要包含了商户appid、商户号、商家key、异步回调url、支付场景信息,如下:

class wxpayconfig
{
  public static $appid = '微信支付的公众号appid';
  public static $mchid = '微信支付分配的商户号';
  public static $key = '微信商户自己设置的安全key';
  public static $notify_url = '商户侧接收微信支付异步通知的url';
  public static $scene_info = '{"h5_info":{"type":"wap","wap_url":" 发起微信h5支付h5的url","wap_name":"支付"}}'; 
}

然后,封装weixin.class.php支付类,主要调用统一下单api,这里不多说了,直接上代码:

<?php
require_once "lib/wxpay.config.php";
class weixin
{
     /**
   * 微信h5下单付款
   *   @order 付款信息
     *   @bodys 付款内容
   * */
     function getcode($order,$bodys){
          $url = "https://api.mch.weixin.qq.com/pay/unifiedorder";//微信传参地址
          //1.获取调用统一下单接口所需必备参数
    $appid =wxpayconfig::$appid;//微信公众号appid
    $mch_id = wxpayconfig::$mchid;//微信支付商户号
    $key = wxpayconfig::$key;//自己设置的微信商家key
    $out_trade_no = $order['order_sn'];//平台内部订单号
    $nonce_str=md5($out_trade_no);//随机字符串
    $body = $bodys;//付款内容
    $total_fee = $order['order_amount']*100;//付款金额,单位为分
    $spbill_create_ip = getip(); //获得用户设备ip
    $attach = 'weixinh5';//附加数据(自定义,在支付通知中原样返回)
    $notify_url = wxpayconfig::$notify_url; //异步回调地址,需外网可以直接访问
    $trade_type = 'mweb';//交易类型,微信h5支付时固定为mweb
    $scene_info =wxpayconfig::$scene_info;//场景信息
          //2.将参数按照key=value的格式,并按照参数名ascii字典序排序生成字符串
    $signa ="appid=$appid&attach=$attach&body=$body&mch_id=$mch_id&nonce_str=$nonce_str&notify_url=$notify_url&out_trade_no=$out_trade_no&scene_info=$scene_info&spbill_create_ip=$spbill_create_ip&total_fee=$total_fee&trade_type=$trade_type";
    //3.拼接字符串
          $strsigntmp = $signa."&key=$key";
          //4.md5加密后转换成大写
    $sign = strtoupper(md5($strsigntmp));
          //5.拼接成所需xml格式
    $post_data = "<xml> 
            <appid>$appid</appid> 
            <attach>$attach</attach> 
            <body>$body</body> 
            <mch_id>$mch_id</mch_id> 
            <nonce_str>$nonce_str</nonce_str> 
            <notify_url>$notify_url</notify_url> 
            <out_trade_no>$out_trade_no</out_trade_no> 
            <spbill_create_ip>$spbill_create_ip</spbill_create_ip> 
            <total_fee>$total_fee</total_fee> 
            <trade_type>$trade_type</trade_type>
            <scene_info>$scene_info</scene_info>
            <sign>$sign</sign> 
          </xml>";
          //6.以post方式向微信传参,并取得微信返回的支付参数
    $dataxml = httprequest($url,'post',$post_data);
    $objectxml = (array)simplexml_load_string($dataxml, 'simplexmlelement', libxml_nocdata); //将微信返回的xml转换成数组
    return $objectxml;
  }
}

最后,paymentcontroller.class.php支付文件,支付文件接收前端发起支付的请求并处理后,调用weixin.class.php支付类并接受结果后返回给前端(此处分享已经去掉接口验证等系列代码逻辑):

public function getpay(){
     //1.引入支付类文件
     include_once "plugins/payment/weixin/weixin.class.php";
     $payment = new \weixin();
     $order_id = i('order_id');
     //2.判断参数是否为空
     if (!empty($order_id)){
          //3.根据订单id查询订单是否存在
          $order = m('order')->where(array('id'=>$order_id))->find();
          if ($order){//订单存在
              //4.判断该笔订单是否已经支付,如已支付则返回支付失败并给出相应提示
              if ($order['pay_status'] == '1'){
                   exit(json_encode(array('status'=>'205','msg'=>'该订单已支付,请勿重复提交!')));
              }
              $bodys = '订单:'.$order['order_sn'] . '支付';
              //5.调用支付类中封装的支付方法并对应传参
              $result = $payment->getcode($order,$bodys);
              //6.当return_code和result_code均为success,代表下单成功,将支付参数返回
              if($result['return_code'] == 'success'){
                   if($result['result_code'] == 'success'){
                        exit(json_encode(array('status'=>'0','msg'=>'下单成功,请支付!','result'=>$result['mweb_url'])));
                   }elseif($result['result_code'] == 'fail'){
                        exit(json_encode(array('status'=>'-201','msg'=>$result['err_code_des'])));
                   }
              }else{
        exit(json_encode(array('status'=>'-1','msg'=>'未知错误,请稍后重试!')));
                  }
          }else{
              //报错:数据不存在
              exit(json_encode(array('status'=>'-200','msg'=>'订单不存在,请核实后再提交!')));
          }
     }else{
          //报错:缺少参数
          exit(json_encode(array('status'=>'-204','msg'=>'参数缺失,请核实!')));
     }
}

前端在接收到支付url后执行即可唤醒微信支付。

附一:获取用户终端设备ip方法

function getip(){      
    if (getenv("http_client_ip"))
       $ip = getenv("http_client_ip");
    else if(getenv("http_x_forwarded_for"))
        $ip = getenv("http_x_forwarded_for");
    else if(getenv("remote_addr"))
       $ip = getenv("remote_addr");
    else $ip = "unknow";
    return $ip;
}

######附二:curl请求方法

/**
   * curl请求
   * @param $url 请求url地址
   * @param $method 请求方法 get post
   * @param null $postfields post数据数组
   * @param array $headers 请求header信息
   * @param bool|false $debug 调试开启 默认false
   * @return mixed
   */
  function httprequest($url, $method, $postfields = null, $headers = array(), $debug = false) {
    $method = strtoupper($method);
    $ci = curl_init();
    /* curl settings */
    curl_setopt($ci, curlopt_http_version, curl_http_version_1_0);
    curl_setopt($ci, curlopt_useragent, "mozilla/5.0 (windows nt 6.2; wow64; rv:34.0) gecko/20100101 firefox/34.0");
    curl_setopt($ci, curlopt_connecttimeout, 60); /* 在发起连接前等待的时间,如果设置为0,则无限等待 */
    curl_setopt($ci, curlopt_timeout, 7); /* 设置curl允许执行的最长秒数 */
    curl_setopt($ci, curlopt_returntransfer, true);
    switch ($method) {
      case "post":
        curl_setopt($ci, curlopt_post, true);
        if (!empty($postfields)) {
          $tmpdatastr = is_array($postfields) ? http_build_query($postfields) : $postfields;
          curl_setopt($ci, curlopt_postfields, $tmpdatastr);
        }
        break;
      default:
        curl_setopt($ci, curlopt_customrequest, $method); /* //设置请求方式 */
        break;
    }
    $ssl = preg_match('/^https:\/\//i',$url) ? true : false;
    curl_setopt($ci, curlopt_url, $url);
    if($ssl){
      curl_setopt($ci, curlopt_ssl_verifypeer, false); // https请求 不验证证书和hosts
      curl_setopt($ci, curlopt_ssl_verifyhost, false); // 不从证书中检查ssl加密算法是否存在
    }
    curl_setopt($ci, curlopt_followlocation, 1);
    curl_setopt($ci, curlopt_maxredirs, 2);/*指定最多的http重定向的数量,这个选项是和curlopt_followlocation一起使用的*/
    curl_setopt($ci, curlopt_httpheader, $headers);
    curl_setopt($ci, curlinfo_header_out, true);
    $response = curl_exec($ci);
    $requestinfo = curl_getinfo($ci);
    if ($debug) {
      echo "=====post data======\r\n";
      var_dump($postfields);
      echo "=====info===== \r\n";
      print_r($requestinfo);
      echo "=====response=====\r\n";
      print_r($response);
    }
    curl_close($ci);
    return $response;
}

好了,一点点菜鸟心得,有不当之处欢迎留言指证交流,一起成长!

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。