作者 郭鑫

pc支付上传,接口修改调试

正在显示 46 个修改的文件 包含 3294 行增加39 行删除

要显示太多修改。

为保证性能只显示 46 of 46+ 个文件。

... ... @@ -25,7 +25,14 @@ class CommonController extends HomeBaseController
if($this->request->param('connect')){
$connect = $this->request->param('connect');
}else{
$connect = 2;
$url = explode('/',$_SERVER['PATH_INFO']);
$count_url = count($url);
$fun = $url[$count_url-1];
if($fun == 'join' || $fun == 'login' || $fun == 'upload_one' ){
$connect = 1;
}else{
$connect = 2;
}
}
if($connect == 2){
$where_firstMember['token'] = $this->request->param('token');
... ... @@ -53,6 +60,7 @@ class CommonController extends HomeBaseController
}
}
/**
* API返回信息格式函数 ;0失败,1成功,-1需要登录
* @param string $code
... ...
... ... @@ -136,6 +136,7 @@ class IntermediaryController extends CommonController
$this->apiResponse('0','用户信息错误');
}
// 查询签到信息
$member['pic'] = cmf_get_image_url($member['pic']);
$where_checkin['agency_id'] = $member['id'];
$tme_str = date('Y-m-d',time());
$where_checkin['create_time'] = strtotime($tme_str);
... ... @@ -161,12 +162,21 @@ class IntermediaryController extends CommonController
public function myIndex(Request $request){
$token = $request->param('token');
$member = $this->left($token);
$quarters = explode('+',$member['quarters']);
$final['intermediary'] = $member;
$where_need['city'] = $member['city'];
$where_need['status'] = 2;
$where_need['quarters'] = array('like','%'.$member['quarters'].'%');
if($quarters){
foreach ($quarters as $quartersk=>$quartersv){
$quarters[$quartersk] = '%'.$quartersv.'%';
}
}
$where_need['quarters'] = array('like',$quarters,'OR');
$page = $request->param('page');
$need_list = Db::name('UserNeed')->where($where_need)->field("id,city,quarters,room,floor,house_type,renovation,quotation_time,create_time,people")->limit(10)->page($page)->select()->toArray();
$need_list = Db::name('UserNeed')->where($where_need)
->field("id,city,quarters,room,floor,house_type,renovation,quotation_time,create_time,people,pay_time")
->limit(10)->page($page)
->select()->toArray();
if($need_list){
$final['intermediary_need'] = $need_list;
}else{
... ... @@ -195,7 +205,7 @@ class IntermediaryController extends CommonController
$where_need['id'] = $request->param('need_id');
$where_need['status'] = 2;
$need_list = Db::name('UserNeed')->where($where_need)
->field("id,user_id,city,quarters,room,floor,house_type,renovation,area,is_first,loan,contract,quotation_time,create_time,people,else")
->field("id,user_id,city,quarters,room,floor,house_type,renovation,area,is_first,loan,contract,quotation_time,create_time,people,else,pay_time")
->find();
if($need_list){
$final['intermediary_need'] = $need_list;
... ... @@ -428,6 +438,7 @@ class IntermediaryController extends CommonController
* @param name:company type:int require:1 default: other: desc:所属公司
* @param name:store type:int require:1 default: other: desc:门店
* @param name:quarters type:int require:1 default: other: desc:服务小区
* @param name:pic type:varchar require:1 default: other: desc:中介头像
* @return data:''@
* @data status:'状态(1->待发布,2->已发布,待报价,3->已成交,4->未交保证金,5->已过期,6->未选择中介,7->中介未确认,8->报价人数不足,9->删除)'
*/
... ... @@ -441,6 +452,9 @@ class IntermediaryController extends CommonController
$update_member['id'] = $member['id'];
$update_member['store'] = $data['store'];
$update_member['quarters'] = $data['quarters'];
if(!empty($data['pic'])){
$update_member['pic'] = $data['pic'];
}
$model = new MemberModel();
$member = $model->isUpdate(true)->save($update_member);
if(!$member){
... ... @@ -452,6 +466,7 @@ class IntermediaryController extends CommonController
if(!$member){
$this->apiResponse('0','中介信息有误');
}else{
$member['pic'] = cmf_get_image_url($member['pic']);
$this->apiResponse('1','成功',$member);
}
}
... ...
... ... @@ -47,8 +47,8 @@ class IntermediaryneedController extends CommonController
*/
public function payMoney($housing_price){
$where_inteRule['status'] = 1;
$where_inteRule['low'] = array('gt',$housing_price);
$where_inteRule['height'] = array('lt',$housing_price);
$where_inteRule['low'] = array('elt',$housing_price);
$where_inteRule['height'] = array('egt',$housing_price);
$inte_money = Db::name('IntermediaryRule')->where($where_inteRule)->field('money')->find();
if(!$inte_money){
$this->apiResponse('0','保证金获取失败');
... ... @@ -119,6 +119,7 @@ class IntermediaryneedController extends CommonController
*/
public function send(Request $request)
{
// header('Access-Control-Allow-Origin:*');
if($request->Post('token') && $request->Post('housing_price')){
// 判空,处理
$validate = Loader::validate('IntermediaryNeed');
... ...
... ... @@ -151,12 +151,15 @@ class UserController extends CommonController
* @param name:password type:int require:1 default: other: desc:密码
* @param name:sure_password type:int require:1 default: other: desc:确认密码
* @param name:code type:int require:1 default: other: desc:验证码
* @param name:parent_id type:int require:1 default: other: desc:推荐人id
* @param name:parent type:int require:1 default: other: desc:推荐人手机号
* @param name:connect type:int require:1 default: other:1 登录注册 ,2其他 desc:1
* @return data:'token'
*/
public function join(Request $request)
{
if($request->Post() && $request->Post('name')) {
$getParam = $request->param();
Db::startTrans();
// 验证
$validate = Loader::validate('User');
... ... @@ -203,9 +206,33 @@ class UserController extends CommonController
$data['token'] = $this->md5($str);
$data['type'] = 1;
$data['start'] = 50;
if(!empty($getParam['parent_id']) || !empty($getParam['parent'])){
$data['parent_id'] = $getParam['parent_id'];
$data['parent_tel'] = $getParam['parent'];
}
$add = $user->allowField(true)->save($data);
$uid = $user->id;
if($add){
// 注册成功
if(!empty($getParam['parent_id'])){
$where_parentAdd['id'] = $getParam['parent_id'];
$where_parentAdd['type'] = 2;
$add_agencyScore = $user->where($where_parentAdd)->setInc('reputation','1');
if(!$add_agencyScore){
Db::rollback();
}
}
$url = $_SERVER['SERVER_ADDR'].$_SERVER['REDIRECT_URL'].'?uid='.$uid;
$get_url = $this->shot($url);
$update_shot['link'] = $get_url;
$update_shot['id'] = $uid;
$result_shot = $user->isUpdate(true)->save($update_shot);
if(!$result_shot){
Db::rollback();
}
$startAdd['detail'] = '注册获得';
$startAdd['star'] = 50;
$startAdd['type'] = 1;
... ... @@ -233,8 +260,15 @@ class UserController extends CommonController
$list = Db::name('Protocol')->where($where_pro)->order("update_time desc")->field("title,content")->find();
$list['content'] = htmlspecialchars_decode($list['content']);
// 推荐人(未完)
$getdata = $this->request->param();
if(!empty($getdata['uid'])){
$where_member['id'] = $getdata['uid'];
$find_parent = Db::name('Member')->where($where_member)->field('id,tel')->find();
if($find_parent){
$list['parent'] = $find_parent['tel'];
$list['parent_id'] = $find_parent['id'];
}
}
if($list){
$this->apiResponse('1','成功',$list);
}else{
... ... @@ -253,6 +287,7 @@ class UserController extends CommonController
* @param name:tel type:int require:1 default: other: desc:手机号
* @param name:password type:int require:1 default: other: desc:密码
* @param name:imgCode type:int require:1 default: other: desc:验证码
* @param name:gener type:int require:1 default: other: desc:1->用户,2->中介
* @param name:rand type:int require:1 default: other: desc:随机数
* @param name:connect type:int require:1 default: other:1 登录注册 ,2其他 desc:1
* @return data:''@
... ... @@ -260,7 +295,6 @@ class UserController extends CommonController
*/
// 登录
public function login(Request $request){
if($request->post() && $request->Post('tel')){
$getData = $request->param();
// 登录验证
... ... @@ -291,9 +325,9 @@ class UserController extends CommonController
if($find_code['code'] != $postImg){
$this->apiResponse('0','验证码错误1');
}
// else{
// Db::name('Imgcode')->where($where_imgcode)->delete();
// }
else{
Db::name('Imgcode')->where($where_imgcode)->delete();
}
}else{
$this->apiResponse('0','验证码错误2');
}
... ... @@ -301,6 +335,7 @@ class UserController extends CommonController
$memberModel = new MemberModel();
$where_member['tel'] = $tel;
$where_member['password'] = $this->md5($password);
$where_member['type'] = $getData['gener'];
$uid = Db::name('Member')->where($where_member)->field('id,token,type')->find();
if($uid){
// 登录重置token
... ... @@ -816,6 +851,59 @@ class UserController extends CommonController
$this->apiResponse('1','成功',$final);
}
/**
* @title 用户个人中心比价详情(sure)
* @description 接口说明
* @author 开发者
* @url /api/portal/User/myNeed
* @method POST
* @param name:token type:int require:1 default: other: desc:token
* @param name:need_id type:int require:1 default: other: desc:需求id
* @return data:''@
* @data status:'状态(1->待发布,2->未交保证金,3->已发布,待报价,4->报价人数不足,5->待选择中介,6->未选择中介,7->已选择中介,待中介确认,8->中介未确认,9->删除,10->已成交,中介已确认)'
* @data comment:'剩余评价次数'
*/
public function myNeedDetail(Request $request){
$token = $request->param('token');
$member = $this->myleft($token);
$data = $request->param();
$final['user'] = $member;
$where_userNeed['user_id'] = $member['id'];
$where_userNeed['id'] = $member['need_id'];
$where_userNeed['status'] = array('neq',9);
$user_need = Db::name('UserNeed')->where($where_userNeed)
->order('create_time desc')
->select()->toArray();
if($user_need){
foreach ($user_need as $unk=>$unv){
$where_comment['need_id'] = $unv['id'];
$where_comment['user_id'] = $unv['user_id'];
$where_comment['status'] = 1;
$comment = Db::name('Comment')->where($where_comment)->field('is_comment,create_time')->find();
if($comment){
// 判断是否超过30天
if(time() > ($comment['create_time'] + 2592000)){
$user_need[$unk]['comment'] = 0;
}else{
if($comment['is_comment'] == 1){
$user_need[$unk]['comment'] = 0;
}else{
$user_need[$unk]['comment'] = 1;
}
}
}else{
$user_need[$unk]['comment'] = 2;
}
}
$final['user_need'] = $user_need;
}else{
$final['user_need'] = array();
}
$final['user'] = $member;
$this->apiResponse('1','成功',$final);
}
/**
* @title 我的比价明细(sure)
... ... @@ -1251,8 +1339,12 @@ class UserController extends CommonController
// 短网址
function shot($url){
$jump = "http://suo.im/api.php?url=".$url;
$shot_val = file_get_contents($jump);
return $shot_val;
}
}
... ...
<?php
/**
* Created by PhpStorm.
* User: 29925
* Date: 2018/6/14
* Time: 16:05
*/
namespace app\portal\controller;
use cmf\controller\HomeBaseController;
use think\Db;
use traits\controller\Jump;
class AlipayController extends HomeBaseController
{
public function _initialize()
{
require_once VENDOR_PATH.'alipay/config.php';
require_once VENDOR_PATH.'alipay/pagepay/service/AlipayTradeService.php';
require_once VENDOR_PATH.'alipay/pagepay/buildermodel/AlipayTradePagePayContentBuilder.php';
$this->config = $config;
}
public function alipay() {
$data = $this->request->param();
$config = $this->config;
//商户订单号,商户网站订单系统中唯一订单号,必填
$out_trade_no = trim($data['order_sn']);
//订单名称,必填
$subject = trim($data['name']);
//付款金额,必填
// $total_amount = trim(I('get.price'));
$total_amount = trim(0.01);
//商品描述,可空
$body = '';
//构造参数
$payRequestBuilder = new \AlipayTradePagePayContentBuilder();
$payRequestBuilder->setBody($body);
$payRequestBuilder->setSubject($subject);
$payRequestBuilder->setTotalAmount($total_amount);
$payRequestBuilder->setOutTradeNo($out_trade_no);
$aop = new \AlipayTradeService($config);
/**
* pagePay 电脑网站支付请求
* @param $builder 业务参数,使用buildmodel中的对象生成。
* @param $return_url 同步跳转地址,公网可以访问
* @param $notify_url 异步通知地址,公网可以访问
* @return $response 支付宝返回的信息
*/
$response = $aop->pagePay($payRequestBuilder,$config['return_url'],$config['notify_url']);
//输出表单
var_dump($response);
}
// 回调
public function notify_url() {
$config = $this->config;
$arr=$_POST;
$alipaySevice = new \AlipayTradeService($config);
$alipaySevice->writeLog(var_export($_POST,true));
$result = $alipaySevice->check($arr);
if($result) {
//商户订单号
$out_trade_no = $_POST['out_trade_no'];
//支付宝交易号
$trade_no = $_POST['trade_no'];
//交易状态
$trade_status = $_POST['trade_status'];
if($_POST['trade_status'] == 'TRADE_FINISHED') {
//判断该笔订单是否在商户网站中已经做过处理
//如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序
//请务必判断请求时的total_amount与通知时获取的total_fee为一致的
//如果有做过处理,不执行商户的业务程序
//注意:
//退款日期超过可退款期限后(如三个月可退款),支付宝系统发送该交易状态通知
}
else if ($_POST['trade_status'] == 'TRADE_SUCCESS') {
//判断该笔订单是否在商户网站中已经做过处理
//如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序
//请务必判断请求时的total_amount与通知时获取的total_fee为一致的
//如果有做过处理,不执行商户的业务程序
//注意:
//付款完成后,支付宝系统发送该交易状态通知
}
}
}
//
public function return_url() {
$config = $this->config;
$arr = $_GET;
$alipaySevice = new \AlipayTradeService($config);
$result = $alipaySevice->check($arr);
// var_dump($_GET);
// echo '<br/>';
// var_dump($result);exit;
if ($result) {
//商户订单号
$out_trade_no = htmlspecialchars($_GET['out_trade_no']);
//支付宝交易号
$trade_no = htmlspecialchars($_GET['trade_no']);
$data = $_GET;
$where['order_sn'] = $data['out_trade_no'];
$where['price'] = $data['total_amount'];
$user_licence_model = Db::name('UserLicence');
$userLicenceInfo = $user_licence_model->where($where)->find();
$info['paytype'] = 2;
$info['pay_time'] = time();
$info['status'] = 1;
$info['transaction_id'] = $data['trade_no'];
Db::startTrans();
$results = $user_licence_model->where($where)->update($info);
if(!$results) {
Db::rollback();
} else {
Db::commit();
if($userLicenceInfo['type'] == 1) {
$this->redirect(url('user/licence/sesame'));
}
if($userLicenceInfo['type'] == 2) {
$this->redirect(url('user/licence/reputation'));
}
if($userLicenceInfo['type'] == 3) {
$this->redirect(url('user/licence/edu'));
}
}
}
}
}
\ No newline at end of file
... ...
... ... @@ -83,7 +83,7 @@ class BankController extends AdminBaseController
{
if($request->post()){
// 添加数据
$data = $request->post();
$data = $request->param();
if($request->Post('id')){
// 修改
$add['name'] = $data['name'];
... ...
... ... @@ -13,6 +13,7 @@ namespace app\portal\controller;
use cmf\controller\HomeBaseController;
use think\Request;
use think\Loader;
use cmf\lib\Upload;
class CommonController extends HomeBaseController
{
... ... @@ -39,4 +40,34 @@ class CommonController extends HomeBaseController
$final = sha1(md5($number));
return $final;
}
/**
* @title 上传素材
* @description 接口说明
* @author 开发者
* @url /portal/Common/upload
* @method POST
* @param name:file type:varchar require:1 default: other: desc:素材内容
* @param name:filetype type:varchar require:1 default: other: desc:素材类型
* @param name:app type:varchar require:1 default: other: desc:素材存储路径
*
* @return title:标题
*
*/
public function upload() {
if ($this->request->isPost()) {
$uploader = new Upload();
// return ["code"=>40004, "msg"=>$this->request->param(), "data"=>[$this->request->file()]];
$result = $uploader->upload();
if ($result === false) {
echo json_encode(["code"=>40004, "msg"=>$uploader->getError(), "data"=>[]]);exit;
} else {
echo json_encode(["code"=>1, "msg"=>"上传成功!", "data"=>[$result]]);exit;
}
}
}
}
... ...
<?php
/**
* Created by PhpStorm.
* User: 29925
* Date: 2018/6/13
* Time: 17:53
*/
namespace app\portal\controller;
use cmf\controller\HomeBaseController;
use think\Db;
class NotifyController extends HomeBaseController
{
// 微信支付回调
public function notify() {
require_once VENDOR_PATH."WxpayAPI/lib/WxPay.Api.php";
require_once VENDOR_PATH."WxpayAPI/lib/WxPay.Notify.php";
require_once VENDOR_PATH.'WxpayAPI/example/log.php';
$post = $this->request->param();
if($post==null){
$post = file_get_contents("php://input");
if($post == null){
$post = $GLOBALS['HTTP_RAW_POST_DATA'];
}
}
if(!empty($post)) {
$xml = $post; //微信的回调数据
$base = new \WxPayResults(); //实例化数据对象结果类
$data = $base->FromXml($xml);
if($base->CheckSign() == true){
if ($data["return_code"] == "SUCCESS") {
$where['order_sn'] = $data['attach'];
if (!$where['order_sn']) {
$where['order_sn'] = $data['out_trade_no'];
}
$where['price'] = $data['total_fee']/100;
$user_licence_model = Db::name('UserLicence');
$info = [
'paytype'=>1,
'pay_time'=>time(),
'status'=>1,
'transaction_id'=>$data['transaction_id']
];
$results = $user_licence_model->where($where)->update($info);
if($results) {
$this->return_success();
}
}
}
}
}
/*
* 给微信发送确认订单金额和签名正确,SUCCESS信息
*/
private function return_success(){
$return['return_code'] = 'SUCCESS';
$return['return_msg'] = 'OK';
$xml_post = '<xml>
<return_code>'.$return['return_code'].'</return_code>
<return_msg>'.$return['return_msg'].'</return_msg>
</xml>';
echo $xml_post;exit;
}
// 查询订单是否支付完成
public function searchStatus() {
if($this->request->isAjax()) {
$data = $this->request->param();
$order_sn = $data['order_sn'];
$user_licence_model = Db::name('UserLicence');
$status = $user_licence_model->where(['order_sn'=>$order_sn])->value('status');
if($status == 1) {
return ['code'=>1,'msg'=>'支付成功'];
} else {
return ['code'=>0,'msg'=>'未支付完成'];
}
}
}
}
\ No newline at end of file
... ...
<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 老猫 <thinkcmf@126.com>
// +----------------------------------------------------------------------
namespace app\portal\controller;
use app\portal\model\BankModel;
use app\portal\model\BrandModel;
use app\portal\model\CooperationModel;
use app\portal\model\ProcessModel;
use app\portal\model\RewardModel;
use cmf\controller\AdminBaseController;
use app\portal\model\PortalTagModel;
use app\portal\service\PostService;
use think\Db;
use think\Request;
use think\Loader;
class RewardController extends AdminBaseController
{
/**
* 列表(暂无用)
* @adminMenu(
* 'name' => '文章管理',
* 'parent' => 'portal/AdminIndex/default',
* 'display'=> true,
* 'hasView'=> true,
* 'order' => 10000,
* 'icon' => '',
* 'remark' => '文章列表',
* 'param' => ''
* )
*/
public function index(Request $request)
{
$where_coo['status'] = 1;
// $where_coo = array();
if($request->post()){
$search = $request->post();
if($search['start_time']){
$start = strtotime($search['start_time']);
if($search['end_time']){
$end = strtotime($search['end_time']);
}else{
$end = time();
}
$where_coo['update_time'] = array('between',"$start,$end");
$this->assign('start_time',date('Y-m-d H:i',$start));
$this->assign('end_time',date('Y-m-d H:i',$end));
}
if($search['keyword']){
$where_coo['name'] = array('like',"%".$search['keyword']."%");
$this->assign('keyword',$search['keyword']);
}
}
$coo_list = Db::name('Reward')->where($where_coo)->order(' create_time desc')->paginate();
$page = $coo_list->render();
$this->assign('page',$page);
$this->assign('list',$coo_list);
return $this->fetch();
}
/**
* 添加、修改
* @adminMenu(
* 'name' => '添加文章',
* 'parent' => 'index',
* 'display'=> false,
* 'hasView'=> true,
* 'order' => 10000,
* 'icon' => '',
* 'remark' => '添加文章',
* 'param' => ''
* )
*/
public function add(Request $request)
{
if($request->post()){
// 添加数据
$data = $request->param();
if($request->Post('id')){
// 修改
$add = $data;
$validate = Loader::validate('Bank');
if(!$validate->scene('edit')->check($add)){
$mes = $validate->getError();
$this->error("$mes");
}
$add['id'] = $request->param('id');
$model = new RewardModel();
$final = $model->isUpdate(true)->allowField(true)->save($add);
}else{
// 添加
$add = $data;
$validate = Loader::validate('Reward');
if(!$validate->scene('add')->check($add)){
$mes = $validate->getError();
$this->error("$mes");
}
$model = new RewardModel();
$final = $model->save($add);
}
if($final){
$this->success('成功',url('index'));
}else{
$this->error('失败');
}
}else{
$where_find['id'] = $request->param('id');
$list = Db::name('Reward')->where($where_find)->find();
$this->assign('list',$list);
return $this->fetch('add');
}
}
// 删除
public function del(Request $request){
$ids = $this->request->post();
$id = $request->param('id');
if($ids){
$add_del['id'] = array('in',$ids['ids']);
}else if($id){
$add_del['id'] = $request->param('id');
}else{
$this->error('删除失败');
}
$add_del['status'] = 9;
$model = new BankModel();
$del = $model->isUpdate(true)->allowField(true)->save($add_del);
if($del){
$this->success('删除成功',url('index'));
}else{
$this->error('删除失败');
}
}
}
... ...
<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 老猫 <thinkcmf@126.com>
// +----------------------------------------------------------------------
namespace app\portal\controller;
use app\portal\model\BankModel;
use app\portal\model\BrandModel;
use app\portal\model\CooperationModel;
use app\portal\model\ProcessModel;
use cmf\controller\AdminBaseController;
use app\portal\model\PortalTagModel;
use app\portal\service\PostService;
use think\Db;
use think\Request;
use think\Loader;
class ShareController extends AdminBaseController
{
/**
* 列表(暂无用)
* @adminMenu(
* 'name' => '文章管理',
* 'parent' => 'portal/AdminIndex/default',
* 'display'=> true,
* 'hasView'=> true,
* 'order' => 10000,
* 'icon' => '',
* 'remark' => '文章列表',
* 'param' => ''
* )
*/
public function index(Request $request)
{
$where_coo['status'] = 1;
// $where_coo = array();
if($request->post()){
$search = $request->post();
if($search['start_time']){
$start = strtotime($search['start_time']);
if($search['end_time']){
$end = strtotime($search['end_time']);
}else{
$end = time();
}
$where_coo['update_time'] = array('between',"$start,$end");
$this->assign('start_time',date('Y-m-d H:i',$start));
$this->assign('end_time',date('Y-m-d H:i',$end));
}
if($search['keyword']){
$where_coo['name'] = array('like',"%".$search['keyword']."%");
$this->assign('keyword',$search['keyword']);
}
}
$coo_list = Db::name('Bank')->where($where_coo)->order('score desc , create_time desc')->paginate();
$page = $coo_list->render();
$this->assign('page',$page);
$this->assign('list',$coo_list);
return $this->fetch();
}
/**
* 添加、修改
* @adminMenu(
* 'name' => '添加文章',
* 'parent' => 'index',
* 'display'=> false,
* 'hasView'=> true,
* 'order' => 10000,
* 'icon' => '',
* 'remark' => '添加文章',
* 'param' => ''
* )
*/
public function add(Request $request)
{
if($request->post()){
// 添加数据
$data = $request->param();
if($request->Post('id')){
// 修改
$add['name'] = $data['name'];
$add['score'] = $data['score'];
$validate = Loader::validate('Bank');
if(!$validate->scene('edit')->check($add)){
$mes = $validate->getError();
$this->error("$mes");
}
$add['id'] = $request->param('id');
$model = new BankModel();
$final = $model->isUpdate(true)->allowField(true)->save($add);
}else{
// 添加
$add['name'] = $data['name'];
$add['score'] = $data['score'];
$validate = Loader::validate('Bank');
if(!$validate->scene('add')->check($add)){
$mes = $validate->getError();
$this->error("$mes");
}
$model = new BankModel();
$final = $model->save($add);
}
if($final){
$this->success('成功',url('index'));
}else{
$this->error('失败');
}
}else{
$where_find['id'] = $request->param('id');
$list = Db::name('Bank')->where($where_find)->find();
$this->assign('list',$list);
return $this->fetch('add');
}
}
// 删除
public function del(Request $request){
$ids = $this->request->post();
$id = $request->param('id');
if($ids){
$add_del['id'] = array('in',$ids['ids']);
}else if($id){
$add_del['id'] = $request->param('id');
}else{
$this->error('删除失败');
}
$add_del['status'] = 9;
$model = new BankModel();
$del = $model->isUpdate(true)->allowField(true)->save($add_del);
if($del){
$this->success('删除成功',url('index'));
}else{
$this->error('删除失败');
}
}
}
... ...
<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 老猫 <thinkcmf@126.com>
// +----------------------------------------------------------------------
namespace app\portal\model;
use app\admin\model\RouteModel;
use think\Model;
class RewardModel extends Model
{
protected $autoWriteTimestamp = true;
}
\ No newline at end of file
... ...
<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 小夏 < 449134904@qq.com>
// +----------------------------------------------------------------------
namespace app\portal\validate;
use think\Validate;
class RewardValidate extends Validate
{
protected $rule = [
'number' => 'require',
];
protected $message = [
'number.require' => '金额不为空!',
];
protected $scene = [
];
}
\ No newline at end of file
... ...
... ... @@ -13,7 +13,7 @@ return [
// 用户名
'username' => 'root',
// 密码
'password' => '',
'password' => 'root',
// 端口
'hostport' => '3306',
// 数据库编码默认采用utf8
... ...
... ... @@ -162,6 +162,8 @@ return array (
'PORTAL_NEED_USER' => '需求管理',
'PORTAL_NEW_INDEX' => '最新成交公布',
'PORTAL_PROCESS_INDEX' => '交易流程',
'PORTAL_REWARD_INDEX' => '信誉奖励设置',
'PORTAL_SHARE_DEFAULT' => '分享内容管理',
'PORTAL_USERNEED_DEFAULT' => '发布需求管理',
'PORTAL_USERNEED_INDEX' => '保证金内容管理',
'USER_ADMINASSET_DELETE' => '删除文件',
... ...
... ... @@ -11,7 +11,7 @@
<li><a href="{:url('Bank/index')}">银行列表</a></li>
<li class="active"><a href="{:url('Bank/add')}">添加银行</a></li>
</ul>
<form action="{:url('Bank/add')}" method="post" class="form-horizontal js-ajax-form margin-top-20">
<form action="{:url('Bank/add')}" method="post" class="form-horizontal js-ajax-form margin-top-20" enctype="multipart/form-data" >
<div class="row">
<div class="col-md-9">
<table class="table table-bordered">
... ... @@ -19,7 +19,7 @@
value="{$list['id']}"/>
<tr>
<th width="15%">银行名称</th>
<td><input class="form-control" type="text" name="name"
<td><input class="form-control" type="text" name="name11"
value="{$list['name']}" placeholder="请输入银行名称"/>
</td>
... ... @@ -66,27 +66,6 @@
});
// function doSelectCategory() {
// var selectedCategoriesId = $('#js-categories-id-input').val();
// openIframeLayer("{:url('AdminCategory/select')}?ids=" + selectedCategoriesId, '请选择分类', {
// area: ['700px', '400px'],
// btn: ['确定', '取消'],
// yes: function (index, layero) {
// //do something
//
// var iframeWin = window[layero.find('iframe')[0]['name']];
// var selectedCategories = iframeWin.confirm();
// if (selectedCategories.selectedCategoriesId.length == 0) {
// layer.msg('请选择分类');
// return;
// }
// $('#js-categories-id-input').val(selectedCategories.selectedCategoriesId.join(','));
// $('#js-categories-name-input').val(selectedCategories.selectedCategoriesName.join(' '));
// //console.log(layer.getFrameIndex(index));
// layer.close(index); //如果设定了yes回调,需进行手工关闭
// }
// });
// }
</script>
</body>
</html>
... ...
<include file="public@header"/>
<style type="text/css">
.pic-list li {
margin-bottom: 5px;
}
</style>
</head>
<body>
<div class="wrap js-check-wrap">
<ul class="nav nav-tabs">
<li><a href="{:url('Reward/index')}">信誉奖励列表</a></li>
<li class="active"><a href="{:url('Reward/add')}">添加信誉奖励</a></li>
</ul>
<form action="{:url('Reward/add')}" method="post" class="form-horizontal js-ajax-form margin-top-20" enctype="multipart/form-data" >
<div class="row">
<div class="col-md-9">
<table class="table table-bordered">
<input class="form-control" type="hidden" name="id"
value="{$list['id']}"/>
<tr>
<th width="15%">信誉奖励类型</th>
<td>
<select style="border: 1px solid #dce4ec;" name="type">
<option name="type[]" value="1" <eq name="list.type" value="1">selected</eq>> &nbsp;注册&nbsp;</option>
<option name="type[]" value="2" <eq name="list.type" value="2">selected</eq>> &nbsp;推荐&nbsp;</option>
<option name="type[]" value="3" <eq name="list.type" value="3">selected</eq>> &nbsp;签到&nbsp;</option>
<option name="type[]" value="4" <eq name="list.type" value="4">selected</eq>> &nbsp;成交&nbsp;</option>
</select>
</td>
</tr>
<tr>
<th width="10%">奖励金额</th>
<td><input class="form-control" type="text" name="number"
value="{$list['number']}" placeholder="请输入奖励金额"/>
</td>
</tr>
</table>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-primary js-ajax-submit">{:lang('ADD')}</button>
<a class="btn btn-default" href="{:url('Reward/index')}">{:lang('BACK')}</a>
</div>
</div>
</div>
</div>
</form>
</div>
<script type="text/javascript" src="__STATIC__/js/admin.js"></script>
<script type="text/javascript">
//编辑器路径定义
var editorURL = GV.WEB_ROOT;
</script>
<script type="text/javascript" src="__STATIC__/js/ueditor/ueditor.config.js"></script>
<script type="text/javascript" src="__STATIC__/js/ueditor/ueditor.all.min.js"></script>
<script type="text/javascript">
$(function () {
editorcontent = new baidu.editor.ui.Editor();
editorcontent.render('content');
try {
editorcontent.sync();
} catch (err) {
}
$('.btn-cancel-thumbnail').click(function () {
$('#thumbnail-preview').attr('src', '__TMPL__/public/assets/images/default-thumbnail.png');
$('#thumbnail').val('');
});
});
</script>
</body>
</html>
... ...
<include file="public@header"/>
</head>
<body>
<div class="wrap js-check-wrap">
<ul class="nav nav-tabs">
<li class="active"><a href="javascript:;">银行列表</a></li>
<li><a href="{:url('Reward/add')}">添加银行</a></li>
</ul>
<form class="well form-inline margin-top-20" method="post" action="{:url('Reward/index')}">
<!--分类:-->
<!--<select class="form-control" name="category" style="width: 140px;">-->
<!--<option value='0'>全部</option>-->
<!--{$category_tree|default=''}-->
<!--</select> &nbsp;&nbsp;-->
时间:
<input type="text" class="form-control js-bootstrap-datetime" name="start_time"
value="{$start_time|default=''}"
style="width: 140px;" autocomplete="off">-
<input type="text" class="form-control js-bootstrap-datetime" name="end_time"
value="{$end_time|default=''}"
style="width: 140px;" autocomplete="off"> &nbsp; &nbsp;
关键字:
<input type="text" class="form-control" name="keyword" style="width: 200px;"
value="{$keyword|default=''}" placeholder="请输入品牌中介名称">
<input type="submit" class="btn btn-primary" value="搜索"/>
<a class="btn btn-danger" href="{:url('Reward/index')}">清空</a>
</form>
<form class="js-ajax-form" action="" method="post">
<div class="table-actions">
<!--<notempty name="category">-->
<!--<button class="btn btn-primary btn-sm js-ajax-submit" type="submit"-->
<!--data-action="{:url('AdminArticle/listOrder')}">{:lang('SORT')}-->
<!--</button>-->
<!--</notempty>-->
<!--<button class="btn btn-primary btn-sm js-ajax-submit" type="submit"-->
<!--data-action="{:url('AdminArticle/publish',array('yes'=>1))}" data-subcheck="true">发布-->
<!--</button>-->
<!--<button class="btn btn-primary btn-sm js-ajax-submit" type="submit"-->
<!--data-action="{:url('AdminArticle/publish',array('no'=>1))}" data-subcheck="true">取消发布-->
<!--</button>-->
<!--<button class="btn btn-primary btn-sm js-ajax-submit" type="submit"-->
<!--data-action="{:url('AdminArticle/top',array('yes'=>1))}" data-subcheck="true">置顶-->
<!--</button>-->
<!--<button class="btn btn-primary btn-sm js-ajax-submit" type="submit"-->
<!--data-action="{:url('AdminArticle/top',array('no'=>1))}" data-subcheck="true">取消置顶-->
<!--</button>-->
<!--<button class="btn btn-primary btn-sm js-ajax-submit" type="submit"-->
<!--data-action="{:url('AdminArticle/recommend',array('yes'=>1))}" data-subcheck="true">推荐-->
<!--</button>-->
<!--<button class="btn btn-primary btn-sm js-ajax-submit" type="submit"-->
<!--data-action="{:url('AdminArticle/recommend',array('no'=>1))}" data-subcheck="true">取消推荐-->
<!--</button>-->
<!--
<notempty name="category">
<button class="btn btn-primary btn-sm js-articles-move" type="button">批量移动</button>
</notempty>
<button class="btn btn-primary btn-sm js-articles-copy" type="button">批量复制</button>
-->
<button class="btn btn-danger btn-sm js-ajax-submit" type="submit"
data-action="{:url('Reward/del')}" data-subcheck="true" data-msg="您确定删除吗?">
{:lang('DELETE')}
</button>
</div>
<table class="table table-hover table-bordered table-list">
<thead>
<tr>
<th width="15">
<label>
<input type="checkbox" class="js-check-all" data-direction="x" data-checklist="js-check-x">
</label>
</th>
<notempty name="category">
<th width="50">{:lang('SORT')}</th>
</notempty>
<th width="50">ID</th>
<th>类型</th>
<th>金额</th>
<!--<th>排序</th>-->
<th width="130">更新时间</th>
<th width="130">发布时间</th>
<!--<th width="70">状态</th>-->
<th width="90">操作</th>
</tr>
</thead>
<foreach name="list" item="list">
<tr>
<td>
<input type="checkbox" class="js-check" data-yid="js-check-y" data-xid="js-check-x" name="ids[]"
value="{$list.id}" title="ID:{$list.id}">
</td>
<td>{$list.id}</td>
<td>
{$list.type}
</td>
<td>
{$list.number}
</td>
<td>
{:date('Y-m-d H:i',$list['update_time'])}
</td>
<td>
{:date('Y-m-d H:i',$list['create_time'])}
<!--<empty name="vo.published_time">-->
<!--未发布-->
<!--<else/>-->
<!--{:date('Y-m-d H:i',$list['published_time'])}-->
<!--</empty>-->
</td>
<td>
<a href="{:url('Reward/add',array('id'=>$list['id']))}">{:lang('EDIT')}</a>
<a href="{:url('Reward/del',array('id'=>$list['id']))}" class="js-ajax-delete">{:lang('DELETE')}</a>
</td>
</tr>
</foreach>
</table>
<ul class="pagination">{$page|default=''}</ul>
</form>
</div>
<script src="__STATIC__/js/admin.js"></script>
<script>
function reloadPage(win) {
win.location.reload();
}
$(function () {
setCookie("refersh_time", 0);
Wind.use('ajaxForm', 'artDialog', 'iframeTools', function () {
//批量复制
$('.js-articles-copy').click(function (e) {
var ids = [];
$("input[name='ids[]']").each(function () {
if ($(this).is(':checked')) {
ids.push($(this).val());
}
});
if (ids.length == 0) {
art.dialog.through({
id: 'error',
icon: 'error',
content: '您没有勾选信息,无法进行操作!',
cancelVal: '关闭',
cancel: true
});
return false;
}
ids = ids.join(',');
art.dialog.open("__ROOT__/index.php?g=portal&m=AdminArticle&a=copy&ids=" + ids, {
title: "批量复制",
width: "300px"
});
});
//批量移动
$('.js-articles-move').click(function (e) {
var ids = [];
$("input[name='ids[]']").each(function () {
if ($(this).is(':checked')) {
ids.push($(this).val());
}
});
if (ids.length == 0) {
art.dialog.through({
id: 'error',
icon: 'error',
content: '您没有勾选信息,无法进行操作!',
cancelVal: '关闭',
cancel: true
});
return false;
}
ids = ids.join(',');
art.dialog.open("__ROOT__/index.php?g=portal&m=AdminArticle&a=move&old_term_id={$term.term_id|default=0}&ids=" + ids, {
title: "批量移动",
width: "300px"
});
});
});
});
</script>
</body>
</html>
\ No newline at end of file
... ...
<include file="public@header"/>
<style type="text/css">
.pic-list li {
margin-bottom: 5px;
}
</style>
</head>
<body>
<div class="wrap js-check-wrap">
<ul class="nav nav-tabs">
<li><a href="{:url('Bank/index')}">银行列表</a></li>
<li class="active"><a href="{:url('Bank/add')}">添加银行</a></li>
</ul>
<form action="{:url('Bank/add')}" method="post" class="form-horizontal js-ajax-form margin-top-20" enctype="multipart/form-data" >
<div class="row">
<div class="col-md-9">
<table class="table table-bordered">
<input class="form-control" type="hidden" name="id"
value="{$list['id']}"/>
<tr>
<th width="15%">银行名称</th>
<td><input class="form-control" type="text" name="name11"
value="{$list['name']}" placeholder="请输入银行名称"/>
</td>
</tr>
<tr>
<th width="10%">排序</th>
<td><input class="form-control" type="text" name="score"
value="{$list['score']}" placeholder="请输入排序,数字越大越靠前"/>
</td>
</tr>
</table>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-primary js-ajax-submit">{:lang('ADD')}</button>
<a class="btn btn-default" href="{:url('Bank/index')}">{:lang('BACK')}</a>
</div>
</div>
</div>
</div>
</form>
</div>
<script type="text/javascript" src="__STATIC__/js/admin.js"></script>
<script type="text/javascript">
//编辑器路径定义
var editorURL = GV.WEB_ROOT;
</script>
<script type="text/javascript" src="__STATIC__/js/ueditor/ueditor.config.js"></script>
<script type="text/javascript" src="__STATIC__/js/ueditor/ueditor.all.min.js"></script>
<script type="text/javascript">
$(function () {
editorcontent = new baidu.editor.ui.Editor();
editorcontent.render('content');
try {
editorcontent.sync();
} catch (err) {
}
$('.btn-cancel-thumbnail').click(function () {
$('#thumbnail-preview').attr('src', '__TMPL__/public/assets/images/default-thumbnail.png');
$('#thumbnail').val('');
});
});
</script>
</body>
</html>
... ...
<include file="public@header"/>
</head>
<body>
<div class="wrap js-check-wrap">
<ul class="nav nav-tabs">
<li class="active"><a href="javascript:;">银行列表</a></li>
<li><a href="{:url('Bank/add')}">添加银行</a></li>
</ul>
<form class="well form-inline margin-top-20" method="post" action="{:url('Bank/index')}">
<!--分类:-->
<!--<select class="form-control" name="category" style="width: 140px;">-->
<!--<option value='0'>全部</option>-->
<!--{$category_tree|default=''}-->
<!--</select> &nbsp;&nbsp;-->
时间:
<input type="text" class="form-control js-bootstrap-datetime" name="start_time"
value="{$start_time|default=''}"
style="width: 140px;" autocomplete="off">-
<input type="text" class="form-control js-bootstrap-datetime" name="end_time"
value="{$end_time|default=''}"
style="width: 140px;" autocomplete="off"> &nbsp; &nbsp;
关键字:
<input type="text" class="form-control" name="keyword" style="width: 200px;"
value="{$keyword|default=''}" placeholder="请输入品牌中介名称">
<input type="submit" class="btn btn-primary" value="搜索"/>
<a class="btn btn-danger" href="{:url('Bank/index')}">清空</a>
</form>
<form class="js-ajax-form" action="" method="post">
<div class="table-actions">
<!--<notempty name="category">-->
<!--<button class="btn btn-primary btn-sm js-ajax-submit" type="submit"-->
<!--data-action="{:url('AdminArticle/listOrder')}">{:lang('SORT')}-->
<!--</button>-->
<!--</notempty>-->
<!--<button class="btn btn-primary btn-sm js-ajax-submit" type="submit"-->
<!--data-action="{:url('AdminArticle/publish',array('yes'=>1))}" data-subcheck="true">发布-->
<!--</button>-->
<!--<button class="btn btn-primary btn-sm js-ajax-submit" type="submit"-->
<!--data-action="{:url('AdminArticle/publish',array('no'=>1))}" data-subcheck="true">取消发布-->
<!--</button>-->
<!--<button class="btn btn-primary btn-sm js-ajax-submit" type="submit"-->
<!--data-action="{:url('AdminArticle/top',array('yes'=>1))}" data-subcheck="true">置顶-->
<!--</button>-->
<!--<button class="btn btn-primary btn-sm js-ajax-submit" type="submit"-->
<!--data-action="{:url('AdminArticle/top',array('no'=>1))}" data-subcheck="true">取消置顶-->
<!--</button>-->
<!--<button class="btn btn-primary btn-sm js-ajax-submit" type="submit"-->
<!--data-action="{:url('AdminArticle/recommend',array('yes'=>1))}" data-subcheck="true">推荐-->
<!--</button>-->
<!--<button class="btn btn-primary btn-sm js-ajax-submit" type="submit"-->
<!--data-action="{:url('AdminArticle/recommend',array('no'=>1))}" data-subcheck="true">取消推荐-->
<!--</button>-->
<!--
<notempty name="category">
<button class="btn btn-primary btn-sm js-articles-move" type="button">批量移动</button>
</notempty>
<button class="btn btn-primary btn-sm js-articles-copy" type="button">批量复制</button>
-->
<button class="btn btn-danger btn-sm js-ajax-submit" type="submit"
data-action="{:url('Bank/del')}" data-subcheck="true" data-msg="您确定删除吗?">
{:lang('DELETE')}
</button>
</div>
<table class="table table-hover table-bordered table-list">
<thead>
<tr>
<th width="15">
<label>
<input type="checkbox" class="js-check-all" data-direction="x" data-checklist="js-check-x">
</label>
</th>
<notempty name="category">
<th width="50">{:lang('SORT')}</th>
</notempty>
<th width="50">ID</th>
<th>品牌中介名</th>
<th>排序</th>
<!--<th>排序</th>-->
<th width="130">更新时间</th>
<th width="130">发布时间</th>
<!--<th width="70">状态</th>-->
<th width="90">操作</th>
</tr>
</thead>
<foreach name="list" item="list">
<tr>
<td>
<input type="checkbox" class="js-check" data-yid="js-check-y" data-xid="js-check-x" name="ids[]"
value="{$list.id}" title="ID:{$list.id}">
</td>
<td>{$list.id}</td>
<td>
{$list.name}
</td>
<td>
{$list.score}
</td>
<td>
{:date('Y-m-d H:i',$list['update_time'])}
</td>
<td>
{:date('Y-m-d H:i',$list['create_time'])}
<!--<empty name="vo.published_time">-->
<!--未发布-->
<!--<else/>-->
<!--{:date('Y-m-d H:i',$list['published_time'])}-->
<!--</empty>-->
</td>
<td>
<a href="{:url('Bank/add',array('id'=>$list['id']))}">{:lang('EDIT')}</a>
<a href="{:url('Bank/del',array('id'=>$list['id']))}" class="js-ajax-delete">{:lang('DELETE')}</a>
</td>
</tr>
</foreach>
</table>
<ul class="pagination">{$page|default=''}</ul>
</form>
</div>
<script src="__STATIC__/js/admin.js"></script>
<script>
function reloadPage(win) {
win.location.reload();
}
$(function () {
setCookie("refersh_time", 0);
Wind.use('ajaxForm', 'artDialog', 'iframeTools', function () {
//批量复制
$('.js-articles-copy').click(function (e) {
var ids = [];
$("input[name='ids[]']").each(function () {
if ($(this).is(':checked')) {
ids.push($(this).val());
}
});
if (ids.length == 0) {
art.dialog.through({
id: 'error',
icon: 'error',
content: '您没有勾选信息,无法进行操作!',
cancelVal: '关闭',
cancel: true
});
return false;
}
ids = ids.join(',');
art.dialog.open("__ROOT__/index.php?g=portal&m=AdminArticle&a=copy&ids=" + ids, {
title: "批量复制",
width: "300px"
});
});
//批量移动
$('.js-articles-move').click(function (e) {
var ids = [];
$("input[name='ids[]']").each(function () {
if ($(this).is(':checked')) {
ids.push($(this).val());
}
});
if (ids.length == 0) {
art.dialog.through({
id: 'error',
icon: 'error',
content: '您没有勾选信息,无法进行操作!',
cancelVal: '关闭',
cancel: true
});
return false;
}
ids = ids.join(',');
art.dialog.open("__ROOT__/index.php?g=portal&m=AdminArticle&a=move&old_term_id={$term.term_id|default=0}&ids=" + ids, {
title: "批量移动",
width: "300px"
});
});
});
});
</script>
</body>
</html>
\ No newline at end of file
... ...
... ... @@ -71,6 +71,56 @@ class HomeBaseController extends BaseController
}
/**
* 生成二维码
* $param url 地址
*/
public function createQRcode($url) {
require VENDOR_PATH.'WxpayAPI/example/phpqrcode/phpqrcode.php';
$QRcode = new \QRcode();
$errorCorrectionLevel = 'L'; //容错级别
$matrixPointSize = 5; //生成图片大小
//生成二维码图片
$data = './upload/';
$flodername = 'qrcode/' . date("Ymd", time());
$png = uniqid() . '.png';
$filename = $data.$flodername . '/' . $png;
if (!file_exists($data.$flodername)) {
mkdir($data.$flodername, 0777, true);
}
$QRcode->png($url, $filename, $errorCorrectionLevel, $matrixPointSize);
return $flodername . '/' . $png;
}
/**
* 微信支付(pc扫码支付)
*/
protected function wxpay($orderInfo,$sort) {
require_once VENDOR_PATH."WxpayAPI/lib/WxPay.Api.php";
require_once VENDOR_PATH."WxpayAPI/example/WxPay.JsApiPay.php";
require_once VENDOR_PATH."WxpayAPI/example/WxPay.NativePay.php";
require_once VENDOR_PATH."WxpayAPI/lib/WxPay.Notify.php";
require_once VENDOR_PATH.'WxpayAPI/example/log.php';
$notify = new \NativePay();
$input = new \WxPayUnifiedOrder();
$input->SetBody($sort);
$input->SetAttach($orderInfo['order_sn']);
$input->SetOut_trade_no(\WxPayConfig::MCHID.date("YmdHis"));
$input->SetTotal_fee($orderInfo['price']*100);//$orderInfo['price_count']*100
$input->SetTime_start(date("YmdHis"));
$input->SetTime_expire(date("YmdHis", time() + 600));
$input->SetGoods_tag("test");
// $input->SetNotify_url('http://ccimc.com/simplewind/Core/Library/Vendor/WxpayAPI/example/notify.php');
$input->SetNotify_url(url('portal/notify/notify','',true,true));
$input->SetTrade_type("NATIVE");
$input->SetProduct_id('');
$result = $notify->GetPayUrl($input);
return $result;
}
/**
* 加载模板输出
* @access protected
* @param string $template 模板文件名
... ...
-----BEGIN CERTIFICATE-----
MIIEYzCCA8ygAwIBAgIEAQgxjjANBgkqhkiG9w0BAQUFADCBijELMAkGA1UEBhMC
Q04xEjAQBgNVBAgTCUd1YW5nZG9uZzERMA8GA1UEBxMIU2hlbnpoZW4xEDAOBgNV
BAoTB1RlbmNlbnQxDDAKBgNVBAsTA1dYRzETMBEGA1UEAxMKTW1wYXltY2hDQTEf
MB0GCSqGSIb3DQEJARYQbW1wYXltY2hAdGVuY2VudDAeFw0xNzA1MTUxNDQwMDRa
Fw0yNzA1MTMxNDQwMDRaMIGSMQswCQYDVQQGEwJDTjESMBAGA1UECBMJR3Vhbmdk
b25nMREwDwYDVQQHEwhTaGVuemhlbjEQMA4GA1UEChMHVGVuY2VudDEOMAwGA1UE
CxMFTU1QYXkxJzAlBgNVBAMUHuWkqea0peaWueebruenkeaKgOaciemZkOWFrOWP
uDERMA8GA1UEBBMIMjY5NzcwNTMwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK
AoIBAQC90K1g8cq3GvkERn22Sw02x68qCpD+q5owh5fcEdjTL6zwtAC80Jx8Yd0G
3DBpeCkefHEmq73pPQRt3pXD+AGT/ffsSFQtDU8p/CC0eqzfU5PM14z1xZjdrMiM
xQZSqwg6WRIQjdYp1ypTlgx+3IP2cVqa6v1t7MfRpZ1SeqMYdAIFGELwGxwxJjFe
ArCodzDzvYs/t6KKyb4VjhvmNIxwG+GwK1OZHy+Y5PVBeGQdJGXMzNSM5O4Ur2bc
qLN3K5VTLRHFqJNohd1dTDOcAyZfYOtcp2b/rQ2d+jrGu9CrHdh79I3/Srdmjq9L
iqgV9gOQNKu0Q91VVZd8YvVjqMpVAgMBAAGjggFGMIIBQjAJBgNVHRMEAjAAMCwG
CWCGSAGG+EIBDQQfFh0iQ0VTLUNBIEdlbmVyYXRlIENlcnRpZmljYXRlIjAdBgNV
HQ4EFgQU5jvXZ+kAyNtyc7hfuQsgPlfaXikwgb8GA1UdIwSBtzCBtIAUPgUm9iJi
tBVbiM1kfrDUYqflhnShgZCkgY0wgYoxCzAJBgNVBAYTAkNOMRIwEAYDVQQIEwlH
dWFuZ2RvbmcxETAPBgNVBAcTCFNoZW56aGVuMRAwDgYDVQQKEwdUZW5jZW50MQww
CgYDVQQLEwNXWEcxEzARBgNVBAMTCk1tcGF5bWNoQ0ExHzAdBgkqhkiG9w0BCQEW
EG1tcGF5bWNoQHRlbmNlbnSCCQC7VJcrvADoVzAOBgNVHQ8BAf8EBAMCBsAwFgYD
VR0lAQH/BAwwCgYIKwYBBQUHAwIwDQYJKoZIhvcNAQEFBQADgYEARNKry3veIem6
7sK620ApJdWYkuHeJcmT8AKN/LbV/bLPe6CY+fgtd0wSSaR3b1CUuDPQFEoPQS2p
S3tNHpqZmB5rkHUfMxBMib6+tCLvsxyKmHXWiaZOFiumwwuLn2OAjKkm5DkBD3sV
CHtQu3Kqt6NID7/Y1By1dccOgZGuNIE=
-----END CERTIFICATE-----
... ...
-----BEGIN PRIVATE KEY-----
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQC90K1g8cq3GvkE
Rn22Sw02x68qCpD+q5owh5fcEdjTL6zwtAC80Jx8Yd0G3DBpeCkefHEmq73pPQRt
3pXD+AGT/ffsSFQtDU8p/CC0eqzfU5PM14z1xZjdrMiMxQZSqwg6WRIQjdYp1ypT
lgx+3IP2cVqa6v1t7MfRpZ1SeqMYdAIFGELwGxwxJjFeArCodzDzvYs/t6KKyb4V
jhvmNIxwG+GwK1OZHy+Y5PVBeGQdJGXMzNSM5O4Ur2bcqLN3K5VTLRHFqJNohd1d
TDOcAyZfYOtcp2b/rQ2d+jrGu9CrHdh79I3/Srdmjq9LiqgV9gOQNKu0Q91VVZd8
YvVjqMpVAgMBAAECggEAMm+ugiH9YWYTYOVyJewPWMz6aEtid6kVUWvWGC3N1V/H
rjXGNGWiDxLZ7ia33m6FTop2bnYYAk+qS59nYCkYEkDbjbcyVr5AmMFb11j5cmX8
0eM8m1mj4tM0fuMjaPf1ObvNJwTpMTjxEEDAlTz2+5bnIl7qdDkEZ1qAURgxGh/T
oqtji7+8trEUeXzi8mRk2s++kDEe1cMN8hHqGwecJGAA8dg3WWilNSSGV9Y42mZX
YSBsMkwWpgK/yIrSkhR3D4rCB0BTajtCvEL37vNYhtYAbNxKZ638YnbJAlz+/Bv0
yRI8WTfrzE1Aviom/+RGDkBQW7loVObUux8Kq89qQQKBgQDuGEYdIfxdtis+b2ZK
bTC0TUsf0gPC7icgilLhGzIGEWxZzopybENBOle2UuORkuDffpWjjtheD+D8+N/R
sC4H4UoqzSy6Y6MiJH2L0zA7odWvmZsdNei9pup8fQZnwxCGxfObmd3Dm+Sv7fVD
gU6eZ+aapLpS8+Oaxq7vxLq8rQKBgQDMFvA47cvTHTEthWvZ0ejakhebcTxILjRO
Bnws30WSoWzbnpNd34DlBdJRXIj+Kbh80Q5GNbPBeIo7+Y/5MnezFC+eDfEXdb+k
Fv/t/yswNrrJaAKRLP3ZtIInHgSKBp2rBJvQU+X0WNW7VrhGiBSnAmabqM+4rwTi
EpYYGheRSQKBgH6jdpeEPiDyBeo9gmDP1vnvqqeQIuQJm9IZAKAuwNqtZb4Wt1jI
8LS+/WxChjwlrWnygFDwZ3EQbRDgptt3I+SZFcPSQZoZ6Oj+E7DNcXgmSewOfYx5
4gMNxubT8RY7kIy+uSXoHyYtwuM4ZB21p0Vl6igSue/pPQRT7TQmpVQ5AoGATUhu
ZRBfO611PuikI5KiW4ow2FLz4d1lPxqjkRZnMRRhtXSCF20YUSF4OAkTczN3QgSk
JCAX1q5/oiBpzZK30x9UvMRIxHp5PHjdJ1GWGCbRao0xU6o24mbBVnC+hUnmEKmp
GyV6EaJGJS+8jjDfqTJ2ioFNT4EvFzC0l6HhxMkCgYAJml7eXlmPc8pcL30kP3Vf
UF6lvCOH5ioPMj8IX0fuUjMU3S9mvGjKJIR3R+J8U821KSyiQKl26tJmVfjW1/KI
nY5J6ucwM26/y46M97JhW9+m8j+BPvdSai1SxQm0Jne5/1ZDp2QLMWiqsnE0VPWm
IQjv5v1VQVYZgFnLR7h3Qw==
-----END PRIVATE KEY-----
... ...
SDK
体验地址
http://paysdk.weixin.qq.com/
快速搭建指南
①、安装配置nginx+phpfpm+php
②、建SDK解压到网站根目录
③、修改lib/WxPay.Config.php为自己申请的商户号的信息(配置详见说明)
⑤、下载证书替换cert下的文件
⑥、搭建完成
SDK目录结构
|-- cert
| |-- apiclient_cert.pem
| `-- apiclient_key.pem
|-- index.php
|-- lib
| |-- WxPay.Api.php
| |-- WxPay.Config.php
| |-- WxPay.Data.php
| |-- WxPay.Exception.php
| `-- WxPay.Notify.php
|-- logs
| |-- 2015-03-06.log
| `-- 2015-03-11.log
`-- example
|-- WxPay.JsApiPay.php
|-- WxPay.MicroPay.php
|-- WxPay.NativePay.php
|-- download.php
|-- micropay.php
|-- native.php
|-- native_notify.php
|-- notify.php
|-- orderquery.php
|-- qrcode.php
|-- refund.php
|-- refundquery.php
|-- jsapi.php
|-- log.php
`-- phpqrcode
目录功能简介
lib
API接口封装代码
WxPay.Api.php 包括所有微信支付API接口的封装
WxPay.Config.php 商户配置
WxPay.Data.php 输入参数封装
WxPay.Exception.php 异常类
WxPay.Notify.php 回调通知基类
cert
证书存放路径,证书可以登录商户平台https://pay.weixin.qq.com/index.php/account/api_cert下载
example
样例程序代码路径
example/phpqrcode
开源二维码php代码
logs
日志文件
※配置指南
MCHID = '1225312702';
这里填开户邮件中的商户号
APPID = 'wx426b3015555a46be';
这里填开户邮件中的(公众账号APPID或者应用APPID)
KEY = 'e10adc3949ba59abbe56e057f20f883e'
这里请使用商户平台登录账户和密码登录http://pay.weixin.qq.com 平台设置的“API密钥”,为了安全,请设置为32字符串。
APPSECRET = '01c6d59a3f9024db6336662ac95c8e74'
改参数在JSAPI支付(open平台账户不能进行JSAPI支付)的时候需要用来获取用户openid,可使用APPID对应的公众平台登录http://mp.weixin.qq.com 的开发者中心获取AppSecret。
... ...
<?php
require_once VENDOR_PATH."WxpayAPI/lib/WxPay.Api.php";
/**
*
* JSAPI支付实现类
* 该类实现了从微信公众平台获取code、通过code获取openid和access_token、
* 生成jsapi支付js接口所需的参数、生成获取共享收货地址所需的参数
*
* 该类是微信支付提供的样例程序,商户可根据自己的需求修改,或者使用lib中的api自行开发
*
* @author widy
*
*/
class JsApiPay
{
/**
*
* 网页授权接口微信服务器返回的数据,返回样例如下
* {
* "access_token":"ACCESS_TOKEN",
* "expires_in":7200,
* "refresh_token":"REFRESH_TOKEN",
* "openid":"OPENID",
* "scope":"SCOPE",
* "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
* }
* 其中access_token可用于获取共享收货地址
* openid是微信支付jsapi支付接口必须的参数
* @var array
*/
public $data = null;
/**
*
* 通过跳转获取用户的openid,跳转流程如下:
* 1、设置自己需要调回的url及其其他参数,跳转到微信服务器https://open.weixin.qq.com/connect/oauth2/authorize
* 2、微信服务处理完成之后会跳转回用户redirect_uri地址,此时会带上一些参数,如:code
*
* @return 用户的openid
*/
public function GetOpenid()
{
//通过code获得openid
if (!isset($_GET['code'])){
//触发微信返回code码
$baseUrl = urlencode('http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
$url = $this->__CreateOauthUrlForCode($baseUrl);
Header("Location: $url");
exit();
} else {
//获取code码,以获取openid
$code = $_GET['code'];
$openid = $this->getOpenidFromMp($code);
return $openid;
}
}
/**
*
* 获取jsapi支付的参数
* @param array $UnifiedOrderResult 统一支付接口返回的数据
* @throws WxPayException
*
* @return json数据,可直接填入js函数作为参数
*/
public function GetJsApiParameters($UnifiedOrderResult)
{
if(!array_key_exists("appid", $UnifiedOrderResult)
|| !array_key_exists("prepay_id", $UnifiedOrderResult)
|| $UnifiedOrderResult['prepay_id'] == "")
{
throw new WxPayException("参数错误");
}
$jsapi = new WxPayJsApiPay();
$jsapi->SetAppid($UnifiedOrderResult["appid"]);
$timeStamp = time();
$jsapi->SetTimeStamp("$timeStamp");
$jsapi->SetNonceStr(WxPayApi::getNonceStr());
$jsapi->SetPackage("prepay_id=" . $UnifiedOrderResult['prepay_id']);
$jsapi->SetSignType("MD5");
$jsapi->SetPaySign($jsapi->MakeSign());
$parameters = json_encode($jsapi->GetValues());
return $parameters;
}
/**
*
* 通过code从工作平台获取openid机器access_token
* @param string $code 微信跳转回来带上的code
*
* @return openid
*/
public function GetOpenidFromMp($code)
{
$url = $this->__CreateOauthUrlForOpenid($code);
//初始化curl
$ch = curl_init();
//设置超时
curl_setopt($ch, CURLOPT_TIMEOUT, $this->curl_timeout);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,FALSE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
if(WxPayConfig::CURL_PROXY_HOST != "0.0.0.0"
&& WxPayConfig::CURL_PROXY_PORT != 0){
curl_setopt($ch,CURLOPT_PROXY, WxPayConfig::CURL_PROXY_HOST);
curl_setopt($ch,CURLOPT_PROXYPORT, WxPayConfig::CURL_PROXY_PORT);
}
//运行curl,结果以jason形式返回
$res = curl_exec($ch);
curl_close($ch);
//取出openid
$data = json_decode($res,true);
$this->data = $data;
$openid = $data['openid'];
return $openid;
}
/**
*
* 拼接签名字符串
* @param array $urlObj
*
* @return 返回已经拼接好的字符串
*/
private function ToUrlParams($urlObj)
{
$buff = "";
foreach ($urlObj as $k => $v)
{
if($k != "sign"){
$buff .= $k . "=" . $v . "&";
}
}
$buff = trim($buff, "&");
return $buff;
}
/**
*
* 获取地址js参数
*
* @return 获取共享收货地址js函数需要的参数,json格式可以直接做参数使用
*/
public function GetEditAddressParameters()
{
$getData = $this->data;
$data = array();
$data["appid"] = WxPayConfig::APPID;
$data["url"] = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
$time = time();
$data["timestamp"] = "$time";
$data["noncestr"] = "1234568";
$data["accesstoken"] = $getData["access_token"];
ksort($data);
$params = $this->ToUrlParams($data);
$addrSign = sha1($params);
$afterData = array(
"addrSign" => $addrSign,
"signType" => "sha1",
"scope" => "jsapi_address",
"appId" => WxPayConfig::APPID,
"timeStamp" => $data["timestamp"],
"nonceStr" => $data["noncestr"]
);
$parameters = json_encode($afterData);
return $parameters;
}
/**
*
* 构造获取code的url连接
* @param string $redirectUrl 微信服务器回跳的url,需要url编码
*
* @return 返回构造好的url
*/
private function __CreateOauthUrlForCode($redirectUrl)
{
$urlObj["appid"] = WxPayConfig::APPID;
$urlObj["redirect_uri"] = "$redirectUrl";
$urlObj["response_type"] = "code";
$urlObj["scope"] = "snsapi_base";
$urlObj["state"] = "STATE"."#wechat_redirect";
$bizString = $this->ToUrlParams($urlObj);
return "https://open.weixin.qq.com/connect/oauth2/authorize?".$bizString;
}
/**
*
* 构造获取open和access_toke的url地址
* @param string $code,微信跳转带回的code
*
* @return 请求的url
*/
private function __CreateOauthUrlForOpenid($code)
{
$urlObj["appid"] = WxPayConfig::APPID;
$urlObj["secret"] = WxPayConfig::APPSECRET;
$urlObj["code"] = $code;
$urlObj["grant_type"] = "authorization_code";
$bizString = $this->ToUrlParams($urlObj);
return "https://api.weixin.qq.com/sns/oauth2/access_token?".$bizString;
}
}
\ No newline at end of file
... ...
<?php
require_once "../lib/WxPay.Api.php";
/**
*
* 刷卡支付实现类
* 该类实现了一个刷卡支付的流程,流程如下:
* 1、提交刷卡支付
* 2、根据返回结果决定是否需要查询订单,如果查询之后订单还未变则需要返回查询(一般反复查10次)
* 3、如果反复查询10订单依然不变,则发起撤销订单
* 4、撤销订单需要循环撤销,一直撤销成功为止(注意循环次数,建议10次)
*
* 该类是微信支付提供的样例程序,商户可根据自己的需求修改,或者使用lib中的api自行开发,为了防止
* 查询时hold住后台php进程,商户查询和撤销逻辑可在前端调用
*
* @author widy
*
*/
class MicroPay
{
/**
*
* 提交刷卡支付,并且确认结果,接口比较慢
* @param WxPayMicroPay $microPayInput
* @throws WxpayException
* @return 返回查询接口的结果
*/
public function pay($microPayInput)
{
//①、提交被扫支付
$result = WxPayApi::micropay($microPayInput, 5);
//如果返回成功
if(!array_key_exists("return_code", $result)
|| !array_key_exists("out_trade_no", $result)
|| !array_key_exists("result_code", $result))
{
echo "接口调用失败,请确认是否输入是否有误!";
throw new WxPayException("接口调用失败!");
}
//签名验证
$out_trade_no = $microPayInput->GetOut_trade_no();
//②、接口调用成功,明确返回调用失败
if($result["return_code"] == "SUCCESS" &&
$result["result_code"] == "FAIL" &&
$result["err_code"] != "USERPAYING" &&
$result["err_code"] != "SYSTEMERROR")
{
return false;
}
//③、确认支付是否成功
$queryTimes = 10;
while($queryTimes > 0)
{
$succResult = 0;
$queryResult = $this->query($out_trade_no, $succResult);
//如果需要等待1s后继续
if($succResult == 2){
sleep(2);
continue;
} else if($succResult == 1){//查询成功
return $queryResult;
} else {//订单交易失败
return false;
}
}
//④、次确认失败,则撤销订单
if(!$this->cancel($out_trade_no))
{
throw new WxpayException("撤销单失败!");
}
return false;
}
/**
*
* 查询订单情况
* @param string $out_trade_no 商户订单号
* @param int $succCode 查询订单结果
* @return 0 订单不成功,1表示订单成功,2表示继续等待
*/
public function query($out_trade_no, &$succCode)
{
$queryOrderInput = new WxPayOrderQuery();
$queryOrderInput->SetOut_trade_no($out_trade_no);
$result = WxPayApi::orderQuery($queryOrderInput);
if($result["return_code"] == "SUCCESS"
&& $result["result_code"] == "SUCCESS")
{
//支付成功
if($result["trade_state"] == "SUCCESS"){
$succCode = 1;
return $result;
}
//用户支付中
else if($result["trade_state"] == "USERPAYING"){
$succCode = 2;
return false;
}
}
//如果返回错误码为“此交易订单号不存在”则直接认定失败
if($result["err_code"] == "ORDERNOTEXIST")
{
$succCode = 0;
} else{
//如果是系统错误,则后续继续
$succCode = 2;
}
return false;
}
/**
*
* 撤销订单,如果失败会重复调用10次
* @param string $out_trade_no
* @param 调用深度 $depth
*/
public function cancel($out_trade_no, $depth = 0)
{
if($depth > 10){
return false;
}
$clostOrder = new WxPayReverse();
$clostOrder->SetOut_trade_no($out_trade_no);
$result = WxPayApi::reverse($clostOrder);
//接口调用失败
if($result["return_code"] != "SUCCESS"){
return false;
}
//如果结果为success且不需要重新调用撤销,则表示撤销成功
if($result["result_code"] != "SUCCESS"
&& $result["recall"] == "N"){
return true;
} else if($result["recall"] == "Y") {
return $this->cancel($out_trade_no, ++$depth);
}
return false;
}
}
\ No newline at end of file
... ...
<?php
//require_once "../lib/WxPay.Api.php";
/**
*
* 刷卡支付实现类
* @author widyhu
*
*/
class NativePay
{
/**
*
* 生成扫描支付URL,模式一
* @param BizPayUrlInput $bizUrlInfo
*/
public function GetPrePayUrl($productId)
{
$biz = new WxPayBizPayUrl();
$biz->SetProduct_id($productId);
$values = WxpayApi::bizpayurl($biz);
$url = "weixin://wxpay/bizpayurl?" . $this->ToUrlParams($values);
return $url;
}
/**
*
* 参数数组转换为url参数
* @param array $urlObj
*/
private function ToUrlParams($urlObj)
{
$buff = "";
foreach ($urlObj as $k => $v)
{
$buff .= $k . "=" . $v . "&";
}
$buff = trim($buff, "&");
return $buff;
}
/**
*
* 生成直接支付url,支付url有效期为2小时,模式二
* @param UnifiedOrderInput $input
*/
public function GetPayUrl($input)
{
if($input->GetTrade_type() == "NATIVE")
{
$result = WxPayApi::unifiedOrder($input);
return $result;
}
}
}
\ No newline at end of file
... ...
<?php
require_once "../lib/WxPay.Api.php";
//require_once "../lib/WxPay.MicroPay.php";
if(isset($_REQUEST["bill_date"]) && $_REQUEST["bill_date"] != ""){
$bill_date = $_REQUEST["bill_date"];
$bill_type = $_REQUEST["bill_type"];
$input = new WxPayDownloadBill();
$input->SetBill_date($bill_date);
$input->SetBill_type($bill_type);
$file = WxPayApi::downloadBill($input);
echo $file;
//TODO 对账单文件处理
exit(0);
}
?>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>微信支付样例-查退款单</title>
</head>
<body>
<form action="#" method="post">
<div style="margin-left:2%;">对账日期:</div><br/>
<input type="text" style="width:96%;height:35px;margin-left:2%;" name="bill_date" /><br /><br />
<div style="margin-left:2%;">账单类型:</div><br/>
<select style="width:96%;height:35px;margin-left:2%;" name="bill_type">
<option value ="ALL">所有订单信息</option>
<option value ="SUCCESS">成功支付的订单</option>
<option value="REFUND">退款订单</option>
<option value="REVOKED">撤销的订单</option>
</select><br /><br />
<div align="center">
<input type="submit" value="下载订单" style="width:210px; height:50px; border-radius: 15px;background-color:#FE6714; border:0px #FE6714 solid; cursor: pointer; color:white; font-size:16px;" type="button" onclick="callpay()" />
</div>
</form>
</body>
</html>
\ No newline at end of file
... ...
<?php
ini_set('date.timezone','Asia/Shanghai');
//error_reporting(E_ERROR);
require_once "../lib/WxPay.Api.php";
//require_once "WxPay.JsApiPay.php";
require_once 'log.php';
//echo 111;exit;
//初始化日志
$logHandler= new CLogFileHandler("../logs/".date('Y-m-d').'.log');
$log = Log::Init($logHandler, 15);
//打印输出数组信息
function printf_info($data)
{
foreach($data as $key=>$value){
echo "<font color='#00ff55;'>$key</font> : $value <br/>";
}
}
//①、获取用户openid
$tools = new JsApiPay();
$openId = $tools->GetOpenid();
//②、统一下单
$input = new WxPayUnifiedOrder();
$input->SetBody("test");
$input->SetAttach("test");
$input->SetOut_trade_no(WxPayConfig::MCHID.date("YmdHis"));
$input->SetTotal_fee("1");
$input->SetTime_start(date("YmdHis"));
$input->SetTime_expire(date("YmdHis", time() + 600));
$input->SetGoods_tag("test");
$input->SetNotify_url("http://paysdk.weixin.qq.com/example/notify.php");
$input->SetTrade_type("JSAPI");
$input->SetOpenid($openId);
$order = WxPayApi::unifiedOrder($input);
echo '<font color="#f00"><b>统一下单支付单信息</b></font><br/>';
printf_info($order);
$jsApiParameters = $tools->GetJsApiParameters($order);
//获取共享收货地址js函数参数
$editAddress = $tools->GetEditAddressParameters();
//③、在支持成功回调通知中处理成功之后的事宜,见 notify.php
/**
* 注意:
* 1、当你的回调地址不可访问的时候,回调通知会失败,可以通过查询订单来确认支付是否成功
* 2、jsapi支付时需要填入用户openid,WxPay.JsApiPay.php中有获取openid流程 (文档可以参考微信公众平台“网页授权接口”,
* 参考http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html)
*/
?>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>微信支付样例-支付</title>
<script type="text/javascript">
//调用微信JS api 支付
function jsApiCall()
{
WeixinJSBridge.invoke(
'getBrandWCPayRequest',
<?php echo $jsApiParameters; ?>,
function(res){
WeixinJSBridge.log(res.err_msg);
alert(res.err_code+res.err_desc+res.err_msg);
}
);
}
function callpay()
{
if (typeof WeixinJSBridge == "undefined"){
if( document.addEventListener ){
document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
}else if (document.attachEvent){
document.attachEvent('WeixinJSBridgeReady', jsApiCall);
document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
}
}else{
jsApiCall();
}
}
</script>
<script type="text/javascript">
//获取共享地址
function editAddress()
{
WeixinJSBridge.invoke(
'editAddress',
<?php echo $editAddress; ?>,
function(res){
var value1 = res.proviceFirstStageName;
var value2 = res.addressCitySecondStageName;
var value3 = res.addressCountiesThirdStageName;
var value4 = res.addressDetailInfo;
var tel = res.telNumber;
alert(value1 + value2 + value3 + value4 + ":" + tel);
}
);
}
window.onload = function(){
if (typeof WeixinJSBridge == "undefined"){
if( document.addEventListener ){
document.addEventListener('WeixinJSBridgeReady', editAddress, false);
}else if (document.attachEvent){
document.attachEvent('WeixinJSBridgeReady', editAddress);
document.attachEvent('onWeixinJSBridgeReady', editAddress);
}
}else{
editAddress();
}
};
</script>
</head>
<body>
<br/>
<font color="#9ACD32"><b>该笔订单支付金额为<span style="color:#f00;font-size:50px">1分</span></b></font><br/><br/>
<div align="center">
<button style="width:210px; height:50px; border-radius: 15px;background-color:#FE6714; border:0px #FE6714 solid; cursor: pointer; color:white; font-size:16px;" type="button" onclick="callpay()" >立即支付</button>
</div>
</body>
</html>
\ No newline at end of file
... ...
<?php
//以下为日志
interface ILogHandler
{
public function write($msg);
}
class CLogFileHandler implements ILogHandler
{
private $handle = null;
public function __construct($file = '')
{
$this->handle = fopen($file,'a');
}
public function write($msg)
{
fwrite($this->handle, $msg, 4096);
}
public function __destruct()
{
fclose($this->handle);
}
}
class Log
{
private $handler = null;
private $level = 15;
private static $instance = null;
private function __construct(){}
private function __clone(){}
public static function Init($handler = null,$level = 15)
{
if(!self::$instance instanceof self)
{
self::$instance = new self();
self::$instance->__setHandle($handler);
self::$instance->__setLevel($level);
}
return self::$instance;
}
private function __setHandle($handler){
$this->handler = $handler;
}
private function __setLevel($level)
{
$this->level = $level;
}
public static function DEBUG($msg)
{
self::$instance->write(1, $msg);
}
public static function WARN($msg)
{
self::$instance->write(4, $msg);
}
public static function ERROR($msg)
{
$debugInfo = debug_backtrace();
$stack = "[";
foreach($debugInfo as $key => $val){
if(array_key_exists("file", $val)){
$stack .= ",file:" . $val["file"];
}
if(array_key_exists("line", $val)){
$stack .= ",line:" . $val["line"];
}
if(array_key_exists("function", $val)){
$stack .= ",function:" . $val["function"];
}
}
$stack .= "]";
self::$instance->write(8, $stack . $msg);
}
public static function INFO($msg)
{
self::$instance->write(2, $msg);
}
private function getLevelStr($level)
{
switch ($level)
{
case 1:
return 'debug';
break;
case 2:
return 'info';
break;
case 4:
return 'warn';
break;
case 8:
return 'error';
break;
default:
}
}
protected function write($level,$msg)
{
if(($level & $this->level) == $level )
{
$msg = '['.date('Y-m-d H:i:s').']['.$this->getLevelStr($level).'] '.$msg."\n";
$this->handler->write($msg);
}
}
}
... ...
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>微信支付样例-查退款单</title>
</head>
<?php
require_once "../lib/WxPay.Api.php";
require_once "WxPay.MicroPay.php";
require_once 'log.php';
//初始化日志
$logHandler= new CLogFileHandler("../logs/".date('Y-m-d').'.log');
$log = Log::Init($logHandler, 15);
//打印输出数组信息
function printf_info($data)
{
foreach($data as $key=>$value){
echo "<font color='#00ff55;'>$key</font> : $value <br/>";
}
}
if(isset($_REQUEST["auth_code"]) && $_REQUEST["auth_code"] != ""){
$auth_code = $_REQUEST["auth_code"];
$input = new WxPayMicroPay();
$input->SetAuth_code($auth_code);
$input->SetBody("刷卡测试样例-支付");
$input->SetTotal_fee("1");
$input->SetOut_trade_no(WxPayConfig::MCHID.date("YmdHis"));
$microPay = new MicroPay();
printf_info($microPay->pay($input));
}
/**
* 注意:
* 1、提交被扫之后,返回系统繁忙、用户输入密码等错误信息时需要循环查单以确定是否支付成功
* 2、多次(一半10次)确认都未明确成功时需要调用撤单接口撤单,防止用户重复支付
*/
?>
<body>
<form action="#" method="post">
<div style="margin-left:2%;">商品描述:</div><br/>
<input type="text" style="width:96%;height:35px;margin-left:2%;" readonly value="刷卡测试样例-支付" name="auth_code" /><br /><br />
<div style="margin-left:2%;">支付金额:</div><br/>
<input type="text" style="width:96%;height:35px;margin-left:2%;" readonly value="1分" name="auth_code" /><br /><br />
<div style="margin-left:2%;">授权码:</div><br/>
<input type="text" style="width:96%;height:35px;margin-left:2%;" name="auth_code" /><br /><br />
<div align="center">
<input type="submit" value="提交刷卡" style="width:210px; height:50px; border-radius: 15px;background-color:#FE6714; border:0px #FE6714 solid; cursor: pointer; color:white; font-size:16px;" type="button" onclick="callpay()" />
</div>
</form>
</body>
</html>
\ No newline at end of file
... ...
<?php
ini_set('date.timezone','Asia/Shanghai');
//error_reporting(E_ERROR);
require_once "../lib/WxPay.Api.php";
require_once "WxPay.NativePay.php";
require_once 'log.php';
//模式一
/**
* 流程:
* 1、组装包含支付信息的url,生成二维码
* 2、用户扫描二维码,进行支付
* 3、确定支付之后,微信服务器会回调预先配置的回调地址,在【微信开放平台-微信支付-支付配置】中进行配置
* 4、在接到回调通知之后,用户进行统一下单支付,并返回支付信息以完成支付(见:native_notify.php)
* 5、支付完成之后,微信服务器会通知支付成功
* 6、在支付成功通知中需要查单确认是否真正支付成功(见:notify.php)
*/
$notify = new NativePay();
$url1 = $notify->GetPrePayUrl("123456789");
//模式二
/**
* 流程:
* 1、调用统一下单,取得code_url,生成二维码
* 2、用户扫描二维码,进行支付
* 3、支付完成之后,微信服务器会通知支付成功
* 4、在支付成功通知中需要查单确认是否真正支付成功(见:notify.php)
*/
$input = new WxPayUnifiedOrder();
$input->SetBody("test");
$input->SetAttach("test");
$input->SetOut_trade_no(WxPayConfig::MCHID.date("YmdHis"));
$input->SetTotal_fee("1");
$input->SetTime_start(date("YmdHis"));
$input->SetTime_expire(date("YmdHis", time() + 600));
$input->SetGoods_tag("test");
$input->SetNotify_url("http://paysdk.weixin.qq.com/example/notify.php");
$input->SetTrade_type("NATIVE");
$input->SetProduct_id("123456789");
$result = $notify->GetPayUrl($input);
$url2 = $result["code_url"];
?>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>微信支付样例-退款</title>
</head>
<body>
<div style="margin-left: 10px;color:#556B2F;font-size:30px;font-weight: bolder;">扫描支付模式一</div><br/>
<img alt="模式一扫码支付" src="http://paysdk.weixin.qq.com/example/qrcode.php?data=<?php echo urlencode($url1);?>" style="width:150px;height:150px;"/>
<br/><br/><br/>
<div style="margin-left: 10px;color:#556B2F;font-size:30px;font-weight: bolder;">扫描支付模式二</div><br/>
<img alt="模式二扫码支付" src="http://paysdk.weixin.qq.com/example/qrcode.php?data=<?php echo urlencode($url2);?>" style="width:150px;height:150px;"/>
</body>
</html>
\ No newline at end of file
... ...
<?php
ini_set('date.timezone','Asia/Shanghai');
error_reporting(E_ERROR);
require_once "../lib/WxPay.Api.php";
require_once '../lib/WxPay.Notify.php';
require_once 'log.php';
//初始化日志
$logHandler= new CLogFileHandler("../logs/".date('Y-m-d').'.log');
$log = Log::Init($logHandler, 15);
class NativeNotifyCallBack extends WxPayNotify
{
public function unifiedorder($openId, $product_id)
{
//统一下单
$input = new WxPayUnifiedOrder();
$input->SetBody("test");
$input->SetAttach("test");
$input->SetOut_trade_no(WxPayConfig::MCHID.date("YmdHis"));
$input->SetTotal_fee("1");
$input->SetTime_start(date("YmdHis"));
$input->SetTime_expire(date("YmdHis", time() + 600));
$input->SetGoods_tag("test");
$input->SetNotify_url("http://paysdk.weixin.qq.com/example/notify.php");
$input->SetTrade_type("NATIVE");
$input->SetOpenid($openId);
$input->SetProduct_id($product_id);
$result = WxPayApi::unifiedOrder($input);
Log::DEBUG("unifiedorder:" . json_encode($result));
return $result;
}
public function NotifyProcess($data, &$msg)
{
//echo "处理回调";
Log::DEBUG("call back:" . json_encode($data));
if(!array_key_exists("openid", $data) ||
!array_key_exists("product_id", $data))
{
$msg = "回调数据异常";
return false;
}
$openid = $data["openid"];
$product_id = $data["product_id"];
//统一下单
$result = $this->unifiedorder($openid, $product_id);
if(!array_key_exists("appid", $result) ||
!array_key_exists("mch_id", $result) ||
!array_key_exists("prepay_id", $result))
{
$msg = "统一下单失败";
return false;
}
$this->SetData("appid", $result["appid"]);
$this->SetData("mch_id", $result["mch_id"]);
$this->SetData("nonce_str", WxPayApi::getNonceStr());
$this->SetData("prepay_id", $result["prepay_id"]);
$this->SetData("result_code", "SUCCESS");
$this->SetData("err_code_des", "OK");
return true;
}
}
Log::DEBUG("begin notify!");
$notify = new NativeNotifyCallBack();
$notify->Handle(true);
... ...
<?php
ini_set('date.timezone','Asia/Shanghai');
error_reporting(E_ERROR);
require_once "../lib/WxPay.Api.php";
require_once '../lib/WxPay.Notify.php';
require_once 'log.php';
//初始化日志
$logHandler= new CLogFileHandler("../logs/".date('Y-m-d').'.log');
$log = Log::Init($logHandler, 15);
class PayNotifyCallBack extends WxPayNotify
{
//查询订单
public function Queryorder($transaction_id)
{
$input = new WxPayOrderQuery();
$input->SetTransaction_id($transaction_id);
$result = WxPayApi::orderQuery($input);
Log::DEBUG("query:" . json_encode($result));
if(array_key_exists("return_code", $result)
&& array_key_exists("result_code", $result)
&& $result["return_code"] == "SUCCESS"
&& $result["result_code"] == "SUCCESS")
{
return true;
}
return false;
}
//重写回调处理函数
public function NotifyProcess($data, &$msg)
{
Log::DEBUG("call back:" . json_encode($data));
$notfiyOutput = array();
if(!array_key_exists("transaction_id", $data)){
$msg = "输入参数不正确";
return false;
}
//查询订单,判断订单真实性
if(!$this->Queryorder($data["transaction_id"])){
$msg = "订单查询失败";
return false;
}
return true;
}
}
Log::DEBUG("begin notify");
$notify = new PayNotifyCallBack();
$notify->Handle(false);
... ...
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>微信支付样例-订单查询</title>
</head>
<?php
ini_set('date.timezone','Asia/Shanghai');
error_reporting(E_ERROR);
require_once "../lib/WxPay.Api.php";
require_once 'log.php';
//初始化日志
$logHandler= new CLogFileHandler("./logs/".date('Y-m-d').'.log');
$log = Log::Init($logHandler, 15);
function printf_info($data)
{
foreach($data as $key=>$value){
echo "<font color='#f00;'>$key</font> : $value <br/>";
}
}
if(isset($_REQUEST["transaction_id"]) && $_REQUEST["transaction_id"] != ""){
$transaction_id = $_REQUEST["transaction_id"];
$input = new WxPayOrderQuery();
$input->SetTransaction_id($transaction_id);
printf_info(WxPayApi::orderQuery($input));
exit();
}
if(isset($_REQUEST["out_trade_no"]) && $_REQUEST["out_trade_no"] != ""){
$out_trade_no = $_REQUEST["out_trade_no"];
$input = new WxPayOrderQuery();
$input->SetOut_trade_no($out_trade_no);
printf_info(WxPayApi::orderQuery($input));
exit();
}
?>
<body>
<form action="#" method="post">
<div style="margin-left:2%;color:#f00">微信订单号和商户订单号选少填一个,微信订单号优先:</div><br/>
<div style="margin-left:2%;">微信订单号:</div><br/>
<input type="text" style="width:96%;height:35px;margin-left:2%;" name="transaction_id" /><br /><br />
<div style="margin-left:2%;">商户订单号:</div><br/>
<input type="text" style="width:96%;height:35px;margin-left:2%;" name="out_trade_no" /><br /><br />
<div align="center">
<input type="submit" value="查询" style="width:210px; height:50px; border-radius: 15px;background-color:#FE6714; border:0px #FE6714 solid; cursor: pointer; color:white; font-size:16px;" type="button" onclick="callpay()" />
</div>
</form>
</body>
</html>
\ No newline at end of file
... ...
<?php
error_reporting(E_ERROR);
require_once 'phpqrcode/phpqrcode1.php';
$url = urldecode($_GET["data"]);
QRcode::png($url);
... ...
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>微信支付样例-退款</title>
</head>
<?php
ini_set('date.timezone','Asia/Shanghai');
error_reporting(E_ERROR);
require_once "../lib/WxPay.Api.php";
require_once 'log.php';
//初始化日志
$logHandler= new CLogFileHandler("../logs/".date('Y-m-d').'.log');
$log = Log::Init($logHandler, 15);
function printf_info($data)
{
foreach($data as $key=>$value){
echo "<font color='#f00;'>$key</font> : $value <br/>";
}
}
if(isset($_REQUEST["transaction_id"]) && $_REQUEST["transaction_id"] != ""){
$transaction_id = $_REQUEST["transaction_id"];
$total_fee = $_REQUEST["total_fee"];
$refund_fee = $_REQUEST["refund_fee"];
$input = new WxPayRefund();
$input->SetTransaction_id($transaction_id);
$input->SetTotal_fee($total_fee);
$input->SetRefund_fee($refund_fee);
$input->SetOut_refund_no(WxPayConfig::MCHID.date("YmdHis"));
$input->SetOp_user_id(WxPayConfig::MCHID);
printf_info(WxPayApi::refund($input));
exit();
}
//$_REQUEST["out_trade_no"]= "122531270220150304194108";
///$_REQUEST["total_fee"]= "1";
//$_REQUEST["refund_fee"] = "1";
if(isset($_REQUEST["out_trade_no"]) && $_REQUEST["out_trade_no"] != ""){
$out_trade_no = $_REQUEST["out_trade_no"];
$total_fee = $_REQUEST["total_fee"];
$refund_fee = $_REQUEST["refund_fee"];
$input = new WxPayRefund();
$input->SetOut_trade_no($out_trade_no);
$input->SetTotal_fee($total_fee);
$input->SetRefund_fee($refund_fee);
$input->SetOut_refund_no(WxPayConfig::MCHID.date("YmdHis"));
$input->SetOp_user_id(WxPayConfig::MCHID);
printf_info(WxPayApi::refund($input));
exit();
}
?>
<body>
<form action="#" method="post">
<div style="margin-left:2%;color:#f00">微信订单号和商户订单号选少填一个,微信订单号优先:</div><br/>
<div style="margin-left:2%;">微信订单号:</div><br/>
<input type="text" style="width:96%;height:35px;margin-left:2%;" name="transaction_id" /><br /><br />
<div style="margin-left:2%;">商户订单号:</div><br/>
<input type="text" style="width:96%;height:35px;margin-left:2%;" name="out_trade_no" /><br /><br />
<div style="margin-left:2%;">订单总金额(分):</div><br/>
<input type="text" style="width:96%;height:35px;margin-left:2%;" name="total_fee" /><br /><br />
<div style="margin-left:2%;">退款金额(分):</div><br/>
<input type="text" style="width:96%;height:35px;margin-left:2%;" name="refund_fee" /><br /><br />
<div align="center">
<input type="submit" value="提交退款" style="width:210px; height:50px; border-radius: 15px;background-color:#FE6714; border:0px #FE6714 solid; cursor: pointer; color:white; font-size:16px;" type="button" onclick="callpay()" />
</div>
</form>
</body>
</html>
\ No newline at end of file
... ...
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>微信支付样例-查退款单</title>
</head>
<?php
ini_set('date.timezone','Asia/Shanghai');
error_reporting(E_ERROR);
require_once "../lib/WxPay.Api.php";
require_once 'log.php';
//初始化日志
$logHandler= new CLogFileHandler("../logs/".date('Y-m-d').'.log');
$log = Log::Init($logHandler, 15);
function printf_info($data)
{
foreach($data as $key=>$value){
echo "<font color='#f00;'>$key</font> : $value <br/>";
}
}
if(isset($_REQUEST["transaction_id"]) && $_REQUEST["transaction_id"] != ""){
$transaction_id = $_REQUEST["transaction_id"];
$input = new WxPayRefundQuery();
$input->SetTransaction_id($transaction_id);
printf_info(WxPayApi::refundQuery($input));
}
if(isset($_REQUEST["out_trade_no"]) && $_REQUEST["out_trade_no"] != ""){
$out_trade_no = $_REQUEST["out_trade_no"];
$input = new WxPayRefundQuery();
$input->SetOut_trade_no($out_trade_no);
printf_info(WxPayApi::refundQuery($input));
exit();
}
if(isset($_REQUEST["out_refund_no"]) && $_REQUEST["out_refund_no"] != ""){
$out_refund_no = $_REQUEST["out_refund_no"];
$input = new WxPayRefundQuery();
$input->SetOut_refund_no($out_refund_no);
printf_info(WxPayApi::refundQuery($input));
exit();
}
if(isset($_REQUEST["refund_id"]) && $_REQUEST["refund_id"] != ""){
$refund_id = $_REQUEST["refund_id"];
$input = new WxPayRefundQuery();
$input->SetRefund_id($refund_id);
printf_info(WxPayApi::refundQuery($input));
exit();
}
?>
<body>
<form action="#" method="post">
<div style="margin-left:2%;color:#f00">微信订单号、商户订单号、微信订单号、微信退款单号选填至少一个,微信退款单号优先:</div><br/>
<div style="margin-left:2%;">微信订单号:</div><br/>
<input type="text" style="width:96%;height:35px;margin-left:2%;" name="transaction_id" /><br /><br />
<div style="margin-left:2%;">商户订单号:</div><br/>
<input type="text" style="width:96%;height:35px;margin-left:2%;" name="out_trade_no" /><br /><br />
<div style="margin-left:2%;">商户退款单号:</div><br/>
<input type="text" style="width:96%;height:35px;margin-left:2%;" name="out_refund_no" /><br /><br />
<div style="margin-left:2%;">微信退款单号:</div><br/>
<input type="text" style="width:96%;height:35px;margin-left:2%;" name="refund_id" /><br /><br />
<div align="center">
<input type="submit" value="查询" style="width:210px; height:50px; border-radius: 15px;background-color:#FE6714; border:0px #FE6714 solid; cursor: pointer; color:white; font-size:16px;" type="button" onclick="callpay()" />
</div>
</form>
</body>
</html>
\ No newline at end of file
... ...
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>微信支付样例</title>
<style type="text/css">
ul {
margin-left:10px;
margin-right:10px;
margin-top:10px;
padding: 0;
}
li {
width: 32%;
float: left;
margin: 0px;
margin-left:1%;
padding: 0px;
height: 100px;
display: inline;
line-height: 100px;
color: #fff;
font-size: x-large;
word-break:break-all;
word-wrap : break-word;
margin-bottom: 5px;
}
a {
-webkit-tap-highlight-color: rgba(0,0,0,0);
text-decoration:none;
color:#fff;
}
a:link{
-webkit-tap-highlight-color: rgba(0,0,0,0);
text-decoration:none;
color:#fff;
}
a:visited{
-webkit-tap-highlight-color: rgba(0,0,0,0);
text-decoration:none;
color:#fff;
}
a:hover{
-webkit-tap-highlight-color: rgba(0,0,0,0);
text-decoration:none;
color:#fff;
}
a:active{
-webkit-tap-highlight-color: rgba(0,0,0,0);
text-decoration:none;
color:#fff;
}
</style>
</head>
<body>
<div align="center">
<ul>
<li style="background-color:#FF7F24"><a href="http://paysdk.weixin.qq.com/example/jsapi.php">JSAPI支付</a></li>
<li style="background-color:#698B22"><a href="http://paysdk.weixin.qq.com/example/micropay.php">刷卡支付</a></li>
<li style="background-color:#8B6914"><a href="http://paysdk.weixin.qq.com/example/native.php">扫码支付</a></li>
<li style="background-color:#CDCD00"><a href="http://paysdk.weixin.qq.com/example/orderquery.php">订单查询</a></li>
<li style="background-color:#CD3278"><a href="http://paysdk.weixin.qq.com/example/refund.php">订单退款</a></li>
<li style="background-color:#848484"><a href="http://paysdk.weixin.qq.com/example/refundquery.php">退款查询</a></li>
<li style="background-color:#8EE5EE"><a href="http://paysdk.weixin.qq.com/example/download.php">下载订单</a></li>
</ul>
</div>
</body>
</html>
\ No newline at end of file
... ...
<?php
require_once "WxPay.Exception.php";
require_once "WxPay.Config.php";
require_once "WxPay.Data.php";
/**
*
* 接口访问类,包含所有微信支付API列表的封装,类中方法为static方法,
* 每个接口有默认超时时间(除提交被扫支付为10s,上报超时时间为1s外,其他均为6s)
* @author widyhu
*
*/
class WxPayApi
{
/**
*
* 统一下单,WxPayUnifiedOrder中out_trade_no、body、total_fee、trade_type必填
* appid、mchid、spbill_create_ip、nonce_str不需要填入
* @param WxPayUnifiedOrder $inputObj
* @param int $timeOut
* @throws WxPayException
* @return 成功时返回,其他抛异常
*/
public static function unifiedOrder($inputObj, $timeOut = 6)
{
$url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
//检测必填参数
if(!$inputObj->IsOut_trade_noSet()) {
throw new WxPayException("缺少统一支付接口必填参数out_trade_no!");
}else if(!$inputObj->IsBodySet()){
throw new WxPayException("缺少统一支付接口必填参数body!");
}else if(!$inputObj->IsTotal_feeSet()) {
throw new WxPayException("缺少统一支付接口必填参数total_fee!");
}else if(!$inputObj->IsTrade_typeSet()) {
throw new WxPayException("缺少统一支付接口必填参数trade_type!");
}
//关联参数
if($inputObj->GetTrade_type() == "JSAPI" && !$inputObj->IsOpenidSet()){
throw new WxPayException("统一支付接口中,缺少必填参数openid!trade_type为JSAPI时,openid为必填参数!");
}
if($inputObj->GetTrade_type() == "NATIVE" && !$inputObj->IsProduct_idSet()){
throw new WxPayException("统一支付接口中,缺少必填参数product_id!trade_type为JSAPI时,product_id为必填参数!");
}
//异步通知url未设置,则使用配置文件中的url
if(!$inputObj->IsNotify_urlSet()){
$inputObj->SetNotify_url(WxPayConfig::NOTIFY_URL);//异步通知url
}
$inputObj->SetAppid(WxPayConfig::APPID);//公众账号ID
$inputObj->SetMch_id(WxPayConfig::MCHID);//商户号
$inputObj->SetSpbill_create_ip($_SERVER['REMOTE_ADDR']);//终端ip
//$inputObj->SetSpbill_create_ip("1.1.1.1");
$inputObj->SetNonce_str(self::getNonceStr());//随机字符串
//签名
$inputObj->SetSign();
$xml = $inputObj->ToXml();
$startTimeStamp = self::getMillisecond();//请求开始时间
$response = self::postXmlCurl($xml, $url, false, $timeOut);
$result = WxPayResults::Init($response);
self::reportCostTime($url, $startTimeStamp, $result);//上报请求花费时间
return $result;
}
/**
*
* 查询订单,WxPayOrderQuery中out_trade_no、transaction_id至少填一个
* appid、mchid、spbill_create_ip、nonce_str不需要填入
* @param WxPayOrderQuery $inputObj
* @param int $timeOut
* @throws WxPayException
* @return 成功时返回,其他抛异常
*/
public static function orderQuery($inputObj, $timeOut = 6)
{
$url = "https://api.mch.weixin.qq.com/pay/orderquery";
//检测必填参数
if(!$inputObj->IsOut_trade_noSet() && !$inputObj->IsTransaction_idSet()) {
throw new WxPayException("订单查询接口中,out_trade_no、transaction_id至少填一个!");
}
$inputObj->SetAppid(WxPayConfig::APPID);//公众账号ID
$inputObj->SetMch_id(WxPayConfig::MCHID);//商户号
$inputObj->SetNonce_str(self::getNonceStr());//随机字符串
$inputObj->SetSign();//签名
$xml = $inputObj->ToXml();
$startTimeStamp = self::getMillisecond();//请求开始时间
$response = self::postXmlCurl($xml, $url, false, $timeOut);
$result = WxPayResults::Init($response);
self::reportCostTime($url, $startTimeStamp, $result);//上报请求花费时间
return $result;
}
/**
*
* 关闭订单,WxPayCloseOrder中out_trade_no必填
* appid、mchid、spbill_create_ip、nonce_str不需要填入
* @param WxPayCloseOrder $inputObj
* @param int $timeOut
* @throws WxPayException
* @return 成功时返回,其他抛异常
*/
public static function closeOrder($inputObj, $timeOut = 6)
{
$url = "https://api.mch.weixin.qq.com/pay/closeorder";
//检测必填参数
if(!$inputObj->IsOut_trade_noSet()) {
throw new WxPayException("订单查询接口中,out_trade_no必填!");
}
$inputObj->SetAppid(WxPayConfig::APPID);//公众账号ID
$inputObj->SetMch_id(WxPayConfig::MCHID);//商户号
$inputObj->SetNonce_str(self::getNonceStr());//随机字符串
$inputObj->SetSign();//签名
$xml = $inputObj->ToXml();
$startTimeStamp = self::getMillisecond();//请求开始时间
$response = self::postXmlCurl($xml, $url, false, $timeOut);
$result = WxPayResults::Init($response);
self::reportCostTime($url, $startTimeStamp, $result);//上报请求花费时间
return $result;
}
/**
*
* 申请退款,WxPayRefund中out_trade_no、transaction_id至少填一个且
* out_refund_no、total_fee、refund_fee、op_user_id为必填参数
* appid、mchid、spbill_create_ip、nonce_str不需要填入
* @param WxPayRefund $inputObj
* @param int $timeOut
* @throws WxPayException
* @return 成功时返回,其他抛异常
*/
public static function refund($inputObj, $timeOut = 6)
{
$url = "https://api.mch.weixin.qq.com/secapi/pay/refund";
//检测必填参数
if(!$inputObj->IsOut_trade_noSet() && !$inputObj->IsTransaction_idSet()) {
throw new WxPayException("退款申请接口中,out_trade_no、transaction_id至少填一个!");
}else if(!$inputObj->IsOut_refund_noSet()){
throw new WxPayException("退款申请接口中,缺少必填参数out_refund_no!");
}else if(!$inputObj->IsTotal_feeSet()){
throw new WxPayException("退款申请接口中,缺少必填参数total_fee!");
}else if(!$inputObj->IsRefund_feeSet()){
throw new WxPayException("退款申请接口中,缺少必填参数refund_fee!");
}else if(!$inputObj->IsOp_user_idSet()){
throw new WxPayException("退款申请接口中,缺少必填参数op_user_id!");
}
$inputObj->SetAppid(WxPayConfig::APPID);//公众账号ID
$inputObj->SetMch_id(WxPayConfig::MCHID);//商户号
$inputObj->SetNonce_str(self::getNonceStr());//随机字符串
$inputObj->SetSign();//签名
$xml = $inputObj->ToXml();
$startTimeStamp = self::getMillisecond();//请求开始时间
$response = self::postXmlCurl($xml, $url, true, $timeOut);
$result = WxPayResults::Init($response);
self::reportCostTime($url, $startTimeStamp, $result);//上报请求花费时间
return $result;
}
/**
*
* 查询退款
* 提交退款申请后,通过调用该接口查询退款状态。退款有一定延时,
* 用零钱支付的退款20分钟内到账,银行卡支付的退款3个工作日后重新查询退款状态。
* WxPayRefundQuery中out_refund_no、out_trade_no、transaction_id、refund_id四个参数必填一个
* appid、mchid、spbill_create_ip、nonce_str不需要填入
* @param WxPayRefundQuery $inputObj
* @param int $timeOut
* @throws WxPayException
* @return 成功时返回,其他抛异常
*/
public static function refundQuery($inputObj, $timeOut = 6)
{
$url = "https://api.mch.weixin.qq.com/pay/refundquery";
//检测必填参数
if(!$inputObj->IsOut_refund_noSet() &&
!$inputObj->IsOut_trade_noSet() &&
!$inputObj->IsTransaction_idSet() &&
!$inputObj->IsRefund_idSet()) {
throw new WxPayException("退款查询接口中,out_refund_no、out_trade_no、transaction_id、refund_id四个参数必填一个!");
}
$inputObj->SetAppid(WxPayConfig::APPID);//公众账号ID
$inputObj->SetMch_id(WxPayConfig::MCHID);//商户号
$inputObj->SetNonce_str(self::getNonceStr());//随机字符串
$inputObj->SetSign();//签名
$xml = $inputObj->ToXml();
$startTimeStamp = self::getMillisecond();//请求开始时间
$response = self::postXmlCurl($xml, $url, false, $timeOut);
$result = WxPayResults::Init($response);
self::reportCostTime($url, $startTimeStamp, $result);//上报请求花费时间
return $result;
}
/**
* 下载对账单,WxPayDownloadBill中bill_date为必填参数
* appid、mchid、spbill_create_ip、nonce_str不需要填入
* @param WxPayDownloadBill $inputObj
* @param int $timeOut
* @throws WxPayException
* @return 成功时返回,其他抛异常
*/
public static function downloadBill($inputObj, $timeOut = 6)
{
$url = "https://api.mch.weixin.qq.com/pay/downloadbill";
//检测必填参数
if(!$inputObj->IsBill_dateSet()) {
throw new WxPayException("对账单接口中,缺少必填参数bill_date!");
}
$inputObj->SetAppid(WxPayConfig::APPID);//公众账号ID
$inputObj->SetMch_id(WxPayConfig::MCHID);//商户号
$inputObj->SetNonce_str(self::getNonceStr());//随机字符串
$inputObj->SetSign();//签名
$xml = $inputObj->ToXml();
$response = self::postXmlCurl($xml, $url, false, $timeOut);
if(substr($response, 0 , 5) == "<xml>"){
return "";
}
return $response;
}
/**
* 提交被扫支付API
* 收银员使用扫码设备读取微信用户刷卡授权码以后,二维码或条码信息传送至商户收银台,
* 由商户收银台或者商户后台调用该接口发起支付。
* WxPayWxPayMicroPay中body、out_trade_no、total_fee、auth_code参数必填
* appid、mchid、spbill_create_ip、nonce_str不需要填入
* @param WxPayWxPayMicroPay $inputObj
* @param int $timeOut
*/
public static function micropay($inputObj, $timeOut = 10)
{
$url = "https://api.mch.weixin.qq.com/pay/micropay";
//检测必填参数
if(!$inputObj->IsBodySet()) {
throw new WxPayException("提交被扫支付API接口中,缺少必填参数body!");
} else if(!$inputObj->IsOut_trade_noSet()) {
throw new WxPayException("提交被扫支付API接口中,缺少必填参数out_trade_no!");
} else if(!$inputObj->IsTotal_feeSet()) {
throw new WxPayException("提交被扫支付API接口中,缺少必填参数total_fee!");
} else if(!$inputObj->IsAuth_codeSet()) {
throw new WxPayException("提交被扫支付API接口中,缺少必填参数auth_code!");
}
$inputObj->SetSpbill_create_ip($_SERVER['REMOTE_ADDR']);//终端ip
$inputObj->SetAppid(WxPayConfig::APPID);//公众账号ID
$inputObj->SetMch_id(WxPayConfig::MCHID);//商户号
$inputObj->SetNonce_str(self::getNonceStr());//随机字符串
$inputObj->SetSign();//签名
$xml = $inputObj->ToXml();
$startTimeStamp = self::getMillisecond();//请求开始时间
$response = self::postXmlCurl($xml, $url, false, $timeOut);
$result = WxPayResults::Init($response);
self::reportCostTime($url, $startTimeStamp, $result);//上报请求花费时间
return $result;
}
/**
*
* 撤销订单API接口,WxPayReverse中参数out_trade_no和transaction_id必须填写一个
* appid、mchid、spbill_create_ip、nonce_str不需要填入
* @param WxPayReverse $inputObj
* @param int $timeOut
* @throws WxPayException
*/
public static function reverse($inputObj, $timeOut = 6)
{
$url = "https://api.mch.weixin.qq.com/secapi/pay/reverse";
//检测必填参数
if(!$inputObj->IsOut_trade_noSet() && !$inputObj->IsTransaction_idSet()) {
throw new WxPayException("撤销订单API接口中,参数out_trade_no和transaction_id必须填写一个!");
}
$inputObj->SetAppid(WxPayConfig::APPID);//公众账号ID
$inputObj->SetMch_id(WxPayConfig::MCHID);//商户号
$inputObj->SetNonce_str(self::getNonceStr());//随机字符串
$inputObj->SetSign();//签名
$xml = $inputObj->ToXml();
$startTimeStamp = self::getMillisecond();//请求开始时间
$response = self::postXmlCurl($xml, $url, true, $timeOut);
$result = WxPayResults::Init($response);
self::reportCostTime($url, $startTimeStamp, $result);//上报请求花费时间
return $result;
}
/**
*
* 测速上报,该方法内部封装在report中,使用时请注意异常流程
* WxPayReport中interface_url、return_code、result_code、user_ip、execute_time_必填
* appid、mchid、spbill_create_ip、nonce_str不需要填入
* @param WxPayReport $inputObj
* @param int $timeOut
* @throws WxPayException
* @return 成功时返回,其他抛异常
*/
public static function report($inputObj, $timeOut = 1)
{
$url = "https://api.mch.weixin.qq.com/payitil/report";
//检测必填参数
if(!$inputObj->IsInterface_urlSet()) {
throw new WxPayException("接口URL,缺少必填参数interface_url!");
} if(!$inputObj->IsReturn_codeSet()) {
throw new WxPayException("返回状态码,缺少必填参数return_code!");
} if(!$inputObj->IsResult_codeSet()) {
throw new WxPayException("业务结果,缺少必填参数result_code!");
} if(!$inputObj->IsUser_ipSet()) {
throw new WxPayException("访问接口IP,缺少必填参数user_ip!");
} if(!$inputObj->IsExecute_time_Set()) {
throw new WxPayException("接口耗时,缺少必填参数execute_time_!");
}
$inputObj->SetAppid(WxPayConfig::APPID);//公众账号ID
$inputObj->SetMch_id(WxPayConfig::MCHID);//商户号
$inputObj->SetUser_ip($_SERVER['REMOTE_ADDR']);//终端ip
$inputObj->SetTime(date("YmdHis"));//商户上报时间
$inputObj->SetNonce_str(self::getNonceStr());//随机字符串
$inputObj->SetSign();//签名
$xml = $inputObj->ToXml();
$startTimeStamp = self::getMillisecond();//请求开始时间
$response = self::postXmlCurl($xml, $url, false, $timeOut);
return $response;
}
/**
*
* 生成二维码规则,模式一生成支付二维码
* appid、mchid、spbill_create_ip、nonce_str不需要填入
* @param WxPayBizPayUrl $inputObj
* @param int $timeOut
* @throws WxPayException
* @return 成功时返回,其他抛异常
*/
public static function bizpayurl($inputObj, $timeOut = 6)
{
if(!$inputObj->IsProduct_idSet()){
throw new WxPayException("生成二维码,缺少必填参数product_id!");
}
$inputObj->SetAppid(WxPayConfig::APPID);//公众账号ID
$inputObj->SetMch_id(WxPayConfig::MCHID);//商户号
$inputObj->SetTime_stamp(time());//时间戳
$inputObj->SetNonce_str(self::getNonceStr());//随机字符串
$inputObj->SetSign();//签名
return $inputObj->GetValues();
}
/**
*
* 转换短链接
* 该接口主要用于扫码原生支付模式一中的二维码链接转成短链接(weixin://wxpay/s/XXXXXX),
* 减小二维码数据量,提升扫描速度和精确度。
* appid、mchid、spbill_create_ip、nonce_str不需要填入
* @param WxPayShortUrl $inputObj
* @param int $timeOut
* @throws WxPayException
* @return 成功时返回,其他抛异常
*/
public static function shorturl($inputObj, $timeOut = 6)
{
$url = "https://api.mch.weixin.qq.com/tools/shorturl";
//检测必填参数
if(!$inputObj->IsLong_urlSet()) {
throw new WxPayException("需要转换的URL,签名用原串,传输需URL encode!");
}
$inputObj->SetAppid(WxPayConfig::APPID);//公众账号ID
$inputObj->SetMch_id(WxPayConfig::MCHID);//商户号
$inputObj->SetNonce_str(self::getNonceStr());//随机字符串
$inputObj->SetSign();//签名
$xml = $inputObj->ToXml();
$startTimeStamp = self::getMillisecond();//请求开始时间
$response = self::postXmlCurl($xml, $url, false, $timeOut);
$result = WxPayResults::Init($response);
self::reportCostTime($url, $startTimeStamp, $result);//上报请求花费时间
return $result;
}
/**
*
* 支付结果通用通知
* @param function $callback
* 直接回调函数使用方法: notify(you_function);
* 回调类成员函数方法:notify(array($this, you_function));
* $callback 原型为:function function_name($data){}
*/
public static function notify($callback, &$msg)
{
//获取通知的数据
$xml = $GLOBALS['HTTP_RAW_POST_DATA'];
//如果返回成功则验证签名
try {
$result = WxPayResults::Init($xml);
} catch (WxPayException $e){
$msg = $e->errorMessage();
return false;
}
return call_user_func($callback, $result);
}
/**
*
* 产生随机字符串,不长于32位
* @param int $length
* @return 产生的随机字符串
*/
public static function getNonceStr($length = 32)
{
$chars = "abcdefghijklmnopqrstuvwxyz0123456789";
$str ="";
for ( $i = 0; $i < $length; $i++ ) {
$str .= substr($chars, mt_rand(0, strlen($chars)-1), 1);
}
return $str;
}
/**
* 直接输出xml
* @param string $xml
*/
public static function replyNotify($xml)
{
echo $xml;
}
/**
*
* 上报数据, 上报的时候将屏蔽所有异常流程
* @param string $usrl
* @param int $startTimeStamp
* @param array $data
*/
private static function reportCostTime($url, $startTimeStamp, $data)
{
//如果不需要上报数据
if(WxPayConfig::REPORT_LEVENL == 0){
return;
}
//如果仅失败上报
if(WxPayConfig::REPORT_LEVENL == 1 &&
array_key_exists("return_code", $data) &&
$data["return_code"] == "SUCCESS" &&
array_key_exists("result_code", $data) &&
$data["result_code"] == "SUCCESS")
{
return;
}
//上报逻辑
$endTimeStamp = self::getMillisecond();
$objInput = new WxPayReport();
$objInput->SetInterface_url($url);
$objInput->SetExecute_time_($endTimeStamp - $startTimeStamp);
//返回状态码
if(array_key_exists("return_code", $data)){
$objInput->SetReturn_code($data["return_code"]);
}
//返回信息
if(array_key_exists("return_msg", $data)){
$objInput->SetReturn_msg($data["return_msg"]);
}
//业务结果
if(array_key_exists("result_code", $data)){
$objInput->SetResult_code($data["result_code"]);
}
//错误代码
if(array_key_exists("err_code", $data)){
$objInput->SetErr_code($data["err_code"]);
}
//错误代码描述
if(array_key_exists("err_code_des", $data)){
$objInput->SetErr_code_des($data["err_code_des"]);
}
//商户订单号
if(array_key_exists("out_trade_no", $data)){
$objInput->SetOut_trade_no($data["out_trade_no"]);
}
//设备号
if(array_key_exists("device_info", $data)){
$objInput->SetDevice_info($data["device_info"]);
}
try{
self::report($objInput);
} catch (WxPayException $e){
//不做任何处理
}
}
/**
* 以post方式提交xml到对应的接口url
*
* @param string $xml 需要post的xml数据
* @param string $url url
* @param bool $useCert 是否需要证书,默认不需要
* @param int $second url执行超时时间,默认30s
* @throws WxPayException
*/
private static function postXmlCurl($xml, $url, $useCert = false, $second = 30)
{
$ch = curl_init();
//设置超时
curl_setopt($ch, CURLOPT_TIMEOUT, $second);
//如果有配置代理这里就设置代理
if(WxPayConfig::CURL_PROXY_HOST != "0.0.0.0"
&& WxPayConfig::CURL_PROXY_PORT != 0){
curl_setopt($ch,CURLOPT_PROXY, WxPayConfig::CURL_PROXY_HOST);
curl_setopt($ch,CURLOPT_PROXYPORT, WxPayConfig::CURL_PROXY_PORT);
}
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,TRUE);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,2);//严格校验
//设置header
curl_setopt($ch, CURLOPT_HEADER, FALSE);
//要求结果为字符串且输出到屏幕上
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
if($useCert == true){
//设置证书
//使用证书:cert 与 key 分别属于两个.pem文件
curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
curl_setopt($ch,CURLOPT_SSLCERT, WxPayConfig::SSLCERT_PATH);
curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
curl_setopt($ch,CURLOPT_SSLKEY, WxPayConfig::SSLKEY_PATH);
}
//post提交方式
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
//运行curl
$data = curl_exec($ch);
//返回结果
if($data){
curl_close($ch);
return $data;
} else {
$error = curl_errno($ch);
curl_close($ch);
throw new WxPayException("curl出错,错误码:$error");
}
}
/**
* 获取毫秒级别的时间戳
*/
private static function getMillisecond()
{
//获取毫秒的时间戳
$time = explode ( " ", microtime () );
$time = $time[1] . ($time[0] * 1000);
$time2 = explode( ".", $time );
$time = $time2[0];
return $time;
}
}
... ...
<?php
/**
* 配置账号信息
*/
class WxPayConfig
{
//=======【基本信息设置】=====================================
//
/**
* TODO: 修改这里配置为您自己申请的商户信息
* 微信公众号信息配置
*
* APPID:绑定支付的APPID(必须配置,开户邮件中可查看)
*
* MCHID:商户号(必须配置,开户邮件中可查看)
*
* KEY:商户支付密钥,参考开户邮件设置(必须配置,登录商户平台自行设置)
* 设置地址:https://pay.weixin.qq.com/index.php/account/api_cert
*
* APPSECRET:公众帐号secert(仅JSAPI支付的时候需要配置, 登录公众平台,进入开发者中心可设置),
* 获取地址:https://mp.weixin.qq.com/advanced/advanced?action=dev&t=advanced/dev&token=2005451881&lang=zh_CN
* @var string
*/
const APPID = 'wxf69d1d87d173c899';
const MCHID = '1507884301';
const KEY = 'YkeE7j21vdwqnBYW8FM2Z11O9T4v1kH0';
const APPSECRET = '93c020c51020d87bda1c0bd98b527ff5';
//=======【证书路径设置】=====================================
/**
* TODO:设置商户证书路径
* 证书路径,注意应该填写绝对路径(仅退款、撤销订单时需要,可登录商户平台下载,
* API证书下载地址:https://pay.weixin.qq.com/index.php/account/api_cert,下载之前需要安装商户操作证书)
* @var path
*/
const SSLCERT_PATH = '../cert/apiclient_cert.pem';
const SSLKEY_PATH = '../cert/apiclient_key.pem';
//=======【curl代理设置】===================================
/**
* TODO:这里设置代理机器,只有需要代理的时候才设置,不需要代理,请设置为0.0.0.0和0
* 本例程通过curl使用HTTP POST方法,此处可修改代理服务器,
* 默认CURL_PROXY_HOST=0.0.0.0和CURL_PROXY_PORT=0,此时不开启代理(如有需要才设置)
* @var unknown_type
*/
const CURL_PROXY_HOST = "0.0.0.0";//"10.152.18.220";
const CURL_PROXY_PORT = 0;//8080;
//=======【上报信息配置】===================================
/**
* TODO:接口调用上报等级,默认紧错误上报(注意:上报超时间为【1s】,上报无论成败【永不抛出异常】,
* 不会影响接口调用流程),开启上报之后,方便微信监控请求调用的质量,建议至少
* 开启错误上报。
* 上报等级,0.关闭上报; 1.仅错误出错上报; 2.全量上报
* @var int
*/
const REPORT_LEVENL = 1;
}
... ...