<?php
ini_set('date.timezone','Asia/Shanghai');
/**
* 判断使用的平台是否是微信
*/
function get_platform()
{
if ( strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false )
{
return "is_weixin";
}
else
{
return "not_weixin";
}
}
$weixin_client = get_platform(); //is_weixin not_weixin
if($weixin_client=='is_weixin'){
error_reporting(E_ERROR);
$_SESSION['is_weixin']='is_weixin';
define("APP_TYPE", "jsapi");
}else{
define("APP_TYPE", "app");
}
//require_once "../lib/WxPay.Api.php";
//require_once "WxPay.JsApiPay.php";
require_once(APPPATH."paylib/lib/WxPay.Api.php");
require_once(APPPATH."paylib/demo/WxPay.JsApiPay.php");
//①、获取用户openid
$tools = new JsApiPay();
//获取参数
$attach_value = $_POST['attach']?$_POST['attach']:$_GET['attach']; //其他参数
$body_value = $_POST['body']?$_POST['body']:$_GET['body']; //传输内容
$total_fee_value = $_POST['total_fee']?$_POST['total_fee']:$_GET['total_fee']; //支付的现金金额
$out_trade_no_value = $_POST['out_trade_no']?$_POST['out_trade_no']:$_GET['out_trade_no']; //支付订单号
$success_url = $_POST['success_jump']?$_POST['success_jump']:$_GET['success_jump'];
$fail_url = $_POST['fail_jump']?$_POST['fail_jump']:$_GET['fail_jump'];
$cancel_url = $_POST['cancel_jump']?$_POST['cancel_jump']:$_GET['cancel_jump'];
if($attach_value=='wash_coupon_pay'){
$return_url = "http://www.****.com/xiaoxiv4/index.php?m=wechat&act=wash&detail=washpayment&order_sn=".$out_trade_no_value;
$success_return_url = "http://www.****.com/xiaoxiv4/index.php?m=wechat&act=wash&detail=cardwash_package";
}
if($attach_value=='service_pay'){
$device_type = get_device_type();
//成功回调
$success_return_url = config_item('APP_DOMAIN').'/Wx_store/service_pay_success?order_sn='.$out_trade_no_value.'&get_device_type='.$device_type;
//失败回调
$return_url = config_item('APP_DOMAIN').'/Wx_store/fail_pay_success?order_sn='.$out_trade_no_value.'&get_device_type='.$device_type;
}
//②、统一下单
$input = new WxPayUnifiedOrder();
$input->SetBody($body_value);
$input->SetAttach($attach_value);
$input->SetOut_trade_no($out_trade_no_value);
$input->SetTotal_fee($total_fee_value);
$input->SetTime_start(date("YmdHis"));
$input->SetTime_expire(date("YmdHis", time() + 600));
if($weixin_client=='is_weixin'){
$openId = $tools->GetOpenid();
// $input->SetNotify_url("http://www.xi6666.com/xiaoxiv4/paylib/demo/notify_app_jsapi.php");
$input->SetNotify_url("http://app.xiaoxi6.com/paylib/demo/notify_app_jsapi.php");
$input->SetTrade_type("JSAPI");
$input->SetOpenid($openId);
}else{
// $input->SetNotify_url("http://www.xi6666.com/xiaoxiv4/paylib/demo/notify_app.php");
$input->SetNotify_url(config_item('APP_DOMAIN')."Pay/notify_app");
$input->SetTrade_type("APP");
}
$order = WxPayApi::unifiedOrder($input);
$order['success_url'] = $success_return_url;
$order['fail_url'] = $return_url;
$order['cancel_url'] = $return_url;
if($weixin_client=='is_weixin') {
$jsApiParameters = $tools->GetJsApiParameters($order);
// //获取共享收货地址js函数参数
// $editAddress = $tools->GetEditAddressParameters();
}else{
$jsApiParameters = json_encode($order);
}
$device_type = get_device_type();
/**
* 获取设备类型
*/
?>
<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>
<br/>
<input type="hidden" id="iossumbit">
<script src="http://www.xi6666.com/chexiaoxi/js/public/jquery-1.9.1.min.js"></script>
<script src="http://www.xi6666.com/chexiaoxi/js/jquery-1.9.1.min.js"></script>
<script src="http://www.xi6666.com/chexiaoxi/js/lightbox/js/jquery-1.3.2.min.js"></script>
<script src="http://www.xi6666.com/chexiaoxi/static/partner/js/jquery-2.0.3.js"></script>
</body>
<script type="text/javascript">
var weixin_client = "<?php echo $weixin_client; ?>";
if(weixin_client == 'is_weixin'){
//调用微信JS api 支付
function jsApiCall()
{
WeixinJSBridge.invoke(
'getBrandWCPayRequest',
<?php echo $jsApiParameters; ?>,
function(res){
var order_sn = '<?php echo $out_trade_no_value;?>';
if (res.err_msg == "get_brand_wcpay_request:ok") {
alert('支付成功');
window.location = "<?php echo $success_return_url;?>";
}else if (res.err_msg == "get_brand_wcpay_request:cancel") {
alert('你已取消微信支付');
window.location = "<?php echo $return_url;?>";
}
}
);
}
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();
}
}
callpay();
}else{
var param = '<?php echo $jsApiParameters;?>';
var paramios = <?php echo $jsApiParameters;?>;
var model= "<?php echo $device_type;?>";
if(model=='android'){
window.JsCallAndroid.weChatPay(param);
}else{
window.location.href="ios://wechatpay";
// setTimeout(function(){
// OCModel.pushWeCharPay(paramios);
// },3500);
}
}
function ioswechatpay()
{
var paramios = <?php echo $jsApiParameters;?>;
return paramios;
}
</script>
</html>
2.ci_core.php文件代码
<?php
/**
* @desc CI配置项开发环境和正式环境常量定义index.php是项目入口文件
*/
define('ENVIRONMENT', isset($_SERVER['CI_ENV']) ? $_SERVER['CI_ENV'] : 'production');
//define('ENVIRONMENT', 'development');
switch (ENVIRONMENT)
{
case 'development':
error_reporting(-1);
ini_set('display_errors', 1);
break;
case 'testing':
case 'production':
ini_set('display_errors', 0);
if (version_compare(PHP_VERSION, '5.3', '>='))
{
error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT & ~E_USER_NOTICE & ~E_USER_DEPRECATED);
}
else
{
error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT & ~E_USER_NOTICE);
}
break;
default:
header('HTTP/1.1 503 Service Unavailable.', TRUE, 503);
echo 'The application environment is not set correctly.';
exit(1); // EXIT_ERROR
}
/**
*定义项目路径
*/
$system_path = '../../../system';
$application_folder = '../../../msapp';
$view_folder = '';
/**
* @desc 项目cli模式
*/
if (defined('STDIN'))
{
chdir(dirname(__FILE__));
}
/**
* @desc 定义系统路径分window和linux判断
*/
if (($_temp = realpath($system_path)) !== FALSE)
{
$system_path = $_temp.DIRECTORY_SEPARATOR;
}
else
{
// Ensure there's a trailing slash
$system_path = strtr(
rtrim($system_path, '/\\'),
'/\\',
DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR
).DIRECTORY_SEPARATOR;
}
// Is the system path correct?
if ( ! is_dir($system_path))
{
header('HTTP/1.1 503 Service Unavailable.', TRUE, 503);
echo 'Your system folder path does not appear to be set correctly. Please open the following file and correct this: '.pathinfo(__FILE__, PATHINFO_BASENAME);
exit(3); // EXIT_CONFIG
}
/*
* -------------------------------------------------------------------
* Now that we know the path, set the main path constants
* -------------------------------------------------------------------
*/
// The name of THIS file
define('SELF', pathinfo(__FILE__, PATHINFO_BASENAME));
// Path to the system directory
define('BASEPATH', $system_path);
// Path to the front controller (this file) directory
define('FCPATH', dirname(__FILE__).DIRECTORY_SEPARATOR);
// Name of the "system" directory
define('SYSDIR', basename(BASEPATH));
// The path to the "application" directory
if (is_dir($application_folder))
{
if (($_temp = realpath($application_folder)) !== FALSE)
{
$application_folder = $_temp;
}
else
{
$application_folder = strtr(
rtrim($application_folder, '/\\'),
'/\\',
DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR
);
}
}
elseif (is_dir(BASEPATH.$application_folder.DIRECTORY_SEPARATOR))
{
$application_folder = BASEPATH.strtr(
trim($application_folder, '/\\'),
'/\\',
DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR
);
}
else
{
header('HTTP/1.1 503 Service Unavailable.', TRUE, 503);
echo 'Your application folder path does not appear to be set correctly. Please open the following file and correct this: '.SELF;
exit(3); // EXIT_CONFIG
}
define('APPPATH', $application_folder.DIRECTORY_SEPARATOR);
// The path to the "views" directory
if ( ! isset($view_folder[0]) && is_dir(APPPATH.'views'.DIRECTORY_SEPARATOR))
{
$view_folder = APPPATH.'views';
}
elseif (is_dir($view_folder))
{
if (($_temp = realpath($view_folder)) !== FALSE)
{
$view_folder = $_temp;
}
else
{
$view_folder = strtr(
rtrim($view_folder, '/\\'),
'/\\',
DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR
);
}
}
elseif (is_dir(APPPATH.$view_folder.DIRECTORY_SEPARATOR))
{
$view_folder = APPPATH.strtr(
trim($view_folder, '/\\'),
'/\\',
DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR
);
}
else
{
header('HTTP/1.1 503 Service Unavailable.', TRUE, 503);
echo 'Your view folder path does not appear to be set correctly. Please open the following file and correct this: '.SELF;
exit(3); // EXIT_CONFIG
}
/*
* --------------------------------------------------------------------
* LOAD THE BOOTSTRAP FILE
* --------------------------------------------------------------------
*
* And away we go...
*/
if (file_exists(APPPATH.'config/'.ENVIRONMENT.'/constants.php'))
{
require_once(APPPATH.'config/'.ENVIRONMENT.'/constants.php');
}
require_once(APPPATH.'config/constants.php');
/*
* ------------------------------------------------------
* Load the global functions
* ------------------------------------------------------
*/
require_once(BASEPATH.'core/Common.php');
require_once(BASEPATH.'core/Function.php');
/*
* ------------------------------------------------------
* Security procedures
* ------------------------------------------------------
*/
if ( ! is_php('5.4'))
{
ini_set('magic_quotes_runtime', 0);
if ((bool) ini_get('register_globals'))
{
$_protected = array(
'_SERVER',
'_GET',
'_POST',
'_FILES',
'_REQUEST',
'_SESSION',
'_ENV',
'_COOKIE',
'GLOBALS',
'HTTP_RAW_POST_DATA',
'system_path',
'application_folder',
'view_folder',
'_protected',
'_registered'
);
$_registered = ini_get('variables_order');
foreach (array('E' => '_ENV', 'G' => '_GET', 'P' => '_POST', 'C' => '_COOKIE', 'S' => '_SERVER') as $key => $superglobal)
{
if (strpos($_registered, $key) === FALSE)
{
continue;
}
foreach (array_keys($$superglobal) as $var)
{
if (isset($GLOBALS[$var]) && ! in_array($var, $_protected, TRUE))
{
$GLOBALS[$var] = NULL;
}
}
}
}
}
/*
* ------------------------------------------------------
* Define a custom error handler so we can log PHP errors
* ------------------------------------------------------
*/
//set_error_handler('_error_handler');
//set_exception_handler('_exception_handler');
//register_shutdown_function('_shutdown_handler');
/*
* ------------------------------------------------------
* Set the subclass_prefix
* ------------------------------------------------------
*
* Normally the "subclass_prefix" is set in the config file.
* The subclass prefix allows CI to know if a core class is
* being extended via a library in the local application
* "libraries" folder. Since CI allows config items to be
* overridden via data set in the main index.php file,
* before proceeding we need to know if a subclass_prefix
* override exists. If so, we will set this value now,
* before any classes are loaded
* Note: Since the config file data is cached it doesn't
* hurt to load it here.
*/
if ( ! empty($assign_to_config['subclass_prefix']))
{
get_config(array('subclass_prefix' => $assign_to_config['subclass_prefix']));
}
/*
* ------------------------------------------------------
* Should we use a Composer autoloader?
* ------------------------------------------------------
*/
if ($composer_autoload = config_item('composer_autoload'))
{
if ($composer_autoload === TRUE)
{
file_exists(APPPATH.'vendor/autoload.php')
? require_once(APPPATH.'vendor/autoload.php')
: log_message('error', '$config[\'composer_autoload\'] is set to TRUE but '.APPPATH.'vendor/autoload.php was not found.');
}
elseif (file_exists($composer_autoload))
{
require_once($composer_autoload);
}
else
{
log_message('error', 'Could not find the specified $config[\'composer_autoload\'] path: '.$composer_autoload);
}
}
/*
* ------------------------------------------------------
* Start the timer... tick tock tick tock...
* ------------------------------------------------------
*/
//$BM =& load_class('Benchmark', 'core');
//$BM->mark('total_execution_time_start');
//$BM->mark('loading_time:_base_classes_start');
/*
* ------------------------------------------------------
* Instantiate the hooks class
* ------------------------------------------------------
*/
//$EXT =& load_class('Hooks', 'core');
/*
* ------------------------------------------------------
* Is there a "pre_system" hook?
* ------------------------------------------------------
*/
//$EXT->call_hook('pre_system');
/*
* ------------------------------------------------------
* Instantiate the config class
* ------------------------------------------------------
*
* Note: It is important that Config is loaded first as
* most other classes depend on it either directly or by
* depending on another class that uses it.
*
*/
$CFG =& load_class('Config', 'core');
// Do we have any manually set config items in the index.php file?
if (isset($assign_to_config) && is_array($assign_to_config))
{
foreach ($assign_to_config as $key => $value)
{
$CFG->set_item($key, $value);
}
}
/*
* ------------------------------------------------------
* Important charset-related stuff
* ------------------------------------------------------
*
* Configure mbstring and/or iconv if they are enabled
* and set MB_ENABLED and ICONV_ENABLED constants, so
* that we don't repeatedly do extension_loaded() or
* function_exists() calls.
*
* Note: UTF-8 class depends on this. It used to be done
* in it's constructor, but it's _not_ class-specific.
*
*/
$charset = strtoupper(config_item('charset'));
ini_set('default_charset', $charset);
if (extension_loaded('mbstring'))
{
define('MB_ENABLED', TRUE);
// mbstring.internal_encoding is deprecated starting with PHP 5.6
// and it's usage triggers E_DEPRECATED messages.
@ini_set('mbstring.internal_encoding', $charset);
// This is required for mb_convert_encoding() to strip invalid characters.
// That's utilized by CI_Utf8, but it's also done for consistency with iconv.
mb_substitute_character('none');
}
else
{
define('MB_ENABLED', FALSE);
}
// There's an ICONV_IMPL constant, but the PHP manual says that using
// iconv's predefined constants is "strongly discouraged".
if (extension_loaded('iconv'))
{
define('ICONV_ENABLED', TRUE);
// iconv.internal_encoding is deprecated starting with PHP 5.6
// and it's usage triggers E_DEPRECATED messages.
@ini_set('iconv.internal_encoding', $charset);
}
else
{
define('ICONV_ENABLED', FALSE);
}
if (is_php('5.6'))
{
ini_set('php.internal_encoding', $charset);
}
/*
* ------------------------------------------------------
* Load compatibility features
* ------------------------------------------------------
*/
require_once(BASEPATH.'core/compat/mbstring.php');
require_once(BASEPATH.'core/compat/hash.php');
require_once(BASEPATH.'core/compat/password.php');
require_once(BASEPATH.'core/compat/standard.php');
/*
* ------------------------------------------------------
* Instantiate the UTF-8 class
* ------------------------------------------------------
*/
$UNI =& load_class('Utf8', 'core');
/*
* ------------------------------------------------------
* Instantiate the URI class
* ------------------------------------------------------
*/
$URI =& load_class('URI', 'core');
/*
* ------------------------------------------------------
* Instantiate the routing class and set the routing
* ------------------------------------------------------
*/
//$RTR =& load_class('Router', 'core', isset($routing) ? $routing : NULL);
/*
* ------------------------------------------------------
* Instantiate the output class
* ------------------------------------------------------
*/
$OUT =& load_class('Output', 'core');
/*
* ------------------------------------------------------
* Is there a valid cache file? If so, we're done...
* ------------------------------------------------------
*/
//if ($EXT->call_hook('cache_override') === FALSE && $OUT->_display_cache($CFG, $URI) === TRUE)
//{
// exit;
//}
/*
* -----------------------------------------------------
* Load the security class for xss and csrf support
* -----------------------------------------------------
*/
$SEC =& load_class('Security', 'core');
/*
* ------------------------------------------------------
* Load the Input class and sanitize globals
* ------------------------------------------------------
*/
$IN =& load_class('Input', 'core');
/*
* ------------------------------------------------------
* Load the Language class
* ------------------------------------------------------
*/
$LANG =& load_class('Lang', 'core');
/*
* ------------------------------------------------------
* Load the app controller and local controller
* ------------------------------------------------------
*
*/
// Load the base controller class
require_once BASEPATH.'core/Controller.php';
/**
* Reference to the CI_Controller method.
*
* Returns current CI instance object
*
* @return CI_Controller
*/
function &get_instance()
{
return CI_Controller::get_instance();
}
if (file_exists(APPPATH.'core/'.$CFG->config['subclass_prefix'].'Controller.php'))
{
require_once APPPATH.'core/'.$CFG->config['subclass_prefix'].'Controller.php';
}
3.微信回调处理,回调中加载ci框架的核心文件。
<?php
ini_set('date.timezone','Asia/Shanghai');
error_reporting(E_ERROR);
/**
* 判断使用的平台是否是微信
*/
require_once "ci_core.php";
define("APP_TYPE", "jsapi");
define('IN_ECS', true);
//回调封装
class notify_app extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->database();
// $this->load->library("session");
// $this->load->helper('url');
$this->load->model('Pay_model','pay');
$this->model_include('Lib_jiameng_order','payment');
$this->model_include('Lib_oil_order','oilpay');
$this->model_include('Lib_wash_coupon_order','wash');
}
//加载includes文件夹下面文件
public function model_include($file,$name,$dir='includes')
{
$this->load->model($file,$name,false,$dir);
}
/**商城回调
* @author xiexingqiao
* @param $order_sn 订单号
* @param $attach
* @param $flow_sn 微信流水号
* @param $total_fee 总金额 以元计算
* @param $pay_channel 支付渠道
* @param $pay_name 支付名称
*/
public function shop_pay_success($order_sn,$attach,$flow_sn,$total_fee,$pay_channel,$pay_name)
{
$this->db->trans_start();
$ret = $this->pay->shop_pay_success($order_sn,$attach,$flow_sn,$total_fee,$pay_channel,$pay_name);
$this->db->trans_complete();
echo json_encode($ret);
}
public function service_pay_success($order_sn,$attach,$flow_sn,$total_fee,$pay_channel,$pay_name)
{
$this->db->trans_start();
$ret = $this->pay->serivce_pay_success($order_sn,$attach,$flow_sn,$total_fee,$pay_channel,$pay_name);
$this->db->trans_complete();
echo json_encode($ret);
}
}
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;
}
$transaction_id = $data["transaction_id"];
if($data['attach']=='shop_pay')
{
//商城支付
$order_sn = $data['out_trade_no'];
$attach = 'shop_pay';
$flow_sn=$transaction_id;
$total_fee=$data['total_fee']/100;
$pay_channel ='weixinapp';
$pay_name = '微信支付';
$notify_obj = new notify_app();
$notify_obj->shop_pay_success($order_sn,$attach,$flow_sn,$total_fee,$pay_channel,$pay_name);
}elseif ($data['attach']=='service_pay')
{
$order_sn = $data['out_trade_no'];
$attach = 'service_pay';
$flow_sn=$transaction_id;
$total_fee=$data['total_fee']/100;
$pay_channel ='weixinapp';
$pay_name = '微信支付';
$notify_obj = new notify_app();
$notify_obj->service_pay_success($order_sn,$attach,$flow_sn,$total_fee,$pay_channel,$pay_name);
}
//order_paid($order_sn, 2, APP_TYPE);
Log::DEBUG("NotifyProcess true");
return true;
}
}
Log::DEBUG("begin notify");
$notify = new PayNotifyCallBack();
$notify->Handle(false);