微信app支付 php,php微信支付之APP支付方法

news/2024/7/7 20:46:01

php微信支付之APP支付方法

本文实例讲述了微信开放平台移动应用集成微信支付功能。分享给大家供大家参考。具体分析如下,更多消息请关注应届毕业生网!

WechatAppPay文件代码如下:

?

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


http://www.niftyadmin.cn/n/2828644.html

相关文章

工地人员定位管理系统,如何有效做到安全生产双预防?

近年来&#xff0c;我国城市化进程不断推进&#xff0c;建设工程规模不断扩大。工程建设规模越大&#xff0c;流程越复杂&#xff0c;对现场监管要求也随之增高。建筑业借助大数据、人员定位、5G等先进技术与工地业务加速融合&#xff0c;加强施工现场安全管理&#xff0c;规范…

linux中的alsa工具与Android中的tinyalsa工具【转】

本文转载自&#xff1a;http://blog.csdn.net/luckywang1103/article/details/48053015 版权声明&#xff1a;本文为博主原创文章&#xff0c;未经博主允许不得转载。 目录(?)[] 由于Android中默认并没有使用标准alsa&#xff0c;而是使用的是tinyalsa&#xff0c;所以就算基于…

wifi芯片_适合家用WiFi的开关电源芯片

在进入互联网时代现在已经很少有家庭没有安装WiFi&#xff0c;这项技术可以算的上是近几年来最伟大的发明之一。它彻底改变了人们的生活&#xff0c;改变了智能设备对网络数据的接受方式。但随着技术的发展&#xff0c;人们开始越来越不满足于目前的WiFi速度&#xff0c;那么如…

php二维数组json,php如何将二维数组转为json数据

php如何将二维数组转为json数据php将二维数组转为json数据的方法&#xff1a;可以利用php内置函数json_encode()来实现。json_encode()函数用于对变量进行json编码&#xff0c;如果执行成功则返回json数据&#xff0c;否则返回false。json_encode() 用于对变量进行 JSON 编码&a…

php脚本怎么设置是否,如何调试PHP脚本?

这是我的小型调试环境&#xff1a;error_reporting(-1);assert_options(ASSERT_ACTIVE, 1);assert_options(ASSERT_WARNING, 0);assert_options(ASSERT_BAIL, 0);assert_options(ASSERT_QUIET_EVAL, 0);assert_options(ASSERT_CALLBACK, assert_callcack);set_error_handler(er…

Rocket.Chat 开源IM系统部署

Rocket.Chat 官方给出的文档也个人觉得太麻烦了&#xff0c;并且对ubuntu的支持程度远高于CentOS&#xff0c;自己就折腾写了个安装的笔记&#xff0c;如果是在公司内部或者是部门内部还是很有用处的&#xff0c;比较看中的功能有和gitlab或github的整合&#xff0c;以及注册认…

MongoDB学习笔记(二)--Capped集合 GridFS存储文件

Capped集合 Capped集合的大小是固定的&#xff0c;如果空间都被用完了&#xff0c;新添加的对象会取代最旧的那个数据。 创建使用了db.createCollection()方法创建了一个名字为mycapped&#xff0c;空间大小为1000…

unity开发相关环境(vs、MonoDevelop)windows平台编码问题

情景描述&#xff1a;最近在做Unity的网络底层&#xff0c;用VS编写源码&#xff0c;MonoDevelop用来Debug&#xff0c;在Flash Builder上搭建的Python做协议生成器&#xff0c;期间有无数次Unity莫名奇妙的的down掉了&#xff0c;然后仔细分析了一下&#xff1a; 1、unity会爆…