0

0

微信支付之APP支付

php中文网

php中文网

发布时间:2016-06-06 19:37:41

|

1302人浏览过

|

来源于php中文网

原创

微信开放平台移动应用集成微信支付功能。 具体使用请移步:http://www.360us.net/article/23.html 仅仅是消费功能,其他功能没有加。 开放平台的微信支付和公众号的微信支付是不一样的,这里说明一下。 无 ?phpnamespace common\services\WechatPay;class Wec

微信开放平台移动应用集成微信支付功能。
具体使用请移步:http://www.360us.net/article/23.html
仅仅是消费功能,其他功能没有加。

开放平台的微信支付和公众号的微信支付是不一样的,这里说明一下。
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) );
	}

}
微信app下载
微信app下载

微信是一款手机通信软件,支持通过手机网络发送语音短信、视频、图片和文字。微信可以单聊及群聊,还能根据地理位置找到附近的人,带给大家全新的移动沟通体验,有需要的小伙伴快来保存下载体验吧!

下载

相关标签:

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

相关专题

更多
php源码安装教程大全
php源码安装教程大全

本专题整合了php源码安装教程,阅读专题下面的文章了解更多详细内容。

150

2025.12.31

php网站源码教程大全
php网站源码教程大全

本专题整合了php网站源码相关教程,阅读专题下面的文章了解更多详细内容。

88

2025.12.31

视频文件格式
视频文件格式

本专题整合了视频文件格式相关内容,阅读专题下面的文章了解更多详细内容。

90

2025.12.31

不受国内限制的浏览器大全
不受国内限制的浏览器大全

想找真正自由、无限制的上网体验?本合集精选2025年最开放、隐私强、访问无阻的浏览器App,涵盖Tor、Brave、Via、X浏览器、Mullvad等高自由度工具。支持自定义搜索引擎、广告拦截、隐身模式及全球网站无障碍访问,部分更具备防追踪、去谷歌化、双内核切换等高级功能。无论日常浏览、隐私保护还是突破地域限制,总有一款适合你!

61

2025.12.31

出现404解决方法大全
出现404解决方法大全

本专题整合了404错误解决方法大全,阅读专题下面的文章了解更多详细内容。

493

2025.12.31

html5怎么播放视频
html5怎么播放视频

想让网页流畅播放视频?本合集详解HTML5视频播放核心方法!涵盖<video>标签基础用法、多格式兼容(MP4/WebM/OGV)、自定义播放控件、响应式适配及常见浏览器兼容问题解决方案。无需插件,纯前端实现高清视频嵌入,助你快速打造现代化网页视频体验。

16

2025.12.31

关闭win10系统自动更新教程大全
关闭win10系统自动更新教程大全

本专题整合了关闭win10系统自动更新教程大全,阅读专题下面的文章了解更多详细内容。

12

2025.12.31

阻止电脑自动安装软件教程
阻止电脑自动安装软件教程

本专题整合了阻止电脑自动安装软件教程,阅读专题下面的文章了解更多详细教程。

5

2025.12.31

html5怎么使用
html5怎么使用

想快速上手HTML5开发?本合集为你整理最实用的HTML5使用指南!涵盖HTML5基础语法、主流框架(如Bootstrap、Vue、React)集成方法,以及无需安装、直接在线编辑运行的平台推荐(如CodePen、JSFiddle)。无论你是新手还是进阶开发者,都能轻松掌握HTML5网页制作、响应式布局与交互功能开发,零配置开启高效前端编程之旅!

2

2025.12.31

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
Excel 教程
Excel 教程

共162课时 | 10.4万人学习

SciPy 教程
SciPy 教程

共10课时 | 1.0万人学习

PHP课程
PHP课程

共137课时 | 8.2万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号