liziyu 发布的文章

直接上代码

<?php
namespace app\controller;

use support\Request;
use support\Response;
use Yansongda\Pay\Pay;

class Payment
{
    protected $config = [
        'alipay' => [
            'default' => [
                // 必填-支付宝分配的 app_id
                'app_id' => 'wx4926de289f70b113',
                // 必填-应用私钥 字符串或路径
                'app_secret_cert' => 'MIIEvLoLc1s/VdBHku+JEd0YmEY+p4sjmcRnlu4AlzLxkWUTTg==',
                // 必填-应用公钥证书 路径
                'app_public_cert_path' => '/Users/yansongda/pay/cert/appCertPublicKey_2016082000295641.crt',
                // 必填-支付宝公钥证书 路径
                'alipay_public_cert_path' => '/Users/yansongda/pay/cert/alipayCertPublicKey_RSA2.crt',
                // 必填-支付宝根证书 路径
                'alipay_root_cert_path' => '/Users/yansongda/pay/cert/alipayRootCert.crt',
                'return_url' => 'https://yansongda.cn/alipay/return',
                'notify_url' => 'https://yansongda.cn/alipay/notify',
                // 选填-第三方应用授权token
                'app_auth_token' => '',
                // 选填-服务商模式下的服务商 id,当 mode 为 Pay::MODE_SERVICE 时使用该参数
                'service_provider_id' => '',
                // 选填-默认为正常模式。可选为: MODE_NORMAL, MODE_SANDBOX, MODE_SERVICE
                'mode' => Pay::MODE_NORMAL,
            ]
        ],
        'wechat' => [
            'default' => [
                // 必填-商户号,服务商模式下为服务商商户号
                'mch_id' => '123xxxx02',
                // 必填-商户秘钥
                'mch_secret_key' => 'xxxxx',  //api安全中心里的V3密码32位的那个
                // 必填-商户私钥 字符串或路径
                'mch_secret_cert' => '/xxxxx/apiclient_key.pem',  //api安全中心里下载的的密钥,绝对路径
                // 必填-商户公钥证书路径
                'mch_public_cert_path' => '/xxxx/apiclient_cert.pem', //api安全中心里下载的公钥,绝对路径
                // 必填
                'notify_url' => 'https://www.xxx.com/member/wx_native_notify', //支付回调地址必须https
                // 选填-公众号 的 app_id
                'mp_app_id' => 'wx4926de289f70b113',
                // 选填-小程序 的 app_id
                'mini_app_id' => '',
                // 选填-app 的 app_id
                'app_id' => '',
                // 选填-合单 app_id
                'combine_app_id' => '',
                // 选填-合单商户号
                'combine_mch_id' => '',
                // 选填-服务商模式下,子公众号 的 app_id
                'sub_mp_app_id' => '',
                // 选填-服务商模式下,子 app 的 app_id
                'sub_app_id' => '',
                // 选填-服务商模式下,子小程序 的 app_id
                'sub_mini_app_id' => '',
                // 选填-服务商模式下,子商户id
                'sub_mch_id' => '',
                // 选填-微信公钥证书路径, optional,强烈建议 php-fpm 模式下配置此参数
                'wechat_public_cert_path' => [
                    '4248DC46520F9EAC26C7FET4464ADBE5ADDA3A' => '/xxxx/wechatpay_public.pem', //通过算法生成的,具体生成方式往下面看。
                ],
                // 选填-默认为正常模式。可选为: MODE_NORMAL, MODE_SERVICE
                'mode' => Pay::MODE_NORMAL,
            ]
        ],
        'logger' => [
            'enable' => false,
            'file' => './logs/alipay.log',
            'level' => 'info', // 建议生产环境等级调整为 info,开发环境为 debug
            'type' => 'single', // optional, 可选 daily.
            'max_file' => 30, // optional, 当 type 为 daily 时有效,默认 30 天
        ],
        'http' => [ // optional
            'timeout' => 5.0,
            'connect_timeout' => 5.0,
            // 更多配置项请参考 [Guzzle](https://guzzle-cn.readthedocs.io/zh_CN/latest/request-options.html)
        ],
    ];

    //二维码生成展示页
    public function index(Request $request)
    {
        Pay::config($this->config);

        $order = [
            'out_trade_no' => time().'',
            'description' => 'subject-测试',
            'amount' => [
                'total' => 1,
            ],
        ];

        $result = Pay::wechat()->scan($order);
        // 二维码内容: $qr = $result->code_url;
        //var_export($result->code_url);

        return view('payment/index', ['code_url' => $result->code_url]);
    }

