php微信支付之APP支付方法

 更新时间:2015年03月04日 16:17:32   作者:OSC首席键客  
这篇文章主要介绍了php微信支付之APP支付方法,实例分析了php微信支付接口文件及使用技巧,需要的朋友可以参考下
(福利推荐:【腾讯云】服务器最新限时优惠活动,云服务器1核2G仅99元/年、2核4G仅768元/3年,立即抢购>>>:9i0i.cn/qcloud

(福利推荐:你还在原价购买阿里云服务器?现在阿里云0.8折限时抢购活动来啦!4核8G企业云服务器仅2998元/3年,立即抢购>>>:9i0i.cn/aliyun

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

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程序设计有所帮助。

相关文章

  • 深入PHP FTP类的详解

    深入PHP FTP类的详解

    本篇文章是对PHP的FTP类进行了详细的分析介绍,需要的朋友参考下
    2013-06-06
  • 上传文件先创建目录 再上传到目录里面去

    上传文件先创建目录 再上传到目录里面去

    上传文件先创建目录,其实应该先加入判断文件夹是否存在,不存在则创建文件夹的,希望朋友们自行添加,这里给出的是核心代码。
    2010-12-12
  • PHP中通过ADO调用Access数据库的方法测试不通过

    PHP中通过ADO调用Access数据库的方法测试不通过

    PHP中通过ADO调用Access数据库的方法测试不通过...
    2006-12-12
  • 详解PHP结构型设计模式之桥接模式Bridge Pattern

    详解PHP结构型设计模式之桥接模式Bridge Pattern

    桥接,顾名思义,就是用来连接两个部分,使得两个部分可以互相通讯。桥接模式将系统的抽象部分与实现部分分离解耦,使他们可以独立的变化。本文通过示例详细介绍了桥接模式的原理与使用,需要的可以参考一下
    2023-04-04
  • PHP利用缓存技术提升性能技巧及原理探究

    PHP利用缓存技术提升性能技巧及原理探究

    随着互联网的快速发展,网站性能对于用户体验和SEO排名变得越来越重要,PHP作为一种常用的服务器端脚本语言,其性能对于网站的响应速度起着至关重要的作用,而PHP的缓存技术就是提高性能的一种重要手段
    2024-01-01
  • PHP扩展模块memcached长连接使用方法分析

    PHP扩展模块memcached长连接使用方法分析

    这篇文章主要介绍了PHP扩展模块memcached长连接使用方法分析,需要的朋友可以参考下
    2014-12-12
  • PHP5 面向对象(学习记录)

    PHP5 面向对象(学习记录)

    PHP5已经支持面向对象,这样可以提高代码效率,与代码的复用性。
    2009-12-12
  • 项目中应用Redis+Php的场景

    项目中应用Redis+Php的场景

    Redis是一个开源的使用ANSI C语言编写、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库,并提供多种语言的API。今天我们来看下php结合redis的一些应用场景
    2016-05-05
  • PHP 源代码分析 Zend HashTable详解

    PHP 源代码分析 Zend HashTable详解

    在PHP的Zend引擎中,有一个数据结构非常重要,它无处不在,是PHP数据存储的核心,各种常量、变量、函数、类、对象等都用它来组织,这个数据结构就是HashTable。
    2009-08-08
  • 浅谈一种Laravel路由文件划分方式

    浅谈一种Laravel路由文件划分方式

    我估计我们所有人都遇到过这样的情况,即我们有一个写满路由的超大文件。不骗你,这让我很长一段时间几近抓狂,我不得不想个办法解决这个问题。 因此,这就是我最终用来构造路由文件的方法。
    2021-05-05

最新评论

?


http://www.vxiaotou.com