PHP laravel 微信 JsApi 支付详细过程

2 篇文章 0 订阅
1 :下载微信支付 sdk(php),下载地址 https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=11_1

在这里插入图片描述

下载完成之后,我是直接解压将整个 sdk文件夹放到根目录下的 verdor 目录中,然后将 sdk 文件夹下 example 中的WxPay开头的文件和 log.php 文件复制到 lib 目录下

在这里插入图片描述

2 :把lib文件夹中的以每个文件中的所有的require_once中的路径去掉,改为当前文件夹下调用

在这里插入图片描述

3 :最重要的一步,修改配置文件 WxPay.Config.php
<?php

require_once "WxPay.Config.Interface.php";

/**
*
* 该类需要业务自己继承, 该类只是作为deamon使用
* 实际部署时,请务必保管自己的商户密钥,证书等
* 
*/

class WxPayConfig extends WxPayConfigInterface
{
	//=======【基本信息设置】=====================================
	/**
	 * TODO: 修改这里配置为您自己申请的商户信息
	 * 微信公众号信息配置
	 * 
	 * APPID:绑定支付的APPID(必须配置,开户邮件中可查看)
	 * 
	 * MCHID:商户号(必须配置,开户邮件中可查看)
	 * 
	 */
	public function GetAppId()
	{
		return 'wx8888888888888888';
	}
	public function GetMerchantId()
	{
		return '8888888888';
	}
	
	//=======【支付相关配置:支付成功回调地址/签名方式】===================================
	/**
	* TODO:支付回调url
	* 签名和验证签名方式, 支持md5和sha256方式
	**/
	public function GetNotifyUrl()
	{
		return "";
	}
	public function GetSignType()
	{
		return "HMAC-SHA256";
	}

	//=======【curl代理设置】===================================
	/**
	 * TODO:这里设置代理机器,只有需要代理的时候才设置,不需要代理,请设置为0.0.0.0和0
	 * 本例程通过curl使用HTTP POST方法,此处可修改代理服务器,
	 * 默认CURL_PROXY_HOST=0.0.0.0和CURL_PROXY_PORT=0,此时不开启代理(如有需要才设置)
	 * @var unknown_type
	 */
	public function GetProxy(&$proxyHost, &$proxyPort)
	{
		$proxyHost = "0.0.0.0";
		$proxyPort = 0;
	}
	

	//=======【上报信息配置】===================================
	/**
	 * TODO:接口调用上报等级,默认紧错误上报(注意:上报超时间为【1s】,上报无论成败【永不抛出异常】,
	 * 不会影响接口调用流程),开启上报之后,方便微信监控请求调用的质量,建议至少
	 * 开启错误上报。
	 * 上报等级,0.关闭上报; 1.仅错误出错上报; 2.全量上报
	 * @var int
	 */
	public function GetReportLevenl()
	{
		return 1;
	}


	//=======【商户密钥信息-需要业务方继承】===================================
	/*
	 * KEY:商户支付密钥,参考开户邮件设置(必须配置,登录商户平台自行设置), 请妥善保管, 避免密钥泄露
	 * 设置地址:https://pay.weixin.qq.com/index.php/account/api_cert
	 * 
	 * APPSECRET:公众帐号secert(仅JSAPI支付的时候需要配置, 登录公众平台,进入开发者中心可设置), 请妥善保管, 避免密钥泄露
	 * 获取地址:https://mp.weixin.qq.com/advanced/advanced?action=dev&t=advanced/dev&token=2005451881&lang=zh_CN
	 * @var string
	 */
	public function GetKey()
	{
		return 'wx888888888888888888888888888888';
	}
	public function GetAppSecret()
	{
		return 'wx888888888888888888888888888888';
	}


	//=======【证书路径设置-需要业务方继承】=====================================
	/**
	 * TODO:设置商户证书路径
	 * 证书路径,注意应该填写绝对路径(仅退款、撤销订单时需要,可登录商户平台下载,
	 * API证书下载地址:https://pay.weixin.qq.com/index.php/account/api_cert,下载之前需要安装商户操作证书)
	 * 注意:
	 * 1.证书文件不能放在web服务器虚拟目录,应放在有访问权限控制的目录中,防止被他人下载;
	 * 2.建议将证书文件名改为复杂且不容易猜测的文件名;
	 * 3.商户服务器要做好病毒和木马防护工作,不被非法侵入者窃取证书文件。
	 * @var path
	 */
	public function GetSSLCertPath(&$sslCertPath, &$sslKeyPath)
	{
		$sslCertPath = '../cert/apiclient_cert.pem';
		$sslKeyPath = '../cert/apiclient_key.pem';
	}
}

4 : 配置文件中关键参数的位置以及微信支付的授权配置

AppId和AppSecert是微信公众号(服务号)申请时的,申请的微信公众号必须已经通过微信认证。
在这里插入图片描述
微信支付商户号和商户密钥是在微信支付的官方申请的商户号,申请后会有一个商户密钥
在这里插入图片描述
在这里插入图片描述
在微信支付中关联公众号
在这里插入图片描述
在微信公众号中设置接口权限,登录公众号,开发—接口权限—功能服务—网页授权
在这里插入图片描述
在接口域名处填写微信支付发起的域名
在这里插入图片描述

5 : 后台控制器的写法

