微信支付基于PHP

简介: 微信支付基于PHP

//微信JSAPI支付

前端页面wx.html

<html>
<head>
   <meta http-equiv="content-type" content="text/html;charset=utf-8"/>
   <meta name="viewport" content="width=device-width, initial-scale=1"/>
   <title>微信支付样例-支付</title>
   <script src="https://static.oschina.net/new-osc/js/utils/jquery.min.js"></script>
   <script type="text/javascript">
        function onBridgeReady(){
            var order_id = 7;
            $.ajax({
                'type':'get',
                'url':'http://wx.owenzhang.com/Pay',
                'data':{            //默认自动添加callback参数
                    'order_id':order_id,
                   'token':'27_G7oqz8ofmbn6q7aSsmpkGeVbQ'  //不安全,请定期刷新token,建议进行文件压缩
                },
                'dataType':'json',
                'success':function(json){
                    var json = json.data;
                    //微信JSAPI支付
                    WeixinJSBridge.invoke(
                        'getBrandWCPayRequest', {
                            "appId":json.appId,     //公众号id,由商户传入
                            "timeStamp":json.timeStamp, //时间戳,自1970年以来的秒数
                            "nonceStr":json.nonceStr, //随机串
                            "package":json.package,//订单详情扩展字符串
                            "signType":json.signType, //微信签名方式:
                            "paySign":json.paySign //微信签名
                        },
                        function(res){
                            if(res.err_msg == "get_brand_wcpay_request:ok" ){
                                // 使用以上方式判断前端返回,微信团队郑重提示:
                                //res.err_msg将在用户支付成功后返回ok,但并不保证它绝对可靠。
                                window.location.href = 'http://owenwx.ygkj8.cn/app/index.php?i=1&c=entry&a=wxapp&m=hotel_jm&do=paysucceed&order_id='+order_id;
                            }
                        });
                },
                'error': function(XMLHttpRequest, textStatus, errorThrown) {
                    alert("请求失败:" + XMLHttpRequest.status);
                }
            });
        }
   </script>
</head>
<body>
<br/>
<font color="#9ACD32"><b>该笔订单支付金额为<span style="color:#f00;font-size:50px">1分</span>钱</b></font><br/><br/>
<div align="center">
   <button style="width:210px; height:50px; border-radius: 15px;background-color:#FE6714; border:0px #FE6714 solid; cursor: pointer;  color:white;  font-size:16px;" type="button" onclick="onBridgeReady()" >立即支付</button>
</div>
</body>
</html>

接口方法

/**
     * 微信支付
     * @access public
     * @param null
     * @return array 返回类型
     * {
    "errno": 0,
    "message": "",
    "data": {
    "appId": "wx412359e77e1b1",
    "timeStamp": "1572319025",
    "nonceStr": "zg237y9123wlx83opu3muusu03wpt",
    "package": "prepay_id=wx29123ec43a85f1123462900",
    "signType": "MD5",
    "paySign": "78C5D9E6123D1F7F948A152D4"
    }
    }
     */
    public function doPagePay()
    {     
      $good_name = '商品名称';      
      $appid = $res["appid"];//公众号appid
      $openid = $this->openid;//用户微信openid
      $mch_id = $res["mchid"];//公众号支付商户号
      $key = $res["wxkey"];//公众号支付Api密钥
      $out_trade_no = $mch_id . time();//支付商户订单号
      $total_fee = $_GPC["money"];
      $total_fee = 0.01;
      $openid = 'onn6Bwf62aiyafBKQsPc072FIHrw';
      if (empty($total_fee)||!$good_name||!$total_fee) {
        return $this->result(10008, '参数错误', '');
      } else {
        $total_fee = floatval($total_fee * 100);
      }   
      $weixinpay = new WeixinPay($appid, $openid, $mch_id, $key, $out_trade_no, $good_name, $total_fee);
      $return = $weixinpay->pay();
      return $this->result(0, '', $return);
    }
    /**
     * 支付成功回调,微信查询订单
     *
     * @access public
     * @param null
     * @return array 返回类型
     */
    public function doPagePaysucceed(){
      $appid = $res["appid"];//公众号appid
      $openid = $this->openid;//用户微信openid
      $mch_id = $res["mchid"];//公众号支付商户号
      $key = $res["wxkey"];//公众号支付Api密钥
      $weixinpay = new WeixinPay($appid, $openid, $mch_id, $key, $out_trade_no, '', '');
      $orderquery = $weixinpay->wxOrderQuery();
      if ($orderquery['return_code']=='SUCCESS'){
        return $this->result(0, '支付成功', '');
      }else{
        return $this->result(0, '该订单支付失败', '');
      }
    }

