tp5使用微信H5支付

废话不多逼逼,直接上代码

Index.php
<?php
namespace app\chhfivepay\controller;
use \think\Log;
use think\Controller;
use think\Db;
use think\Request;
use think\Config;
include 'WxpayService.php';
class Index extends Controller {

    public function pay() {
        $code = Request::instance()->post();
        Log::write($code);
        /* sjc  2019.9.19     23:51  请保留此行 尊重劳动成果 */
        $mchid = 'xxxxx';          //微信支付商户号 PartnerID 通过微信支付商户资料审核后邮件发送
        $appid = 'xxxxx';  //微信支付申请对应的公众号的APPID
        $appKey = 'xxxxx';   //微信支付申请对应的公众号的APP Key
        $apiKey = 'xxxxx';   //https://pay.weixin.qq.com 帐户设置-安全设置-API安全-API密钥-设置API密钥
        $outTradeNo = date('YmdHis', time()) . xxxx;     //你自己的商品订单号
        $payAmount = 100;          //付款金额,单位:元
        //$payAmount = $code['total_fee'];    //订单标题
        //$orderName = $code['body'];    //订单标题
        $orderName = 'maimaimai';
        $notifyUrl = 'https://www.xxxx.cn/xxx/notify/notify';     //付款成功后的回调地址(不要有问号)
        $returnUrl = 'www.xxxx.cn';     //付款成功后,页面跳转的地址
        $wapUrl = 'www.xxxx.cn';   //WAP网站URL地址
        $wapName = 'H5支付';       //WAP 网站名
        //传递到支付页面去请求支付。 
        $wxPay = new WxpayService($mchid, $appid, $apiKey);
        $wxPay->setTotalFee($payAmount);
        $wxPay->setOutTradeNo($outTradeNo);
        $wxPay->setOrderName($orderName);
        $wxPay->setNotifyUrl($notifyUrl);
        $wxPay->setReturnUrl($returnUrl);
        $wxPay->setWapUrl($wapUrl);
        $wxPay->setWapName($wapName);
        $mwebUrl = $wxPay->createJsBizPackage($payAmount, $outTradeNo, $orderName, $notifyUrl);
        $this->assign("res", $mwebUrl);
        $this->assign("payAmount", $payAmount);
//        $this->assign("orderName", $orderName);
        return $this->fetch("index");
    }

}

<?php
Notify.php
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace app\chhfivepay\controller;

use think\Config;
use think\Db;
use think\Log;
use think\Cache;

class Notify {
   /* sjc  2019.9.19     23:51  请保留此行 尊重劳动成果 */
    public function notify() {
        //接收微信参数
        $postXml = file_get_contents("php://input"); //接收微信参数
        Log::write($postXml);

    }

}

WxpayService.php
<?php
namespace app\chhfivepay\controller;
/*
 * 小程序微信支付
 */
use think\Log;
use think\Db;
   /* sjc  2019.9.19     23:51  请保留此行 尊重劳动成果 */
   /* sjc  2019.9.19     23:51  请保留此行 尊重劳动成果 */
class WxpayService
{
    
