jsapi微信支付个人心得

在一星期之前吧,我开始接触微信,最微信支付,最开始也是一脸懵逼,还好吧,我请教大神,完美解决支付问题,下面直接上干货。

首先要准备微信支付模块,就是微信支付宝,官方是一个zip压缩文件

WxpayAPI_php_v3.zip

然后解压放在项目根路径也可以。

如果说你是只需要绑定一个商户

const APPID = 'xxxxxxxx';
const MCHID = 'xxxxxxxx';
const KEY = 'xxxxxxxxx';
const APPSECRET = 'xxxxxxxxx';

  

你的微信配置文件可以写死 文件在微信支付模块lib文件夹下 WxPay.Config.php

主要的配置实在微信支付模块example下 jsapi.php 这是最重要的文件 我们的主要操作都是在这里面

ini_set('date.timezone','Asia/Shanghai');
ini_set('display_errors','Off');
error_reporting(E_ERROR);
require_once  '../../../tp5/mydatabase.php';
require_once "../lib/WxPay.Api.php";
require_once "WxPay.JsApiPay.php";
require_once 'log.php';

  最开始我们要引入配置支付文件 楼主给支付配置文件起的名字叫做mydatabases.php 楼主的微信支付文件夹是两层所以是../../../

const USERNAME=USERNAME;
const  PASSWORD=PASSWORD;
const DATABASE=DATABASE;

  先设定几个变量 楼主是查数据库去取APPID APPSECRET KEY MCHID

//数据库连接
$conn = mysqli_connect('localhost',USERNAME,PASSWORD);
if ($conn) {
	$db = mysqli_select_db($conn,DATABASE);
	if ($db) {
		mysqli_set_charset($conn,'utf8');
		$sql = 'select * from activity where activity_id = '.$_COOKIE["activity_id"].'';
		$result = mysqli_query($conn,$sql);
		if ($result) {
			while ($row = mysqli_fetch_array($result)) {
				$fee = $row["activity_paymoney"];
				$body = $row["activity_title"];
				//var_dump($row);
			}
		} else {
			echo '数据库查询失败';
		}
	} else {
		echo '链接数据库';
	}
} else {
	echo '登陆数据库失败';
}

  所以接下来查询数据库

$tools = new JsApiPay();
$openId = $tools->GetOpenid();

  ①、获取用户openid

$input = new WxPayUnifiedOrder();
$input->SetBody($body);
$input->SetAttach($_COOKIE["activity_id"]);
$input->SetOut_trade_no(WxPayConfig::MCHID.date("YmdHis"));
$input->SetTotal_fee($fee*100);
$input->SetTime_start(date("YmdHis"));
$input->SetTime_expire(date("YmdHis",time() + 600));
$input->SetGoods_tag("test");
$input->SetNotify_url(MYMYURL."/wxpay/wxpay/example/notify.php");
$input->SetTrade_type("JSAPI");
$input->SetOpenid($openId);
$order = WxPayApi::unifiedOrder($input);
$jsApiParameters = $tools->GetJsApiParameters($order);

  ②、统一下单 一定要配置SetNotify_url SetTime_expire-》600是指即时到账 如果希望时间晚点到账 ,可以调整数字大小

mysqli_close($conn);

  数据库关闭

<html>
<head>
    <meta http-equiv="content-type" content="text/html;charset=utf-8"/>
    <title>微信支付</title>
	<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0,maximum-scale=1.0, user-scalable=no">
    <link rel="stylesheet" href="/home/css/pay.css">
    <link rel="stylesheet" href="/home/css/reset.css">
<script src="/home/js/jquery-1.8.3.min.js"></script>
<script src="/home/js/jquery.cookie.js"></script>
<script type="text/javascript">
    var html = document.querySelector('html');
    html.style.fontSize = html.offsetWidth / 7.2 + 'px';
    addEventListener('resize', function() {
        html.style.fontSize = html.offsetWidth / 7.2 + 'px';
    }, false);
</script>
    <script type="text/javascript">
	//调用微信JS api 支付
	function jsApiCall()
	{
		WeixinJSBridge.invoke(
			'getBrandWCPayRequest',
			<?php echo $jsApiParameters; ?>,
			function(res){
				WeixinJSBridge.log(res.err_msg);
				// alert(res.err_code+res.err_desc+res.err_msg);
				if (res.err_msg == "get_brand_wcpay_request:ok") { 
                    window.location.href = "/tp5/public/users/index/index?id="+$.cookie('activity_id')+"&olduid="+$.cookie('openid');
				} else {
					alert('取消支付');
					window.location.href = "/tp5/public/users/index/index?id="+$.cookie('activity_id')+"&olduid="+$.cookie('openid'); 
				}
			}
		);
	}
	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();
		}
	}
        function cancel(){
                    // window.history.go(-1);
                     window.location.href = "/tp5/public/users/index/index?id="+$.cookie('activity_id')+"&olduid="+$.cookie('openid');  
               }
	</script>