01ebd755782e4c909dad0843d3544acf.jpeg

01ebd755782e4c909dad0843d3544acf.jpeg

父类wxpay.php

/**
   * 微信支付
   * 微信支付:JSAPI支付,订单查询,
   * @author      owenzhang
   * @version     1.0 
   */
<?php
class WeixinPay
{
  protected $appid;
  protected $mch_id;
  protected $key;
  protected $openid;
  protected $out_trade_no;
  protected $body;
  protected $total_fee;
  function __construct($appid, $openid, $mch_id, $key, $out_trade_no, $body, $total_fee)
  {
    $this->appid = $appid;
    $this->openid = $openid;
    $this->mch_id = $mch_id;
    $this->key = $key;
    $this->out_trade_no = $out_trade_no;
    $this->body = $body;
    $this->total_fee = $total_fee;
  }
  //微信JSAPI支付
  public function pay()
  {
    $return = $this->weixinapp();
    return $return;
  }
  //微信支付查询订单
  public function wxOrderQuery()
  {
    $return = $this->orderquery();
    return $return;
  }
  private function unifiedorder()
  {
    $url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
    $parameters = array("appid" => $this->appid, "mch_id" => $this->mch_id, "nonce_str" => $this->createNoncestr(), "body" => $this->body, "out_trade_no" => $this->out_trade_no, "total_fee" => $this->total_fee, "spbill_create_ip" => "192.168.0.161", "notify_url" => "http://www.weixin.qq.com/wxpay/pay.php", "openid" => $this->openid, "trade_type" => "JSAPI");
    $parameters["sign"] = $this->getSign($parameters);
    $xmlData = $this->arrayToXml($parameters);
    $return = $this->xmlToArray($this->postXmlCurl($xmlData, $url, 60));
    return $return;
  }
  private function orderquery()
  {
    $url = "https://api.mch.weixin.qq.com/pay/orderquery";
    $parameters = array("appid" => $this->appid, "mch_id" => $this->mch_id, "out_trade_no" => $this->out_trade_no, "nonce_str" => $this->createNoncestr(), "sign_type" => "MD5");
    $parameters["sign"] = $this->getSign($parameters);
    $xmlData = $this->arrayToXml($parameters);
    $return = $this->xmlToArray($this->postXmlCurl($xmlData, $url, 60));
    return $return;
  }
  private static function postXmlCurl($xml, $url, $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);
    curl_setopt($ch, CURLOPT_HEADER, FALSE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_POST, TRUE);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
    curl_setopt($ch, CURLOPT_TIMEOUT, 40);
    set_time_limit(0);
    $data = curl_exec($ch);
    if ($data) {
      curl_close($ch);
      return $data;
    } else {
      $error = curl_errno($ch);
      curl_close($ch);
      throw new WxPayException("curl出错,错误码:{$error}");
    }
  }
  private function arrayToXml($arr)
  {
    $xml = "<root>";
    foreach ($arr as $key => $val) {
      if (is_array($val)) {
        $xml .= "<" . $key . ">" . arrayToXml($val) . "</" . $key . ">";
      } else {
        $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
      }
    }
    $xml .= "</root>";
    return $xml;
  }
  private function xmlToArray($xml)
  {
    libxml_disable_entity_loader(true);
    $xmlstring = simplexml_load_string($xml, "SimpleXMLElement", LIBXML_NOCDATA);
    $val = json_decode(json_encode($xmlstring), true);
    return $val;
  }
  private function weixinapp()
  {
    $unifiedorder = $this->unifiedorder();
    $parameters = array("appId" => $this->appid, "timeStamp" => '' . time() . '', "nonceStr" => $this->createNoncestr(), "package" => "prepay_id=" . $unifiedorder["prepay_id"], "signType" => "MD5");
    $parameters["paySign"] = $this->getSign($parameters);
    return $parameters;
  }
  private function createNoncestr($length = 32)
  {
    $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
    $str = '';
    $i = 0;
    while ($i < $length) {
      $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
      $i++;
    }
    return $str;
  }
  private function getSign($Obj)
  {
    foreach ($Obj as $k => $v) {
      $Parameters[$k] = $v;
    }
    ksort($Parameters);
    $String = $this->formatBizQueryParaMap($Parameters, false);
    $String = $String . "&key=" . $this->key;
    $String = md5($String);
    $result_ = strtoupper($String);
    return $result_;
  }
  private function formatBizQueryParaMap($paraMap, $urlencode)
  {
    $buff = '';
    ksort($paraMap);
    foreach ($paraMap as $k => $v) {
      if ($urlencode) {
        $v = urlencode($v);
      }
      $buff .= $k . "=" . $v . "&";
    }
    $reqPar = '';
    if (strlen($buff) > 0) {
      $reqPar = substr($buff, 0, strlen($buff) - 1);
    }
    return $reqPar;
  }
}