    protected $mchid;
    protected $appid;
    protected $apiKey;
    protected $totalFee;
    protected $outTradeNo;
    protected $orderName;
    protected $notifyUrl;
    protected $returnUrl;
    protected $wapUrl;
    protected $wapName;
    public function __construct($mchid, $appid, $key)
    {
        $this->mchid = $mchid;
        $this->appid = $appid;
        $this->apiKey = $key;
    }
    public function setTotalFee($totalFee)
    {
        $this->totalFee = $totalFee;
    }
    public function setOutTradeNo($outTradeNo)
    {
        $this->outTradeNo = $outTradeNo;
    }
    public function setOrderName($orderName)
    {
        $this->orderName = $orderName;
    }
    public function setWapUrl($wapUrl)
    {
        $this->wapUrl = $wapUrl;
    }
    public function setWapName($wapName)
    {
        $this->wapName = $wapName;
    }
    public function setNotifyUrl($notifyUrl)
    {
        $this->notifyUrl = $notifyUrl;
    }
    public function setReturnUrl($returnUrl)
    {
        $this->returnUrl = $returnUrl;
    }
    /**
     * 发起订单
     * @return array
     */
    public function createJsBizPackage()
    {
        
        
        
        $config = array(
            'mch_id' => $this->mchid,
            'appid' => $this->appid,
            'key' => $this->apiKey,
        );
        $scene_info = array(
            'h5_info' =>array(
                'type'=>'Wap',
                'wap_url'=>$this->wapUrl,
                'wap_name'=>$this->wapName,
            )
        );
        $unified = array(
            'appid' => $config['appid'],
            'attach' => 'pay',             //商家数据包,原样返回,如果填写中文,请注意转换为utf-8
            'body' => $this->orderName,
            'mch_id' => $config['mch_id'],
            'nonce_str' => self::createNonceStr(),
            'notify_url' => $this->notifyUrl,
            'out_trade_no' => $this->outTradeNo,
            'spbill_create_ip' => $_SERVER['REMOTE_ADDR'],
            'total_fee' => intval($this->totalFee * 100),       //单位 转为分
            'trade_type' => 'MWEB',
            'scene_info'=>json_encode($scene_info)
        );
        $unified['sign'] = self::getSign($unified, $config['key']);
        $responseXml = self::curlPost('https://api.mch.weixin.qq.com/pay/unifiedorder', self::arrayToXml($unified));
        $unifiedOrder = simplexml_load_string($responseXml, 'SimpleXMLElement', LIBXML_NOCDATA);
        if ($unifiedOrder->return_code != 'SUCCESS') {
            die($unifiedOrder->return_msg);
        }
        if($unifiedOrder->mweb_url){
            return $unifiedOrder->mweb_url.'&redirect_url='.urlencode($this->returnUrl);
        }
        exit('error');
    }
    public static function curlPost($url = '', $postData = '', $options = array())
    {
        if (is_array($postData)) {
            $postData = http_build_query($postData);
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30); //设置cURL允许执行的最长秒数
        if (!empty($options)) {
            curl_setopt_array($ch, $options);
        }
        //https请求 不验证证书和host
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
    public static function createNonceStr($length = 16)
    {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $str = '';
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }
    public static function arrayToXml($arr)
    {
        $xml = "<xml>";
        foreach ($arr as $key => $val) {
            if (is_numeric($val)) {
                $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
            } else
                $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
        }
        $xml .= "</xml>";
        return $xml;
    }
    /**
     * 获取签名
     */
    public static function getSign($params, $key)
    {
        ksort($params, SORT_STRING);
        $unSignParaString = self::formatQueryParaMap($params, false);
        $signStr = strtoupper(md5($unSignParaString . "&key=" . $key));
        return $signStr;
    }
    protected static function formatQueryParaMap($paraMap, $urlEncode = false)
    {
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v) {
            if (null != $v && "null" != $v) {
                if ($urlEncode) {
                    $v = urlencode($v);
                }
                $buff .= $k . "=" . $v . "&";
            }
        }
        $reqPar = '';
        if (strlen($buff) > 0) {
            $reqPar = substr($buff, 0, strlen($buff) - 1);
        }
        return $reqPar;
    }

    
}
index.php
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf8"/>
<meta id="viewport" name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1; user-scalable=no;" />
<title>【微信支付V2.0】MWEB支付实例</title>
<style type="text/css">
/* 重置 [[*/
body,p,ul,li,h1,h2,form,input{margin:0;padding:0;}
h1,h2{font-size:100%;}
ul{list-style:none;}
body{-webkit-user-select:none;-webkit-text-size-adjust:none;font-family:Helvetica;background:#ECECEC;}
html,body{height:100%;}
a,button,input,img{-webkit-touch-callout:none;outline:none;}
a{text-decoration:none;}
/* 重置 ]]*/
/* 功能 [[*/
.hide{display:none!important;}
.cf:after{content:".";display:block;height:0;clear:both;visibility:hidden;}
/* 功能 ]]*/
/* 按钮 [[*/
a[class*="btn"]{display:block;height:42px;line-height:42px;color:#FFFFFF;text-align:center;border-radius:5px;}
.btn-blue{background:#3D87C3;border:1px solid #1C5E93;}
.btn-green{background-image:-webkit-gradient(linear, left top, left bottom, color-stop(0, #43C750), color-stop(1, #31AB40));border:1px solid #2E993C;box-shadow:0 1px 0 0 #69D273 inset;}
/* 按钮 [[*/
/* 充值页 [[*/
.charge{font-family:Helvetica;padding-bottom:10px;-webkit-user-select:none;}
.charge h1{height:44px;line-height:44px;color:#FFFFFF;background:#3D87C3;text-align:center;font-size:20px;-webkit-box-sizing:border-box;box-sizing:border-box;}
.charge h2{font-size:14px;color:#777777;margin:5px 0;text-align:center;}
.charge .content{padding:10px 12px;}
.charge .select li{position:relative;display:block;float:left;width:100%;margin-right:2%;height:150px;line-height:150px;text-align:center;border:1px solid #BBBBBB;color:#666666;font-size:16px;margin-bottom:5px;border-radius:3px;background-color:#FFFFFF;-webkit-box-sizing:border-box;box-sizing:border-box;overflow:hidden;}
.charge .price{border-bottom:1px dashed #C9C9C9;padding:10px 10px 15px;margin-bottom:20px;color:#666666;font-size:12px;}
.charge .price strong{font-weight:normal;color:#EE6209;font-size:26px;font-family:Helvetica;}
.charge .showaddr{border:1px dashed #C9C9C9;padding:10px 10px 15px;margin-bottom:20px;color:#666666;font-size:12px;text-align:center;}
.charge .showaddr strong{font-weight:normal;color:#9900FF;font-size:26px;font-family:Helvetica;}
.charge .copy-right{margin:5px 0; font-size:12px;color:#848484;text-align:center;}
/* 充值页 ]]*/
</style>
</head>
<body>
	<article class="charge">
		<h1>微信支付-H5-demo</h1>
		<section class="content">
				<h2>商品:测试商品。</h2>		
		  <ul class="select cf">
					<li><img src="https://www.selfice.cn/weixinpay.jpg" style="width:150px;height:150px"></li>
				</ul>
				<p class="copy-right">亲,此商品不提供退款和发货服务哦</p>
				<div class="price">微信价:<strong>{$payAmount}元</strong></div>
				<div class="operation"><a class="btn-green" id="getBrandWCPayRequest" href="{$res}">立即购买</a></div>
				<p class="copy-right">微信支付 由美食与美酒</p>
		</section>
	</article>
</body>
</html>
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值