欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

php微信支付之APP支付方法

程序员文章站 2022-05-26 12:11:20
本文实例讲述了微信开放平台移动应用集成微信支付功能。分享给大家供大家参考。具体分析如下: wechatapppay文件代码如下: 复制代码 代码如下: <...

本文实例讲述了微信开放平台移动应用集成微信支付功能。分享给大家供大家参考。具体分析如下:

wechatapppay文件代码如下:

复制代码 代码如下:

<?php
namespace common\services\wechatpay;
class wechatapppay extends wechatpaybase
{
    //package参数
    public $package = [];
    //异步通知参数
    public $notify = [];
    //推送预支付订单参数
    protected $config = [];
    //存储access token和获取时间的文件
    protected $file;
    //access token
    protected $accesstoken;
    //取access token的url
    const access_token_url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s';
    //生成预支付订单提交地址
    const post_order_url = 'https://api.weixin.qq.com/pay/genprepay?access_token=%s';
    public function __construct()
    {
        $this->file = __dir__ . '/payaccesstoken.txt';
    }
    /**
     * 创建app支付最终返回参数
     * @throws \exception
     * @return multitype:string null
     */
    public function createapppaydata()
    {
        $this->generateconfig();
        $prepayid = $this->getprepayid();
        try{
            $array = [
                'appid' => $this->appid,
                'appkey' => $this->paysignkey,
                'noncestr' => $this->getrandomstr(),
                'package' => 'sign=wxpay',
                'partnerid' => $this->partnerid,
                'prepayid' => $prepayid,
                'timestamp' => (string)time(),
            ];
            $array['sign'] = $this->sha1sign($array);
            unset($array['appkey']);
        } catch(\exception $e) {
            throw new \exception($e->getmessage());
        }
        return $array;
    }
    /**
     * 验证支付成功后的通知参数
     *
     * @throws \exception
     * @return boolean
     */
    public function verifynotify()
    {
        try{
            $staysignstr = $this->notify;
            unset($staysignstr['sign']);
            $sign = $this->signdata($staysignstr);
            return $this->notify['sign'] === $sign;
        } catch(\exception $e) {
            throw new \exception($e->getmessage());
        }
    }
    /**
     * 魔术方法,给添加支付参数进来
     *
     * @param string $name  参数名
     * @param string $value  参数值
     */
    public function __set($name, $value)
    {
        $this->$name = $value;
    }
    /**
     * 设置access token
     * @param string $token
     * @throws \exception
     * @return boolean
     */
    public function setaccesstoken()
    {
        try{
            if(!file_exists($this->file) || !is_file($this->file)) {
                $f = fopen($this->file, 'a');
                fclose($f);
            }
            $content = file_get_contents($this->file);
            if(!empty($content)) {
                $info = json_decode($content, true);
                if( time() - $info['gettime'] < 7150 ) {
                    $this->accesstoken = $info['accesstoken'];
                    return true;
                }
            }
            //文件内容为空或access token已失效,重新获取
            $this->outputaccesstokentofile();
        } catch(\exception $e) {
            throw new \exception($e->getmessage());
        }
        return true;
    }
    /**
     * 写入access token 到文件
     * @throws \exception
     * @return boolean
     */
    protected function outputaccesstokentofile()
    {
        try{
            $f = fopen($this->file, 'wb');
            $token = [
                'accesstoken' => $this->getaccesstoken(),
                'gettime' => time(),
            ];
            flock($f, lock_ex);
            fwrite($f, json_encode($token));
            flock($f, lock_un);
            fclose($f);
            $this->accesstoken = $token['accesstoken'];
        } catch(\exception $e) {
            throw new \exception($e->getmessage());
        }
        return true;
    }
    /**
     * 取access token
     *
     * @throws \exception
     * @return string
     */
    protected function getaccesstoken()
    {
        $url = sprintf(self::access_token_url, $this->appid, $this->appsecret);
        $result = json_decode( $this->geturl($url), true );
        if(isset($result['errcode'])) {
            throw new \exception("get access token failed:{$result['errmsg']}");
        }
        return $result['access_token'];
    }
    /**
     * 取预支付会话标识
     *
     * @throws \exception
     * @return string
     */
    protected function getprepayid()
    {
        $data = json_encode($this->config);
        $url = sprintf(self::post_order_url, $this->accesstoken);
        $result = json_decode( $this->posturl($url, $data), true );
        if( isset($result['errcode']) && $result['errcode'] != 0 ) {
            throw new \exception($result['errmsg']);
        }
        if( !isset($result['prepayid']) ) {
            throw new \exception('get prepayid failed, url request error.');
        }
        return $result['prepayid'];
    }
    /**
     * 组装预支付参数
     *
     * @throws \exception
     */
    protected function generateconfig()
    {
        try{
            $this->config = [
                    'appid' => $this->appid,
                    'traceid' => $this->traceid,
                    'noncestr' => $this->getrandomstr(),
                    'timestamp' => time(),
                    'package' => $this->generatepackage(),
                    'sign_method' => $this->sign_method,
            ];
            $this->config['app_signature'] = $this->generatesign();
        } catch(\exception $e) {
            throw new \exception($e->getmessage());
        }
    }
    /**
     * 生成package字段
     *
     * 生成规则:
     * 1、生成sign的值signvalue
     * 2、对package参数再次拼接成查询字符串,值需要进行urlencode
     * 3、将sign=signvalue拼接到2生成的字符串后面得到最终的package字符串
     *
     * 第2步urlencode空格需要编码成%20而不是+
     *
     * rfc 1738会把 空格编码成+
     * rfc 3986会把空格编码成%20
     *
     * @return string
     */
    protected function generatepackage()
    {
        $this->package['sign'] = $this->signdata($this->package);
        return http_build_query($this->package, '', '&', php_query_rfc3986);
    }
    /**
     * 生成签名
     *
     * @return string
     */
    protected function generatesign()
    {
        $signarray = [
            'appid' => $this->appid,
            'appkey' => $this->paysignkey,
            'noncestr' => $this->config['noncestr'],
            'package' => $this->config['package'],
            'timestamp' => $this->config['timestamp'],
            'traceid' => $this->traceid,
        ];
        return $this->sha1sign($signarray);
    }
    /**
     * 签名数据
     *
     * 生成规则:
     * 1、字典排序,拼接成查询字符串格式,不需要urlencode
     * 2、上一步得到的字符串最后拼接上key=paternerkey
     * 3、md5哈希字符串并转换成大写得到sign的值signvalue
     *
     * @param array $data 待签名数据
     * @return string 最终签名结果
     */
    protected function signdata($data)
    {
        ksort($data);
        $str = $this->arraytostring($data);
        $str .= "&key={$this->partnerkey}";
        return strtoupper( $this->signmd5($str) );
    }
    /**
     * sha1签名
     * 签名规则
     * 1、字典排序
     * 2、拼接查询字符串
     * 3、sha1运算
     *
     * @param array $arr
     * @return string
     */
    protected function sha1sign($arr)
    {
        ksort($arr);
        return sha1( $this->arraytostring($arr) );
    }
}

希望本文所述对大家的php程序设计有所帮助。