目录
相关文章
|
5月前
|
PHP
微信公众号的程序接入 - PHP 版本源代码
微信公众号的程序接入 - PHP 版本源代码
微信公众号的程序接入 - PHP 版本源代码
ly~
|
1月前
|
存储 供应链 小程序
除了微信小程序,PHP 还可以用于开发哪些类型的小程序?
除了微信小程序,PHP 还可用于开发多种类型的小程序,包括支付宝小程序、百度智能小程序、抖音小程序、企业内部小程序及行业特定小程序。在电商、生活服务、资讯、工具、娱乐、营销等领域,PHP 能有效管理商品信息、订单处理、支付接口、内容抓取、复杂计算、游戏数据、活动规则等多种业务。同时,在企业内部,PHP 可提升工作效率,实现审批流程、文件共享、生产计划等功能;在医疗和教育等行业,PHP 能管理患者信息、在线问诊、课程资源、成绩查询等重要数据。
ly~
67 6
|
15天前
|
云安全 存储 小程序
PHP微信小程序解决方案PhpMall
PHP微信小程序解决方案PhpMall
29 0
|
4月前
|
PHP 开发工具
php免费用免认证的微信支付宝支付
php免费用免认证的微信支付宝支付
39 5
|
4月前
|
PHP
php使用curl新增微信临时素材(上传图片)
php使用curl新增微信临时素材(上传图片)
227 4
|
5月前
|
JavaScript Java 测试技术
基于微信小程序的家政服务预约系统的+php+vue.js附带文章和源代码设计说明文档ppt
基于微信小程序的家政服务预约系统的+php+vue.js附带文章和源代码设计说明文档ppt
57 3
基于微信小程序的家政服务预约系统的+php+vue.js附带文章和源代码设计说明文档ppt
|
4月前
|
PHP
PHP微信公众号投票活动系统源码
PHP微信公众号投票活动系统源码
160 11
|
4月前
|
PHP 移动开发 安全
PHP应用如何对接微信公众号JSAPI支付
本文介绍了微信支付的多种方式,包括JSAPI支付、APP支付、Native支付、付款码支付和H5支付。
49 8
|
3月前
|
移动开发 小程序 前端开发
php + h5使用 scheme页面跳转微信小程序-其他浏览器一键跳转到微信并打开小程序
php + h5使用 scheme页面跳转微信小程序-其他浏览器一键跳转到微信并打开小程序
92 0
|
3月前
|
缓存 前端开发 PHP
【超详细】php实现扫码关注微信公众号系统/网站自动注册登录
【超详细】php实现扫码关注微信公众号系统/网站自动注册登录
240 0