    //支付成功回调
    public function verify(Request $request)
    {
        Pay::config($this->config);

        // 是的,你没有看错,就是这么简单!
        $result = Pay::wechat()->callback($request->post());
        file_put_contents(__DIR__ . '/notify_result_ysd.txt',
            date('Y-m-d H:i:s') . ':' . var_export($result, true));
        

        //这里很关键,需要注意。
        return new Response(200, [], json_encode(['code' => 'SUCCESS', 'message' => '成功']));
    }
}

微信支付平台证书下载:

http://www.liziyu.com/archives/309/

话不多说直接上代码:

// app\member\controller\pay.php

<?php

namespace app\controller;

use EasyWeChat\Kernel\Exceptions\Exception;
use EasyWeChat\Kernel\Exceptions\InvalidArgumentException;
use support\Request;
use EasyWeChat\Pay\Application;
use Symfony\Component\HttpFoundation\HeaderBag;
use Symfony\Component\HttpFoundation\Request as SymfonyRequest;

class Index
{
    private $config = [
        'mch_id' => 'xxxx', //根据自已实际的填写
        // 商户证书
        'private_key' => '/xxx/apiclient_key.pem',//根据自已实际的填写,绝对路径
        'certificate' => '/xxx/apiclient_cert.pem', //根据自已实际的填写,绝对路径
        // v3 API 秘钥
        'secret_key' => 'xxxx', //根据自已实际的填写
        // v2 API 秘钥
        'v2_secret_key' => 'xxx', //根据自已实际的填写
        'platform_certs' => [
            '/xxx/wechatpay_public.pem', //根据自已实际的填写,获取办法见下面。
        ],
        'http' => [
            'throw' => true, // 状态码非 200、300 时是否抛出异常,默认为开启
            'timeout' => 5.0,
            // 'base_uri' => 'https://api.mch.weixin.qq.com/', // 如果你在国外想要覆盖默认的 url 的时候才使用,根据不同的模块配置不同的 uri
        ],
    ];

    //二维码生成展示页
    public function index(Request $request)
    {
        try {
            $app = new Application($this->config);
            $response = $app->getClient()->post('/v3/pay/transactions/native', [
                'json' => [
                    'mchid' => (string)$app->getMerchant()->getMerchantId(),
                    'out_trade_no' => 'SN_'.time(),
                    'appid' => 'xxxx', //根据自已实际的填写
                    'description' => '测试内容',
                    'notify_url' => 'https://www.xxxx.com/member/wx_native_notify', //注意是ssl协议
                    'amount' => [
                        'total' => 2,
                        'currency' => 'CNY',
                    ]
                ]
            ]);
        } catch (InvalidArgumentException $e) {
            //
        }
        return view('index/index', ['code_url' => $response->toArray()]);
    }


    //回调
    public function verify(Request $request)
    {
        try {
           //下面四行很关键
            $symfony_request = new SymfonyRequest($request->get(), $request->post(), [], $request->cookie(), [], [], $request->rawBody());
            $symfony_request->headers = new HeaderBag($request->header());
            $app = new Application($this->config);
            $app->setRequestFromSymfonyRequest($symfony_request);

            // $app 为你实例化的支付对象,此处省略实例化步骤
            $server = $app->getServer();
            
            // 处理支付结果事件
            $server->handlePaid(function ($message) {
                // $message 为微信推送的通知结果,详看微信官方文档
                file_put_contents(__DIR__ . '/notify_result.txt',
                    date('Y-m-d H:i:s') . ':' . var_export($message, true));
                
                // 微信支付订单号 $message['transaction_id']
                // 商户订单号 $message['out_trade_no']
                // 商户号 $message['mchid']
                // 具体看微信官方文档...
                // 进行业务处理,如存数据库等...

            });
            //这一步特别要注意,必须这么写。
            return $server->serve()->getBody()->getContents();

        } catch (Exception $e) {
            echo $e->getMessage();
        }
    }

}

“平台证书”申请办法:http://www.liziyu.com/archives/309/

第一步:

假设你已经成功安装了composer工具,并可以正常运行。下面以Linux或MacOS为例:
在任意目录下(如:Download),下载组件:

//
composer require wechatpay/wechatpay
//

1.png

第二步:

在当前(Download)项目目录下检测是否有可执行的命令文件:

//
composer exec -l
//

2.png
显示有可执行文件 CertificateDownloader.php 表示此文件可执行。

第三步:

执行以下令命:

//
composer exec CertificateDownloader.php
//

3.png
出现以上提示表示正常,可以继续往下。

第四步:

根据上图所示,组装命令行,规则通常如下:

//
composer exec CertificateDownloader.php -- -k ${apiV3key} -m ${mchId} -f ${mchPrivateKeyFilePath} -s ${mchSerialNo} -o ${outputFilePath}
//

这里参见:https://github.com/wechatpay-apiv3/wechatpay-php

组装完成后台命令行如下:

//
composer exec CertificateDownloader.php --  -k xxxxxx12345xxxxx -m 1238717442 -f /Users/liziyu/Documents/Wechat_Pay_Cert/wx_cert/apiclient_key.pem -s 4248DC46520F9EAC26C7DA22E3E74FDIGKEE87KA -o /Users/liziyu/Documents/Wechat_Pay_Cert/wx_cert
//


根据实际情况修改成自已的商户平台参数。

5.png

如果出现以上提示表示生成成功了。

6.png
如上图片示,生成的“平台证书”即可使用了。

最后:
附上微信官方PHP开发V3版 Demo供下载参考。

WxpayAPI_php.zip

判断移动端的简单方法

$agent = strtolower($_SERVER['HTTP_USER_AGENT']);
$iphone = (strpos($agent, 'iphone')) ? true : false;
$ipad = (strpos($agent, 'ipad')) ? true : false;
$android = (strpos($agent, 'android')) ? true : false;
if($iphone || $ipad || $android){
    define('ISMOBILE',true);
} else {
    define('ISMOBILE',false);
};

判断微信端的简单方法

function isWeixin() { 
  if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) { 
    return true; 
  } else {
    return false; 
  }
}

JsApi.php展现下单页面

<?php

header('Content-type:text/html; Charset=utf-8');
$mchid = '微信支付商户号';
$appid = '微信支付申请对应的公众号的APPID';
$appKey = '微信支付申请对应的公众号的APPSECRET';
$apiKey = 'API密钥';   //商户平台-帐户设置-安全设置-API安全-API密钥-设置API密钥
//①、获取用户openid
$wxPay = new WxpayService($mchid,$appid,$appKey,$apiKey);
$openId = $wxPay->GetOpenid();      //获取openid
if(!$openId) exit('获取openid失败');
//②、统一下单
$outTradeNo = uniqid();     //你自己的商品订单号
$payAmount = 0.01;          //付款金额,单位:元
$orderName = 'test';    //订单标题
$notifyUrl = 'https://www.likeyunba.com/pay/notify.php';     //付款成功后的回调地址(不要有问号)
$payTime = time();      //付款时间
$jsApiParameters = $wxPay->createJsBizPackage($openId,$payAmount,$outTradeNo,$orderName,$notifyUrl,$payTime);
$jsApiParameters = json_encode($jsApiParameters);
?>
    <html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1"/>
        <title>微信支付样例-支付</title>
        <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="http://www.likeyunba.com/pay/true.html";
                        }else{
                            //支付失败/或取消支付跳转页面
                            window.location.href="http://www.likeyunba.com/pay/false.html";
                        }
                    }
                );
            }
            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>
    </head>
    <body>
    <br/>
    <font color="#9ACD32"><b>该笔订单支付金额为<span style="color:#f00;font-size:50px"><?php echo $payAmount?>元</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="callpay()" >立即支付</button>
    </div>
    </body>
    </html>