</head>
<body>
    <div id="pay">
    <div class="wrap">
      <div class="order">
        <div class="order-in"><p style="border-bottom: 0.05rem solid #fd908d;margin: 1.1rem auto;color:#fff;font-size: 0.4rem;width:50vw;line-height: 1rem;">订单金额</p></div>
        <div class="order-in"><p style="color: #eefe00;line-height: 1rem;"><span class="fee"><?php echo $fee; ?></span>元</p></div>
      </div>
      <div class="pay" onclick="callpay()">微信支付</div>
      <div class="cancelpay" onclick="cancel()">取消支付</div>
        <div class="blank">
            <p class="zf"><a href="http://maidian.winyx.net/about.aspx" style="font-weight:900;font-family:'Microsoft YaHei';">技术支持:</a></p>
        </div>
    </div>
    </div>
</body>
</html>

  

支付的自定义html

接下来是notify.php文件 这个文件主要是修改数据库状态

require_once  '../../../tp5/mydatabase.php';
require_once "../lib/WxPay.Api.php";
require_once '../lib/WxPay.Notify.php';
require_once 'log.php';
require_once  'Tixian.php';

  引入数据库文件配置

public function NotifyProcess($data, &$msg){
  Log::DEBUG("call back:" . json_encode($data));
  $notfiyOutput = array();
    if(!array_key_exists("transaction_id", $data)){
    $msg = "输入参数不正确";
    return false;

  }
}

  //查询订单,判断订单真实性

if(!$this->Queryorder($data["transaction_id"])){
	$msg = "订单查询失败";
	return false;
}

  

        //从这里开始链接数据库
		$_COOKIE['openid1']=$data['openid'];
                $_COOKIE['activity_id1']=$data['attach']; 
		//修改数据的微信订单和付款时间
		//连接数据库
		$conn=mysqli_connect('localhost',USERNAME,PASSWORD);
		mysqli_select_db($conn,DATABASE);
		mysqli_set_charset($conn,'utf8');//设置字符集
		//准备sql语句
		$paymoney="select * from activity where activity_id='{$data['attach']}'";//查询活动金额
                   $paymoneys=mysqli_query($conn,$paymoney);
                   while ($row = mysqli_fetch_array($paymoneys)) {
				$fee = $row["activity_paymoney"];
                 }
		$sql="update users set pay_wx_order='{$data['transaction_id']}',pay_time='{$data['time_end']}',money_self={$fee},state=1 where openid='{$data['openid']}' and activity_id='{$data['attach']}'";
		$result=mysqli_query($conn,$sql);
	//======把支付数据写入数据库开始==============================================-
        $chaxun="select * from tixian where openid='{$data['openid']}' and activity_id='{$data['attach']}'";
        $chaxuns=mysqli_query($conn,$chaxun);
        $chaxunss=mysqli_fetch_array($chaxuns);
         //执行插入数据
        if($chaxunss){
        }else{     
               $time=date('Y-m-d H:i:s',time());
               $tixian="insert into tixian  value(null,'{$data['openid']}',3,{$data['attach']},'{$time}',null,null)"; 
               $tixians=mysqli_query($conn,$tixian);
        }
        $rechaxun="select * from tixian where openid='{$data['openid']}' and activity_id='{$data['attach']}'";
        $rechaxuns=mysqli_query($conn,$rechaxun);
         while($rechaxunss=mysqli_fetch_array($rechaxuns)){
               $tixian_state=$rechaxunss['state'];
         }
       if($tixian_state==3){
          //执行更新提现状态
          $gengxin="update tixian set state=2 where openid='{$data['openid']}' and activity_id='{$data['attach']}'";
          $gengxins=mysqli_query($conn,$gengxin);
          //执行提现代码
          //提现类外边,就是最下边写
	      $tt=new Tixian();
	      $tt->actionAct_tixian();
       }
       //=========================================================
        mysqli_close($conn);
        return SUCCESS;//通知微信收到数据   
	}
}

  

重写回调处理函数里边处理状态

接下来 就是配置服务器的什么回调地址 什么的 做这个就不说了 微信解释的挺清楚地 好了 今天教程将就到这里了 有问题 大家评论留言 楼主尽力解答 原创不易 受教了 

上一篇:[CF套题] CF-1201


下一篇:微信支付之公众号支付源码-亲测可用