直接下载官方demo,
支付宝demo改名为 alipay,放在extend文件夹下面,
微信demo改名为wx,也放在extend文件下面,微信demo需要修改的有两处:1.‘extend/wx/example/WxPay.Config.php’文件中‘require_once "../lib/WxPay.Config.Interface.php"’改为 ‘require_once __DIR__."/../lib/WxPay.Config.Interface.php"’;2.‘extend/wx/example/WxPay.NativePay.php’文件中‘require_once "../lib/WxPay.Api.php"’改为‘require_once __DIR__."/../lib/WxPay.Api.php"’
控制器代码如下(控制器路径:api/user/controller/Pay.php)
<?php
namespace app\user\controller;
use think\Db;
use think\Controller;
class Pay extends Controller
{
/*
* 支付宝支付 $money 金额 ,前端直接请求访问该链接即可
*/
public function pay($money=0.01)
{
import('alipay.pagepay.service.AlipayTradeService', EXTEND_PATH, '.php');
import('alipay.pagepay.buildermodel.AlipayTradePagePayContentBuilder', EX TEND_PATH, '.php');
$order_sn = time(); // 生成订单号,这里直接取时间戳了
/*
* 创建支付订单,存入充值表中,大家自行处理
* */
$data = [
'order_sn' => $order_sn,
'uid' => session('user.id'),
'price' => $money,
'status' => 1,
'order_time'=> date('Y-m-d H:i:s')
];
Db::name('recharge')->insert($data);
// 请求参数设置
$config = config('pay'); // 读取支付宝配置信息
$out_trade_no = $order_sn; // 商户订单号,商户网站订单系统中唯一订单号,必填
$subject = '支付宝充值测试'; // 订单名称,必填
$total_amount = $money; // 付款金额,必填
$body = '支付宝充值测试'; // 商品描述,可空
// 构造参数
$payRequestBuilder = new \AlipayTradePagePayContentBuilder();
$payRequestBuilder->setBody($body);
$payRequestBuilder->setSubject($subject);
$payRequestBuilder->setTotalAmount($total_amount);
$payRequestBuilder->setOutTradeNo($out_trade_no);
$aop = new \AlipayTradeService($config);
$response = $aop->pagePay($payRequestBuilder,$config['return_url'],$config['notify_url']); // (请求参数, 同步通知地址, 异步通知地址)
//输出表单
var_dump($response);
}
// 异步通知地址
public function notifyurl()
{
Db::startTrans();
try {
$post = input();
if ($post['trade_status'] == "TRADE_SUCCESS") {
// 验证订单状态,订单金额,订单APPID
// 商户自行对订单进行处理
} else {
echo "error";
}
Db::commit();
} catch (\Exception $e) {
Db::rollback();
}
}
// 同步通知地址
public function returnurl()
{
$this->redirect('user/Finance/lists');
}
/*
* 微信支付接入 $money 金额(微信的单位是分,真正的金额需要乘以100)
*/
public function wxPay($money=0.01)
{
import('wx.lib.WxPay', EXTEND_PATH, '.Api.php');
import('wx.example.WxPay', EXTEND_PATH, '.NativePay.php');
import('wx.lib.WxPay', EXTEND_PATH, '.Data.php');
$order_sn = time(); // 生成订单号,这里直接取时间戳了
// 构造请求参数
$notify = new \NativePay();
$input = new \WxPayUnifiedOrder();
$input->SetBody("微信充值测试");
$input->SetAttach("微信充值测试");
$input->SetOut_trade_no($order_sn);
$input->SetTotal_fee($money*100);
$input->SetTime_start(date("YmdHis"));
$input->SetTime_expire(date("YmdHis", time() + 600));
$input->SetGoods_tag("几度CMS账户充值");
$input->SetNotify_url(config('wx.NotifyUrl'));
$input->SetTrade_type("NATIVE");
$input->SetProduct_id($order_sn);
/*
* 创建支付订单,存入充值表中,大家自行处理
* */
$data = [
'order_sn' => $order_sn,
'uid' => session('user.id'),
'price' => $money,
'status' => 1,
'order_time'=> date('Y-m-d H:i:s')
];
Db::name('recharge')->insert($data);
$result = $notify->GetPayUrl($input);
$url2 = $result["code_url"];
$src = 'http://'.$_SERVER['HTTP_HOST'].'/user/Pay/qrcode.html?data='.urlencode($url2);
echo '<div style="width: 900px; height: 500px; margin: 200px auto; border: 1px solid #ccc; text-align: center;">
<div style="margin-left: 10px;color:#556B2F;font-size:30px;font-weight: bolder;">
<img style="height: 30px;" src="/static/wx/wxpay.png" alt="微信支付">
微信支付
</div>
<br/>
<p>
<img alt="微信支付" src="http://'.$_SERVER['HTTP_HOST'].'/user/Pay/qrcode.html?data='.urlencode($url2).'" style="width:200px; height:200px; border: 1px solid #ccc;"/>
</p>
<p>扫一扫支付'.$money.' 元</p>
</div>';
}
// 生成微信支付二维码
public function qrcode()
{
import('wx.example.phpqrcode.phpqrcode', EXTEND_PATH, '.php');
$QRcode = new \QRcode();
$url = urldecode($_GET["data"]);
if (substr($url, 0, 6) == "weixin") {
$QRcode->png($url);
} else {
header('HTTP/1.1 404 Not Found');
}
}
// 微信异步通知
public function wxNotify()
{
$data = trim(file_get_contents('php://input')); // 读取回调信息
$xmls = simplexml_load_string($data);
// xml转换成数组
$array = [];
foreach ($xmls as $key => $xml) {
$count = $xml->count();
if ($count == 0) {
$res = (string) $xml;
} else {
$res = parseXml($xml);
}
$array[$key] = $res;
}
// 找到当前回调信息
$order = Db::name('recharge')->where('order_sn', $array['out_trade_no'])->find();
if ($order) {
if ($array['result_code'] == 'SUCCESS' && $array['return_code'] == 'SUCCESS' ) {
// 验证订单状态,订单金额,订单APPID
if ($order['status'] == 1 && $order['price'] == round($array['total_fee']*0.01, 2) && config('wx.AppId') == $array['appid']) {
// 验证订单状态,订单金额,订单APPID
// 商户自行对订单进行处理
// 记录日志
$this->log_into_txt(EXTEND_PATH.'wx/logs/'.date('Y_m_d').'.log' ,"【接收到微信的notifyurl通知】:支付成功 \n" ,'head');
$this->log_into_txt(EXTEND_PATH.'wx/logs/'.date('Y_m_d').'.log' ,"$data\n");
echo 'success';
} else {
// 记录日志
$this->log_into_txt(EXTEND_PATH.'wx/logs/'.date('Y_m_d').'.log' ,"【接收到微信的notifyurl通知】:支付失败 \n" ,'head');
$this->log_into_txt(EXTEND_PATH.'wx/logs/'.date('Y_m_d').'.log' ,"$data\n");
echo 'error';
}
}
exit(); // 微信会重复回调,必须exit给终止掉,采坑点
}
}
/**
* 网上找来的,自带的日志报错,懒得调了
* [log_into_txt 写入日志到txt文件]
* @param [type] $file [文件路径]
* @param [type] $data [写入的数据]
* @param [type] $type [head写入头端,foot写入尾端,all全部]
* @return [type] [description]
*/
function log_into_txt($file, $str, $type='')
{
//文件地址
$fileName = substr($file, 0, -(strlen($file)-strrpos($file,'/')));
if (!is_dir($fileName)) {
mkdir($fileName, 0777, true);
chmod($fileName, 0777);
}
$date = date('Y-m-d H:i:s');
$handle = fopen($file, "a+");
flock($handle, LOCK_EX);
if($type == 'head' || $type == 'all') {
fwrite($handle,"---------------------------------------------------------------------------------\r\n");
}
fwrite($handle,"$date\n{$str}\r\n");
if($type == 'foot' || $type == 'all') {
fwrite($handle,"---------------------------------------------------------------------------------\r\n");
}
flock($handle, LOCK_UN);
fclose($handle);
}
}
最佳答案