<?php
header("Content-Type:text/html; charset=utf-8");
class WxpayService
{
    protected $mchid;
    protected $appid;
    protected $appKey;
    protected $apiKey;
    public $data = null;
    public function __construct($mchid, $appid, $appKey,$key)
    {
        $this->mchid = $mchid; //https://pay.weixin.qq.com 产品中心-开发配置-商户号
        $this->appid = $appid; //微信支付申请对应的公众号的APPID
        $this->appKey = $appKey; //微信支付申请对应的公众号的APP Key
        $this->apiKey = $key;   //https://pay.weixin.qq.com 帐户设置-安全设置-API安全-API密钥-设置API密钥
    }
    /**
     * 通过跳转获取用户的openid,跳转流程如下:
     * 1、设置自己需要调回的url及其其他参数,跳转到微信服务器https://open.weixin.qq.com/connect/oauth2/authorize
     * 2、微信服务处理完成之后会跳转回用户redirect_uri地址,此时会带上一些参数,如:code
     * @return 用户的openid
     */
    public function GetOpenid()
    {
        //通过code获得openid
        if (!isset($_GET['code'])){
            //触发微信返回code码
            $scheme = $_SERVER['HTTPS']=='on' ? 'https://' : 'http://';
            $baseUrl = urlencode($scheme.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].$_SERVER['QUERY_STRING']);
            $url = $this->__CreateOauthUrlForCode($baseUrl);
            Header("Location: $url");
            exit();
        } else {
            //获取code码,以获取openid
            $code = $_GET['code'];
            $openid = $this->getOpenidFromMp($code);
            return $openid;
        }
    }
    /**
     * 通过code从工作平台获取openid机器access_token
     * @param string $code 微信跳转回来带上的code
     * @return openid
     */
    public function GetOpenidFromMp($code)
    {
        $url = $this->__CreateOauthUrlForOpenid($code);
        $res = self::curlGet($url);
        //取出openid
        $data = json_decode($res,true);
        $this->data = $data;
        $openid = $data['openid'];
        return $openid;
    }
    /**
     * 构造获取open和access_toke的url地址
     * @param string $code,微信跳转带回的code
     * @return 请求的url
     */
    private function __CreateOauthUrlForOpenid($code)
    {
        $urlObj["appid"] = $this->appid;
        $urlObj["secret"] = $this->appKey;
        $urlObj["code"] = $code;
        $urlObj["grant_type"] = "authorization_code";
        $bizString = $this->ToUrlParams($urlObj);
        return "https://api.weixin.qq.com/sns/oauth2/access_token?".$bizString;
    }
    /**
     * 构造获取code的url连接
     * @param string $redirectUrl 微信服务器回跳的url,需要url编码
     * @return 返回构造好的url
     */
    private function __CreateOauthUrlForCode($redirectUrl)
    {
        $urlObj["appid"] = $this->appid;
        $urlObj["redirect_uri"] = "$redirectUrl";
        $urlObj["response_type"] = "code";
        $urlObj["scope"] = "snsapi_base";
        $urlObj["state"] = "STATE"."#wechat_redirect";
        $bizString = $this->ToUrlParams($urlObj);
        return "https://open.weixin.qq.com/connect/oauth2/authorize?".$bizString;
    }
    /**
     * 拼接签名字符串
     * @param array $urlObj
     * @return 返回已经拼接好的字符串
     */
    private function ToUrlParams($urlObj)
    {
        $buff = "";
        foreach ($urlObj as $k => $v)
        {
            if($k != "sign") $buff .= $k . "=" . $v . "&";
        }
        $buff = trim($buff, "&");
        return $buff;
    }
    /**
     * 统一下单
     * @param string $openid 调用【网页授权获取用户信息】接口获取到用户在该公众号下的Openid
     * @param float $totalFee 收款总费用 单位元
     * @param string $outTradeNo 唯一的订单号
     * @param string $orderName 订单名称
     * @param string $notifyUrl 支付结果通知url 不要有问号
     * @param string $timestamp 支付时间
     * @return string
     */
    public function createJsBizPackage($openid, $totalFee, $outTradeNo, $orderName, $notifyUrl, $timestamp)
    {
        $config = array(
            'mch_id' => $this->mchid,
            'appid' => $this->appid,
            'key' => $this->apiKey,
        );
        $orderName = iconv('GBK','UTF-8',$orderName);
        $unified = array(
            'appid' => $config['appid'],
            'attach' => 'pay',             //商家数据包,原样返回,如果填写中文,请注意转换为utf-8
            'body' => $orderName,
            'mch_id' => $config['mch_id'],
            'nonce_str' => self::createNonceStr(),
            'notify_url' => $notifyUrl,
            'openid' => $openid,            //rade_type=JSAPI,此参数必传
            'out_trade_no' => $outTradeNo,
            'spbill_create_ip' => '127.0.0.1',
            'total_fee' => intval($totalFee * 100),       //单位 转为分
            'trade_type' => 'JSAPI',
        );
        $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 === false) {
            die('parse xml error');
        }
        if ($unifiedOrder->return_code != 'SUCCESS') {
            die($unifiedOrder->return_msg);
        }
        if ($unifiedOrder->result_code != 'SUCCESS') {
            die($unifiedOrder->err_code);
        }
        $arr = array(
            "appId" => $config['appid'],
            "timeStamp" => "$timestamp",        //这里是字符串的时间戳,不是int,所以需加引号
            "nonceStr" => self::createNonceStr(),
            "package" => "prepay_id=" . $unifiedOrder->prepay_id,
            "signType" => 'MD5',
        );
        $arr['paySign'] = self::getSign($arr, $config['key']);
        return $arr;
    }
    public static function curlGet($url = '', $options = array())
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        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 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;
    }
}
?>


Notify.php 回调通知

<?php
/**
 * 原生支付(扫码支付)及公众号支付的异步回调通知
 * 说明:需要在native.php或者jsapi.php中的填写回调地址。例如:http://www.xxx.com/wx/notify.php
 * 付款成功后,微信服务器会将付款结果通知到该页面
 */
