微信公众号支付

分类首页日期1年前访问605评论0
<?php
header("Content-type: text/html; charset=utf-8");
require_once "wxpay/lib/WxPay.Api.php";
require_once "wxpay/example/WxPay.JsApiPay.php";
require_once "wxpay/example/WxPay.Config.php";
require_once 'wxpay/example/log.php';
////////////////////////////////
$time = time();

//①、获取用户openid
try {

  $tools = new JsApiPay();
  $openId = $tools->GetOpenid();
  //②、统一下单
  $input = new WxPayUnifiedOrder();
  $input->SetBody("test");
  $input->SetAttach("test");
  $input->SetOut_trade_no("sdkphp" . date("YmdHis"));
  $input->SetTotal_fee("1000");
  $input->SetTime_start(date("YmdHis"));
  $input->SetTime_expire(date("YmdHis", $time + 600));
  $input->SetGoods_tag("test");
  $input->SetNotify_url("http://mall.elss.com.cn/pay/notify.php"); // http://paysdk.weixin.qq.com/notify.php
  $input->SetTrade_type("JSAPI");

  $input->SetOpenid($openId);
  $config = new WxPayConfig();
  $order = WxPayApi::unifiedOrder($config, $input);
  if (!empty($order['return_code']) && $order['return_code'] == 'FAIL') {
    echo $order['return_msg'];
    return;
  }
  $order['timeStamp'] = (string)$time;
  $jsApiParameters = $tools->GetJsApiParameters($order);
  //获取共享收货地址js函数参数
  $editAddress = $tools->GetEditAddressParameters();
} catch (Exception $e) {
  Log::ERROR(json_encode($e));
}
?>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
  <title>百奥盛康</title>
  <link rel="stylesheet" href="/index/css/bootstrap.min.css">
  <link rel="stylesheet" type="text/css" href="/index/css/style.css">
  <link href="/index/css/sheep.css" rel="stylesheet" type="text/css" />
  <script src="/index/js/jquery-1.11.1.js" language="javascript"></script>
  <link href="/index/css/address.css" rel="stylesheet" type="text/css" />
  <script src="http://res.wx.qq.com/open/js/jweixin-1.1.0.js"></script>
</head>

<body style="background:#f4f7fe;">
  <div class="qyfpwhite">
    <?php if (!empty($res['xprice'])) { ?>
      <p style="color:#fe8119; font-size:18px; font-weight:bold; line-height:40px;"><?php echo "电子卡"; ?></p>
      <?php foreach ($xcard as $k => $v) { ?>

        <?php if ($v['price'] == 600) { ?>
          <img src="/index/images/zsk.png" class="viewimg">
        <?php } elseif ($v['price'] == 500) { ?>
          <img src="/index/images/jk.png" class="viewimg">
        <?php } elseif ($v['price'] == 300) { ?>
          <img src="/index/images/yk.png" class="viewimg">
        <?php } elseif ($v['price'] == 200) { ?>
          <img src="/index/images/lk.png" class="viewimg">
        <?php } ?>
        <!-- <img src="images/fp_03.jpg" class="viewimg" /> -->
        <p style="line-height:30px;"><?php echo "【盛康星礼卡】"; ?></p>
        <p style="color:#fe8119; line-height:30px;"><?php echo "¥"; ?><span class="lbsize4"><?php echo $v['price']; ?></span><span style="color:#ccc;"><?php echo "X"; ?><?php echo $v['num']; ?></span></p>
    <?php }
    } ?>
    <?php if (!empty($res['sprice'])) { ?>
      <p><?php echo "实体卡"; ?></p>
      <?php foreach ($scard as $k => $v) { ?>

        <?php if ($v['price'] == 600) { ?>
          <img src="/index/images/zsk.png" class="viewimg">
        <?php } elseif ($v['price'] == 500) { ?>
          <img src="/index/images/jk.png" class="viewimg">
        <?php } elseif ($v['price'] == 300) { ?>
          <img src="/index/images/yk.png" class="viewimg">
        <?php } elseif ($v['price'] == 200) { ?>
          <img src="/index/images/lk.png" class="viewimg">
        <?php } ?>
        <!-- <img src="images/fp_03.jpg" class="viewimg" /> -->
        <p><?php echo "【盛康星礼卡】"; ?></p>
        <p style="color:#fe8119;"><?php echo "¥"; ?><span class="lbsize4"><?php echo $v['price']; ?></span><span style="color:#ccc;"><?php echo "X"; ?><?php echo $v['num']; ?></span></p>
    <?php }
    } ?>
    <p>
    <table width="100%" border="0" class="fptable">
      <tr>
        <td width="30%">商品总价</td>
        <td align="right">¥<?php echo $res['price']; ?></td>
      </tr>
      <tr>
        <td width="30%">运费</td>
        <td align="right">¥<?php echo $yunfei; ?></td>
      </tr>
      <tr>
        <td width="30%">订单总价</td>
        <td align="right">¥<?php echo $dzprice; ?></td>
      </tr>
    </table>
    </p>
  </div>
  <div class="qyfpwhite">
    <p>
    <table width="100%" border="0" class="fptable">
      <tr>
        <td>订单编号:<?php echo $res['card_sn']; ?></td>
      </tr>
      <tr>
        <td>下单时间:<?php echo $res['create_time']; ?></td>
      </tr>
      <tr>
        <td><span style="color:#f00;" id="fapiao">如需开发票请点击这里</span></td>
      </tr>
    </table>
    </p>
  </div>
  <div class="pinyang">
    <input type="hidden" id='ordersn' value="<?php echo $res['card_sn']; ?>">
    <input type="hidden" id='price' value="<?php echo $dzprice; ?>">
    <input type="hidden" id='yunfei' value="<?php echo $yunfei; ?>">
    <div class="pinyangbtn" style="float:right; width:100%" id="payButton" onclick="callpay()">去支付</div>
  </div>
