zoukankan      html  css  js  c++  java
  • php、Thinkphp微信支付V3 、php、Thinkphp微信API V3、摒弃官方demo,自写调用demo

    以前一直使用v2,格式是xml格式,但是微信最新推出v3之后,只有以前的老用户才能用v2,而新用户只能用v3。阅读了一下文档,发现v3采用的是json格式和以前的xml大有不同。官方的demo又不清不白,用的是guzzle(关键我不会啊,研究又要太久时间,项目赶,没办法只有自己编写一个demo了,希望可以帮助大家)

    首先创建一个文件和类,如WxPayv3.php,请勿直接复制,因为可以看到这个类继承了另一个类(别担心,父类只是一些配置参数而已,可以自己去创建一个,我就不写出来了)

    <?php
    namespace wx;
    use wxWxExtend;
    class WxPayv3 extends WxExtend{
        
        /**
         * # +========================================================================
         * # | - @name        执行
         * # | - @author     cq <just_leaf@foxmail.com> 
         * # | - @copyright zmtek 2021-01-20
         * # +========================================================================
         */
        public function execute($url,$body = null,$http_method = 'POST') {
            
            # 转化大写
            $http_method = strtoupper($http_method);
            
            if($http_method == 'POST') {
                
                $body   = json_encode($body);
            }else{
                
                $url    = $url . '?' . http_build_query($body); 
                $body   = null;
            }
            
            # 分割符号
            $sign       = $this -> getV3Sign($url,$http_method,$body);
            
            $header[]   = 'User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.108 Safari/537.36';
            $header[]   = 'Accept: application/json';
            $header[]   = 'Content-Type: application/json;';
            $header[]   = 'Authorization: WECHATPAY2-SHA256-RSA2048 '.$sign;
        
            $exc        = $this -> Curl($url,$body,$http_method,$header);
            return $exc;
        }
        
        /**
         * # +========================================================================
         * # | - @name        请求
         * # | - @author     cq <just_leaf@foxmail.com> 
         * # | - @copyright zmtek 2021-01-20
         * # +========================================================================
         */
        public function Curl($url, $data, $http_method,$header = array(), $timeout = 30)
        {
            $opts = array(
                    CURLOPT_TIMEOUT        => 30,
                    CURLOPT_RETURNTRANSFER => 1,
                    CURLOPT_SSL_VERIFYPEER => false,
                    CURLOPT_SSL_VERIFYHOST => false,
                    CURLOPT_HTTPHEADER     => $header,
                    CURLOPT_URL            => $url,
                    CURLOPT_HEADER         => 1 ,
            );
            
            # 根据请求类型设置特定参数
            if($http_method == 'POST') {
                
                # 判断是否传输文件
                $opts[CURLOPT_POST] = 1;
                $opts[CURLOPT_POSTFIELDS] = $data;
            }
                    
            # 初始化并执行curl请求
            $ch         = curl_init();
            curl_setopt_array($ch, $opts);
            
            $data       = curl_exec($ch);
            $error      = curl_error($ch);
            $httpCode   = curl_getinfo($ch,CURLINFO_HTTP_CODE); 
            curl_close($ch);
            if($error) throw new Exception('请求发生错误:' . $error);
            list($headers, $body) = explode("
    
    ", $data, 2);
            
            $result['data']     = $body;
            $result['httpcode'] = $httpCode;
            $result['headers']  = explode("
    ", $headers);
            return  $result;
        }
        
        /**
         * # +========================================================================
         * # | - @name        签名
         * # | - @author     cq <just_leaf@foxmail.com> 
         * # | - @copyright zmtek 2021-01-20
         * # +========================================================================
         */
        public function getV3Sign($url,$http_method,$body) {
            
            # 商户号
            $merchant_id    = $this -> MCHID;
            # 随机字符串
            $nonce          = strtoupper($this -> getNoncestr());
            # 商户序列号
            $serial_no      = $this -> merchantSerialNumber;
            # 时间搓
            $timestamp      = time();
            # url
            $url_parts      = parse_url($url);
            # 获取绝对路径
            $canonical_url  = ($url_parts['path'] . (!empty($url_parts['query']) ? "?${url_parts['query']}" : ""));
            # 密钥key
            $private_key    = $this -> getPrivateKey($this -> SSLKEY_PATH);
            # 拼接参数
            $message        = 
            $http_method."
    ".
            $canonical_url."
    ".
            $timestamp."
    ".
            $nonce."
    ".
            $body."
    ";
            
            # 获取签名             
            openssl_sign($message, $raw_sign, $private_key, 'sha256WithRSAEncryption');
            $sign   = base64_encode($raw_sign);
            
            $token  = sprintf('mchid="%s",nonce_str="%s",timestamp="%d",serial_no="%s",signature="%s"',
            $merchant_id, $nonce, $timestamp, $serial_no, $sign);
            return $token;
        }
    
        /**
         * # +========================================================================
         * # | - @name        获取私钥
         * # | - @author     cq <just_leaf@foxmail.com> 
         * # | - @copyright zmtek 2019-12-26
         * # +========================================================================
         */
        public function getPrivateKey($filepath) {
            
            return openssl_get_privatekey(file_get_contents($filepath));
        }
        
        /**
         * # +========================================================================
         * # | - @name        获取随机数
         * # | - @author     cq <just_leaf@foxmail.com> 
         * # | - @copyright zmtek 2021-01-20
         * # +========================================================================
         */
        public function getNoncestr($length = 32) {
            
            $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
            $str ="";
            for ( $i = 0; $i < $length; $i++ )  {  
                $str.= substr($chars, mt_rand(0, strlen($chars)-1), 1);  
            }  
            return $str;
        }
    }

     然后再new再调用就完事了

    /**
             * # +========================================================================
             * # | - @name        查询用户
             * # | - @author     cq <just_leaf@foxmail.com> 
             * # | - @copyright zmtek 2020-11-24
             * # +------------------------------------------------------------------------
             * # | - 1.msg
             * # +========================================================================
             */
            public function permissions_openid(WxPayv3 $WxPayv3,WxExtend $WxExtend) {
                
                $url    = 'https://api.mch.weixin.qq.com/v3/payscore/permissions/openid/xxxx';
                $authorization_code = $WxPayv3 -> getNoncestr();
                $data   = array(
                    'appid'                 => $WxExtend -> appletappid ,
                    'service_id'            => $WxExtend -> service_id,
                );
                
                $result = $WxPayv3 -> execute($url,$data,'GET');
                pf($result);
                // $data   = json_decode($result['data'],true);
                // return $this -> success($data);
            }

    好,我们来看调用结果

    啊呀,好家伙,是不是我这个方法有问题呢?结果赶紧看下官方文档,原来是微信那边挂了。不信?看下图

    好啦,之后就可以愉快的调用任何接口了。

    如果你还不会怎么办,有大招,关注下方公众号,提问即可。一般回复时间一天左右

  • 相关阅读:
    UINavigationController
    UIWebView
    控制器view的加载顺序initWithNibName >>> viewDidLoad >>> viewWillAppear >>> viewDidAppear
    UITableView
    JS调用OC方法
    【概念】winform的特点
    【概念】指针
    【c++】类的继承(三种继承方式)、基类和派生类、面向对象三要素
    【笔试】C++笔试题
    【c#】解决DataTable.Rows.Add(dr)语句执行速度慢的问题(GridControl)
  • 原文地址:https://www.cnblogs.com/leaf-cq/p/14302927.html
Copyright © 2011-2022 走看看