header('Content-type:text/html; Charset=utf-8');
$mchid = '微信支付商户号';
$appid = '公众号APPID';
$apiKey = 'API密钥';
$wxPay = new WxpayService($mchid, $appid, $apiKey);
$result = $wxPay->notify();
if ($result) {
    echo '成功了';
    //完成你的逻辑
    //例如连接数据库,获取付款金额$result['cash_fee'],获取订单号$result['out_trade_no'],修改数据库中的订单状态等;
} else {
    echo 'pay error';
}

class WxpayService
{
    protected $mchid;
    protected $appid;
    protected $apiKey;

    public function __construct($mchid, $appid, $key)
    {
        $this->mchid = $mchid;
        $this->appid = $appid;
        $this->apiKey = $key;
    }

    public function notify()
    {
        $config = array(
            'mch_id' => $this->mchid,
            'appid' => $this->appid,
            'key' => $this->apiKey,
        );
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
        if ($postObj === false) {
            die('parse xml error');
        }
        if ($postObj->return_code != 'SUCCESS') {
            die($postObj->return_msg);
        }
        if ($postObj->result_code != 'SUCCESS') {
            die($postObj->err_code);
        }
        $arr = (array)$postObj;
        unset($arr['sign']);
        if (self::getSign($arr, $config['key']) == $postObj->sign) {
            echo '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
            return $arr;
        }
    }

    /**
     * 获取签名
     */
    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;
    }
}

本文转自互联网,具体网址不记得了。向原作者致敬!

不多说,上完整代码!

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    //这里是应有的css文件引用
    <?php require "app/admin/view/layout/header.html" ?>
</head>
<body>
<div class="layui-card-body text-center" style="box-sizing: border-box;">
    <div id="qrcode" class="layui-inline"></div>
    <h2 style="color: red;padding-top:20px">请使用微信扫码支付</h2>
</div>
 //这里是应有的js文件引用
<?php require "app/admin/view/layout/footer.html" ?>

<script>

    layui.use(['form', 'QRCode'], function () {
        var $ = layui.jquery;
        var form = layui.form;
        var QRCode = layui.QRCode;

        new QRCode(document.getElementById("qrcode"), {
            text: '二维码的短地址',
            width: 250,
            height: 250,
            colorDark: '#000000',
            colorLight: '#ffffff',
            correctLevel: QRCode.CorrectLevel.H,
        });


        //1.支付轮询
        $(document).ready(function () {
            setInterval(function () {
                //1.先得到当前iframe层的索引 关闭窗口
                var index = parent.layer.getFrameIndex(window.name);
                $.post("后台url",
                    {out_trade_no: "订单号"},
                    function (res) {
                    if (res.code === 200) {
                        layer.msg(res.msg, {icon: 1, time: 2500, shade: 0.4}, function () {
                            parent.layer.close(index); //2.再执行关闭自身
                            parent.location.reload();
                        });
                    }
                }, 'json');
                return false;
            }, 3000);
        });
    });
</script>
</body>
</html>


说实话,到放弃为止,我还是没有找到这个商户公钥到底在哪里得到。

我下面收集了一个热心网友给我的回复,但我也没有测试,贴出来给大家参考:

# 必填-商户号,服务商模式下为服务商商户号
mch_id='1111111111',
# 必填-商户秘钥 V3 版本生成的 32 位秘钥
mch_secret_key=""
# 商户私钥 字符串或路径 (商户私钥,就是V2的私钥,路径也可以)
mch_secret_cert="apiclient_cert.key"
# 必填-商户公钥证书路径 (商户公钥,就是V2的私钥,路径也可以)
mch_public_cert_path="apiclient_key.pem"
// 就是之前的 那两个 对应一下就行啦
// 没有什么太复杂的  很简单
// 这个证书 要去  https://pay.weixin.qq.com/wiki/doc/apiv3/wechatpay/wechatpay6_0.shtml 下载证书文件生成
// 生成的就是 apiclient_cert + apiclient_key文件


========================== 更新(暂未测试) ==========================

1、官方文档:https://pay.weixin.qq.com/wiki/doc/api/tools/mch_pay.php?chapter=24_7

2、命令行工具:https://github.com/EasyWechat/console

Get payment RSA public key.

$ ./vendor/bin/easywechat payment:rsa_public_key \
    --mch_id=14339221228 \
    --api_key=36YTbDmLgyQ52noqdxgwGiYy \
    --cert_path=/Users/overtrue/www/demo/apiclient_cert.pem \
    --key_path=/Users/overtrue/www/demo/apiclient_key.pem 
    
# Public key of mch_id:14339221228 saved as ./public-14339221228.pem