</body>

</html>
<!-- <script type="text/javascript">
	function gopay()
	{
		var sn=$('#ordersn').val();
		var price=$('#price').val();
		$.post('index.php',{ordersn:sn,price:price})
	}
</script> -->
<div class="qyfpbxo" style="display:none; margin-bottom:80px;">

  <div class="qyfpwhite">
    <table width="100%" border="0" class="fptable">
      <!-- <tr>
            <td width="30%">发票类型</td>
            <td align="right">增值税纸质普通发票</td>
          </tr> -->
      <input type="hidden" id='id' value="<?php echo $id; ?>" name="">
      <tr>
        <td>抬头类型</td>
        <td align="right">
          <input name="type" type="radio" value="0" checked="checked" />个人或事业单位&nbsp;&nbsp;
          <input name="type" type="radio" value="1" />企业
        </td>
      </tr>
    </table>
    <div id="grtable">
      <table width="100%" border="0" class="fptable">
        <tr>
          <td width="30%">发票抬头</td>
          <td width="70%" align="right"><input name="taitou" id="taitou" type="text" placeholder="个人" class="inputtt" /></td>
        </tr>
        <tr>
          <td>邮箱地址</td>
          <td align="right"><input name="e_mail" id="e_mail" type="text" placeholder="必填" class="inputtt" /></td>
        </tr>
      </table>
    </div>
    <div id="qytable">
      <table width="100%" border="0" class="fptable">
        <tr>
          <td width="30%">发票抬头</td>
          <td width="70%" align="right"><input name="taitou" id="taitou1" type="text" placeholder="必填" class="inputtt" /></td>
        </tr>
        <tr>
          <td>税号</td>
          <td align="right"><input name="shuihao" type="text" id="shuihao" placeholder="税号必填" class="inputtt" /></td>
        </tr>
        <tr>
          <td>开户银行</td>
          <td align="right"><input name="kaihuhang" id="kaihuhang" type="text" placeholder="选填" class="inputtt" /></td>
        </tr>
        <tr>
          <td>银行账号</td>
          <td align="right"><input name="zhanghao" id="zhanghao" type="text" placeholder="选填" class="inputtt" /></td>
        </tr>
        <tr>
          <td>企业地址</td>
          <td align="right"><input name="dizhi" id="dizhi" type="text" placeholder="选填" class="inputtt" /></td>
        </tr>
        <tr>
          <td>企业电话</td>
          <td align="right"><input name="dianhua" id="dianhua" type="text" placeholder="选填" class="inputtt" /></td>
        </tr>
        <tr>
          <td>邮箱地址</td>
          <td align="right"><input name="e_mail1" id="e_mail1" type="text" placeholder="必填" class="inputtt" /></td>
        </tr>
      </table>
    </div>
  </div>
  <input name="" type="button" class="btntjsq" onclick="tijiao()" value="提交申请" />