我的控制器是写在 /app/Http/Controller/Pay 下新建 WxpayController.php

 <?php

namespace App\Http\Controllers\Pay;


use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redis;

require_once "vendor/wxpaysdk/lib/WxPay.Api.php";
require_once "vendor/wxpaysdk/lib/WxPay.NativePay.php";
require_once "vendor/wxpaysdk/lib/phpqrcode/phpqrcode.php";
require_once "vendor/wxpaysdk/lib/WxPay.JsApiPay.php";
require_once "vendor/wxpaysdk/lib/WxPay.Config.php";

class WxpayController extends Controller
{
    public function jsApiPay()
    {
    	// 下面这部分是判断商品的库存和订单信息,以下仅供参考
        $redis_goods_stock = 0;
        $goods_info = [];
        // redis 获取商品信息
        $redis_activity_goods = Redis::get('redis_activity_goods');
        if($redis_activity_goods){
            $goods_info = json_decode($redis_activity_goods,true);
            if(!empty($goods_info)){
                 // redis 获取商品库存
                $redis_goods_stock = Redis::get('redis_goods_stock');
                if($redis_goods_stock){
                    $redis_goods_stock = json_decode($redis_goods_stock,true);
                }
            }
        }

        if(!$redis_goods_stock || !$goods_info){
            echo '库存不足';exit;return false;
        }
		// 验证商品信息及库存信息结束,以上仅供参考
		

        //①、获取用户openid
        try{
            $res = [];
            $res['priceTotal'] = 0.01; // 必要参数,订单总金额

            //调起微信支付jsApi接口
            $tools = new \JsApiPay();
            $openId = $tools->GetOpenid();
            //②、统一下单
            $input = new \WxPayUnifiedOrder();
            $input->SetBody("test");
            $input->SetAttach("test");
            $input->SetOut_trade_no("yh".date("YmdHis"));
            $input->SetTotal_fee((string)($res['priceTotal']*100));
            $input->SetTime_start(date("YmdHis"));
            $input->SetTime_expire(date("YmdHis", time() + 600));
            $input->SetGoods_tag("test");
            $input->SetNotify_url("这里配置支付完成后的回调路径,用来一步处理商品订单信息");
            $input->SetTrade_type("JSAPI");
            $input->SetOpenid($openId);
            $config = new \WxPayConfig();
            $order = \WxPayApi::unifiedOrder($config, $input);

            $res['jsApiParameters'] = $tools->GetJsApiParameters($order);
            //获取共享收货地址js函数参数
            $res['editAddress'] = $tools->GetEditAddressParameters();
            return view('/pay/jsapi_pay',$res);
        } 
        catch(Exception $e) 
        {
            echo $e;
            exit;
            // Log::ERROR(json_encode($e));
        }
    }
}

5 : 前台页面写法 jsapi_pay.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <link type="text/css" rel="stylesheet" href="{{asset('static/layui/css/layui.css')}}">
    <script type="text/javascript" src="{{asset('static/common/js/jquery-2.0.0.min.js')}}"></script>
    <script src="{{asset('static/layer/jquery.js?v=1.83.min')}}"></script>
    <script src="{{asset('static/layer/layer.min.js')}}"></script>
    <script type="text/javascript" src="{{asset('static/layui/layui.all.js')}}"></script>

    <title>支付订单</title>
    <script type="text/javascript">
        layui.use(['layer'],function(){
                   $ = layui.jquery;            
                   });
           //调用微信JS api 支付
               function jsApiCall()
               {
                   var jsApiPar =JSON.parse($('input[name="jsApiPar"]').val());
                   WeixinJSBridge.invoke(
                       'getBrandWCPayRequest',
                       jsApiPar,
                       function(res){
                           WeixinJSBridge.log(res.err_msg);
                           if( res.err_msg == 'get_brand_wcpay_request:ok'){
                           		// 这个是判断支付成功后,可以进行的页面操作,我是直接跳转到首页 
                           		window.location.href = '/';
                           }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">
                //获取共享地址
                function editAddress()
               {               
                   var editAdd =JSON.parse($('input[name="editAdd"]').val());
                   WeixinJSBridge.invoke(
                       'editAddress',
                       editAdd,
                       function(res){
                           $('div[name="test"]').text(JSON.parse(res));
                           var value1 = res.proviceFirstStageName;
                           var value2 = res.addressCitySecondStageName;
                           var value3 = res.addressCountiesThirdStageName;
                           var value4 = res.addressDetailInfo;
                           var tel = res.telNumber;
                           alert(value1 + value2 + value3 + value4 + ":" + tel);
                       }
                   );
               }   
               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>
</head>
<body>
    <br/>
    <p color="#d22930" style="text-align:center;margin-top:80px;">
      <span>支付金额</span><br/><br/>
      <span style="color:#f00;font-size:40px">¥ {{$priceTotal}}</span>
    </p><br/><br/>
    <div align="center">
        <button style="width:210px; height:50px; border-radius: 15px;background-color:#d22930; border:0px #d22930 solid; cursor: pointer;  color:white;  font-size:16px;" type="button" onclick="callpay()" >立即支付</button>
        <input type="hidden" name="jsApiPar" value="{{$jsApiParameters}}">
        <input type="hidden" name="editAdd" value="{{$editAddress}}">
    </div>
</body>
</html>
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值