</div>
<script src="/index/js/jquery.min.js"></script>
<script>
  $(document).ready(function() {
    $('input[type=radio][name=type]').change(function() {
      var val = $('input:radio[name="type"]:checked').val();
      if (val == 0) {
        //alert("选中第一个!");
        $("#grtable").css("display", "block");
        $("#gryx").css("display", "block");
        $("#qytable").css("display", "none");
      } else if (val == 1) {
        //grtablealert("选中第二个!");
        $("#qytable").css("display", "block");
        $("#gryx").css("display", "none");
        $("#grtable").css("display", "none");
      }
    });
    $("#fapiao").click(function() {
      $(".qyfpbxo").toggle();
    });
  });

  function tijiao() {
    var type = $('input:radio[name="type"]:checked').val(); //发票类型
    var taitou = $('#taitou').val(); //发票抬头
    var taitou1 = $('#taitou1').val(); //发票抬头
    var shuihao = $('#shuihao').val(); //税号
    var kaihuhang = $('#kaihuhang').val(); //开户行
    var zhanghao = $('#zhanghao').val(); //账号
    var dizhi = $('#dizhi').val(); //公司地址
    var dianhua = $('#dianhua').val(); //公司电话
    var e_mail = $('#e_mail').val(); //收票邮箱
    var e_mail1 = $('#e_mail1').val(); //收票邮箱
    var id = $('#id').val();

    var myreg = /^([\.a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;

    if (type == 0) {
      console.log(type, taitou, shuihao, kaihuhang, zhanghao, dizhi, dianhua, e_mail, id);
      if (!myreg.test(e_mail)) {
        alert("请输入正确邮箱地址");
      } else {
        $.post('xiadan.php?act=tijiao&id=' + id, {
          type: type,
          taitou: taitou,
          shuihao: shuihao,
          kaihuhang: kaihuhang,
          zhanghao: zhanghao,
          dizhi: dizhi,
          dianhua: dianhua,
          e_mail: e_mail,
          id: id
        }, function(res) {
          if (res.code == 1) {
            location.reload();
          } else {
            alert(res.msg);
          }
        }, 'json')
      }
    } else if (type == 1) {
      console.log(type, taitou1, shuihao, kaihuhang, zhanghao, dizhi, dianhua, e_mail1, id);
      if (!myreg.test(e_mail1)) {
        alert("请输入正确邮箱地址");
      } else {
        $.post('xiadan.php?act=tijiao&id=' + id, {
          type: type,
          taitou: taitou1,
          shuihao: shuihao,
          kaihuhang: kaihuhang,
          zhanghao: zhanghao,
          dizhi: dizhi,
          dianhua: dianhua,
          e_mail: e_mail1,
          id: id
        }, function(res) {
          if (res.code == 1) {
            location.reload();
          } else {
            alert(res.msg);
          }
        }, 'json')
      }
    }



  }
</script>
<script type="text/javascript">

  wx.config({
    debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
    appId: '<?php echo $order['appid']; ?>', // 必填,公众号的唯一标识
    timestamp: '', // 必填,生成签名的时间戳
    nonceStr: '', // 必填,生成签名的随机串
    signature: '', // 必填,签名,见附录1
    jsApiList: ['chooseWXPay'] // 必填,需要使用的JS接口列表,这里只写支付的

  });
  //调用微信JS api 支付
  function jsApiCall() {
    WeixinJSBridge.invoke(
      'getBrandWCPayRequest',
      <?php if ($jsApiParameters) {
        echo $jsApiParameters . ',';
      } else {
        echo '{},';
      }  ?>
      function(res) {
        WeixinJSBridge.log(res.err_msg);
        if (res.err_msg == 'get_brand_wcpay_request:cancel') {
          alert('已取消支付');
        } else if (res.err_msg == 'get_brand_wcpay_request:ok') {
          alert('支付成功!');
          window.close();
          window.location.href = "user.php";
          message.success("支付成功", 5)
        } else {
          alert('支付失败!');
        }
      }
    );
  }

  function callpay() {
    if (typeof WeixinJSBridge == "undefined") {
      if (document.addEventListener) {
        document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
      } else if (document.attachEvent) {
        document.attachEvent('WeixinJSBridgeReady', jsApiCall);
        document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
      }
    } else {

      jsApiCall();
    }
  }
</script>
<script type="text/javascript">
  var ui = {
      payButton: $("#payButton")
    },
    payObj = {},
    orderNo = '';
  //支付按鈕點擊事件
  var sn = $('#ordersn').val();
  var price = $('#price').val();
  var yunfei = $('#yunfei').val();
  //获取共享地址
  function editAddress() {
    WeixinJSBridge.invoke(
      'editAddress',
      <?php if ($editAddress) {
        echo $editAddress . ',';
      } else {
        echo '{},';
      }  ?>
      function(res) {
        console.log(res)
        var value1 = res.proviceFirstStageName;
        var value2 = res.addressCitySecondStageName;
        var value3 = res.addressCountiesThirdStageName;
        var value4 = res.addressDetailInfo;
        var tel = res.telNumber;
      }
    );
  }

  window.onload = function() {
    if (typeof WeixinJSBridge == "undefined") {
      if (document.addEventListener) {
        document.addEventListener('WeixinJSBridgeReady', editAddress, false);
      } else if (document.attachEvent) {
        document.attachEvent('WeixinJSBridgeReady', editAddress);
        document.attachEvent('onWeixinJSBridgeReady', editAddress);
      }
    } else {
      editAddress();
    }
  };
</script>

支付配置参数在SDK包的'example/WxPay.Config.php'配置

SDK文件下载:weixinpay.zip

回调:

<?php
ini_set('date.timezone', 'Asia/Shanghai');

//error_reporting(E_ERROR);
require_once "wxpay/lib/WxPay.Api.php";
require_once 'wxpay/lib/WxPay.Notify.php';
require_once 'wxpay/example/log.php';
require_once "wxpay/example/WxPay.Config.php";


//初始化日志
$logHandler = new CLogFileHandler("wxpay/logs/" . date('Y-m-d') . '.log');
$log = Log::Init($logHandler, 15);
//Log::DEBUG("begin notify".time());

class PayNotifyCallBack extends WxPayNotify
{
      //查询订单
      public function Queryorder($transaction_id)
      {
            $input = new WxPayOrderQuery();
            $input->SetTransaction_id($transaction_id);

            $config = new WxPayConfig();
            $result = WxPayApi::orderQuery($config, $input);
            Log::DEBUG("query:" . json_encode($result));
            if (
                  array_key_exists("return_code", $result)
                  && array_key_exists("result_code", $result)
                  && $result["return_code"] == "SUCCESS"
                  && $result["result_code"] == "SUCCESS"
            ) {
                  return true;
            }
            return false;
      }

      /**
       *
       * 回包前的回调方法
       * 业务可以继承该方法,打印日志方便定位
       * @param string $xmlData 返回的xml参数
       *
       **/
      public function LogAfterProcess($xmlData)
      {
            Log::DEBUG("call back, return xml:" . $xmlData);
            return;
      }

      //重写回调处理函数
      /**
       * @param WxPayNotifyResults $data 回调解释出的参数
       * @param WxPayConfigInterface $config
       * @param string $msg 如果回调处理失败,可以将错误信息输出到该方法
       * @return true回调出来完成不需要继续回调,false回调处理未完成需要继续回调
       */
      public function NotifyProcess($objData, $config, &$msg)
      {
            $rstatus = false;
            $data = $objData->GetValues();
            //TODO 1、进行参数校验
            if (
                  !array_key_exists("return_code", $data)
                  || (array_key_exists("return_code", $data) && $data['return_code'] != "SUCCESS")
            ) {
                  //TODO失败,不是支付成功的通知
                  //如果有需要可以做失败时候的一些清理处理,并且做一些监控
                  $msg = "异常异常";
                  return false;
            }
            if (!array_key_exists("transaction_id", $data)) {
                  $msg = "输入参数不正确";
                  return false;
            }

            //TODO 2、进行签名验证
            try {
                  $checkResult = $objData->CheckSign($config);
                  if ($checkResult == false) {
                        //签名错误
                        Log::ERROR("签名错误...");
                        return false;
                  }
            } catch (Exception $e) {
                  Log::ERROR(json_encode($e));
            }

            //TODO 3、处理业务逻辑
            Log::DEBUG("call back:" . json_encode($data));
            $notfiyOutput = array();


            //查询订单,判断订单真实性
            if (!$this->Queryorder($data["transaction_id"])) {
                  $msg = "订单查询失败";
                  return false;
            }
            //回调成功逻辑代码
            //////////////////////////////
            //查询订单
          
            $result = $GLOBALS["db"]->getRow("select * from card_order where card_sn='$out_trade_no'");
          
            //修改订单状态
            $rstatus = $GLOBALS["db"]->query("update card_order set `status`=1,`update_time`='$update_time' where card_sn='$out_trade_no'");
            
            ///////////////////////////////
            if ($rstatus) {
                  $file = fopen('order.log', 'a+');
                  fwrite($file, "支付成功" . ' 操作时间:' . date("Y-m-d H:i:s") . $data['out_trade_no'] . "\r\n");
                  echo 1;
                  return true;
            } else {
                  $msg = "订单查询失败";
                  $file = fopen('order.log', 'a+');
                  fwrite($file, "支付成功,修改订单失败" . ' 操作时间:' . date("Y-m-d H:i:s") .  json_encode($data) . "\r\n");
                  return false;
            }
            //



      }
}

$config = new WxPayConfig();
Log::DEBUG("begin notify");
$notify = new PayNotifyCallBack();
$notify->Handle($config, false);