<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class IPayLinksService extends CI_Controller
{
public $gatewayUrl;
public $pay_info_arr = array();
public $query_info_arr = array();
public $order_info_arr = array();
public $card_info_arr = array();
public $return_url;
public $notify_url;
// cht
public function __construct(){
parent::__construct();
$this->config->load('iPayLinks');
// $this->config->load('dev_iPayLinks'); // test
$this->load->model('IPayLinks_model');
$this->load->model('Note_model');
$this->load->model('Online_payment_account_model', 'payment_model');
$this->gatewayUrl = $this->config->item('gatewayUrl');
$this->queryUrl = $this->config->item('queryUrl');
$this->return_url = $this->config->item('returnUrl');
$this->notify_url = $this->config->item('noticeUrl');
$this->pay_info_arr['version'] = $this->query_info_arr['version'] = $this->config->item('version');
$this->pay_info_arr['partnerId'] = $this->query_info_arr['partnerId'] = "10000004000";
// $this->pay_info_arr['partnerId'] = $this->query_info_arr['partnerId'] = $this->config->item('partnerId');
$this->pay_info_arr['charset'] = $this->query_info_arr['charset'] = $this->config->item('charset');
$this->pay_info_arr['signType'] = $this->query_info_arr['signType'] = $this->config->item('signType');
$this->pay_info_arr['siteId'] = $this->config->item('siteId');
$this->pay_info_arr['tradeType'] = $this->config->item('tradeType');
$this->pay_info_arr['borrowingMarked'] = $this->config->item('borrowingMarked');
$this->pay_info_arr['noticeUrl'] = $this->config->item('noticeUrl');
$this->pay_info_arr['mcc'] = $this->config->item('mcc');
$this->pay_info_arr['payType'] = $this->config->item('payType');
$this->pay_info_arr['payMode'] = $this->config->item('payMode');
$this->pay_info_arr['currencyCode'] = $this->config->item('currencyCode');
$this->query_info_arr['mode'] = $this->config->item('query_mode');
$this->query_info_arr['type'] = $this->config->item('query_type');
if(empty($this->pay_info_arr['partnerId'])||trim($this->pay_info_arr['partnerId'])==""){
throw new Exception("partnerId should not be NULL!");
}
if(empty($this->pay_info_arr['siteId'])||trim($this->pay_info_arr['siteId'])==""){
throw new Exception("siteId should not be NULL!");
}
}
public function index()
{
$this->note_list();
}
public function note_list2()
{
$this->permission->is_admin(true);
$data = array();
$data["paytext"] = $this->payment_status();
$data["keywords"] = $this->input->get_post("keywords");
$data["date"] = $this->input->get_post("date");
empty($data['date']) ? $data['date'] = date('Y-m-d') : false;
if (!empty($data['keywords'])) {
$data['notelist'] = $this->Note_model->search_key($data['keywords']);
} else {
$data['notelist'] = $this->Note_model->search_date($data['date']);
}
$this->load->view("iPayLinks_list",$data);
return;
}
public function note_list()
{
$this->permission->is_admin(true);
$data = array();
$data["paytext"] = $this->payment_status();
$data["keywords"] = $this->input->get_post("keywords");
$data["date"] = $this->input->get_post("date");
empty($data['date']) ? $data['date'] = date('Y-m-d') : false;
if (!empty($data['keywords'])) {
$data['notelist'] = $this->Note_model->search_key2($data['keywords']);
} else {
$data['notelist'] = $this->Note_model->search_date2($data['date']);
}
$this->load->view("iPayLinks_list2",$data);
return;
}
//失败记录列表
public function note_faillist() {
$this->permission->is_admin(true);
$data = array();
$data["paytext"] = $this->payment_status();
//有关键词则不限制日期
$data['search_key'] = $this->input->post('keywords');
$data['date'] = $this->input->get_post('date');
empty($data['date']) ? $data['date'] = date('Y-m-d') : false;
$data['notelist'] = $this->Note_model->failnote(100);
$this->load->view("iPayLinks_list",$data);
}
public function get_url_string()
{
$param = ($this->input->get_post('param'));
return base64_decode($param);
}
/*!
* 跳转到信用卡信息页面,包含订单信息
* @author LYT < lyt @ hainatravel . com >
* @date 2017-08-11
*/
public function order_info()
{
$param = $this->input->get_post("param");
$data['form_html'] = "< input type = 'hidden' name = 'param' value = '".$param."' > ";
$data['year_html'] = "";
$this_year = date('Y');
for ($i=0; $i < 10 ; $ i + + ) {
$data['year_html'] .= "< option value = '".($this_year+$i)."' > ".($this_year+$i)."< / option > ";
}
$data['month_html'] = "";
for ($i=1; $i < 13 ; $ i + + ) {
$data['month_html'] .= "< option value = '".($i)."' > ".($i)."< / option > ";
}
$this->get_order_info();
$data['description'] = $param_arr = str_replace("\n", "< br > ", $this->order_info_arr['goodsDesc']) ;
bcscale(2);
$data['amount'] = strval(bcdiv($this->order_info_arr['orderAmount'], 100));
$data['currencyCode'] = $this->pay_info_arr['currencyCode'];
$data['orderId'] = $this->order_info_arr['orderId'];
$this->load->view("iPayLinks_index",$data);
}
/*!
* 跳转到付款结束页面
* @author LYT < lyt @ hainatravel . com >
* @date 2017-08-17
* @param array $data 付款结果信息
*/
public function order_done($data=NULL)
{
if (empty($data)) {
$data["code"] = 1;
$data["msg"] = "Unknow request";
$data["error_code"] = "Unknow";
}
$url_query = "";
foreach ($data as $key => $v) {
$url_query .= $key . "=" . urlencode($v) ."&";
}
redirect($this->return_url . "?" . substr($url_query, 0, -1));
}
public function load_return()
{
$data["code"] = $this->input->get_post("code");
$data["msg"] = $this->input->get_post("msg");
$data["error_code"] = $this->input->get_post("error_code");
$this->load->view("iPayLinks_rep",$data);
}
/*!
* 接收订单信息
* @author LYT < lyt @ hainatravel . com >
* @date 2017-08-11
*/
public function get_order_info()
{
$param_string = $this->get_url_string();
@parse_str($param_string, $param_arr);
if ( ! $param_string || empty($param_arr['order_id'])) {
$this->order_done();
return false;
}
$this->order_info_arr['orderId'] = $this->order_info_arr['deviceFingerprintId'] = trim($param_arr['order_id']);
$this->order_info_arr['goodsName'] = trim($param_arr['goods_name']);
$this->order_info_arr['goodsDesc'] = trim($param_arr['goods_desc']);
// 两位小数去掉小数点;
// 1.00 USD => 100
bcscale(0);
$this->order_info_arr['orderAmount'] = intval(bcmul(floatval(trim($param_arr['order_amount'])), 100));
$this->order_info_arr['customerIP'] = $this->input->ip_address();
$this->order_info_arr['submitTime'] = date('YmdHis');
$this->pay_info_arr['currencyCode'] = !empty($param_arr['currency']) ? trim($param_arr['currency']) : $this->config->item('currencyCode');
$this->return_url = !empty($param_arr['return_url']) ? trim($param_arr['return_url']) : $this->return_url;
$this->notify_url = !empty($param_arr['notify_url']) ? trim($param_arr['notify_url']) : $this->notify_url;
if ($this->notify_url) {
$this->pay_info_arr['noticeUrl'] = $this->notify_url ;
}
}
public function get_card_info()
{
$this->card_info_arr['cardHolderNumber'] = trim(str_replace(" ", "", $this->input->get_post('cardHolderNumber')));
$this->card_info_arr['cardHolderFirstName'] = trim($this->input->get_post('cardHolderFirstName'));
$this->card_info_arr['cardHolderLastName'] = trim($this->input->get_post('cardHolderLastName'));
$this->card_info_arr['cardExpirationMonth'] = trim($this->input->get_post('cardExpirationMonth'));
$this->card_info_arr['cardExpirationMonth'] = $this->card_info_arr['cardExpirationMonth'] > 9 ? $this->card_info_arr['cardExpirationMonth'] : "0".$this->card_info_arr['cardExpirationMonth'];
$this->card_info_arr['cardExpirationYear'] = substr(trim($this->input->get_post('cardExpirationYear')),2,2);
$this->card_info_arr['securityCode'] = trim(str_replace(" ","",$this->input->get_post('securityCode')));
$this->card_info_arr['cardHolderEmail'] = trim($this->input->get_post('cardHolderEmail'));
// 记录付款人联系信息
$card_holder_arr = array(
"n" => substr($this->card_info_arr['cardHolderFirstName']." ".$this->card_info_arr['cardHolderLastName'],0,50),
"e" => substr($this->card_info_arr['cardHolderEmail'],0,50)
);
$this->card_info_arr['remark'] = json_encode($card_holder_arr);
}
public function order_pay()
{
$this->get_order_info();
$this->get_card_info();
$form_request = array_merge($this->pay_info_arr,$this->card_info_arr,$this->order_info_arr);
$form_request['signMsg'] = $this->generate_sign($form_request);
$resp = $this->curl($this->gatewayUrl,$form_request);
$respWellFormed = $this->verify_sign($resp);
// 未得到结果
if (false === $respWellFormed->data) {
$this->order_done();
return;
}
// test
// $this->ipaylinks_notice($resp);
// 返回结果
$ret = $this->result_2_return_url($respWellFormed->data->resultCode,$respWellFormed->data->resultMsg);
$this->order_done($ret);
return;
}
/*!
* 主动查询完成的交易
* 得到结果后进行入库处理,包括失败的交易
* @author LYT < lyt @ hainatravel . com >
* @date 2017-08-29
* @param Object $respObject 交易完成得到的xml Object
*/
public function query_pay_result($respObject)
{
$this->query_info_arr["queryOrderId"] = $this->create_guid();
$this->query_info_arr["orderId"] = $respObject->orderId;
$this->query_info_arr["beginTime"] = $respObject->acquiringTime;
$this->query_info_arr["endTime"] = $respObject->completeTime;
$this->query_info_arr["signMsg"] = $this->generate_sign($this->query_info_arr);
$resp = $this->curl($this->queryUrl,$this->query_info_arr);
$query_resp = $this->verify_sign($resp);
// 未得到结果
if (false === $query_resp->data) {
$this->order_done();
return;
}
// 查询到交易结果的写入记录
$this->iPayLinks_log($query_resp);
// test
// log_message('error',"\n---------------------------------end--------------------------------\n\n\n");
return;
}
public function query_pay($orderid=NULL, $output=true)
{
$this->query_info_arr["queryOrderId"] = $this->create_guid();
$this->query_info_arr["orderId"] = $orderid;
$this->query_info_arr["mode"] = 1;
// $this->query_info_arr["type"] = $day_offset; // 1-支付;2-退款
$this->query_info_arr["signMsg"] = $this->generate_sign($this->query_info_arr);
$resp = $this->curl($this->queryUrl,$this->query_info_arr);
$resp_obj = simplexml_load_string($resp);
if ($output !== true) {
return $resp_obj->details;
}
return $this->output->set_content_type('application/json')->set_output(json_encode(simplexml_load_string($resp)));
}
public function query_refund($refund_order_id)
{
$this->query_info_arr["queryOrderId"] = $this->create_guid();
$this->query_info_arr["orderId"] = $refund_order_id;
$this->query_info_arr['mode'] = '1';
$this->query_info_arr['type'] = '2';
$this->query_info_arr["signMsg"] = $this->generate_sign($this->query_info_arr);
$resp = $this->curl($this->queryUrl,$this->query_info_arr);
$resp_obj = simplexml_load_string($resp);
$this->output->set_content_type('application/json')->set_output(json_encode(simplexml_load_string($resp)));
return;
}
public function query_pay_list($day_offset = 3)
{
$this->query_info_arr["queryOrderId"] = $this->create_guid();
$this->query_info_arr["beginTime"] = date('YmdHis',strtotime("-$day_offset days"));
$this->query_info_arr["endTime"] = date('YmdHis235959');
$this->query_info_arr["mode"] = 2;
$this->query_info_arr["type"] = 1; // 1-支付;2-退款
$this->query_info_arr["signMsg"] = $this->generate_sign($this->query_info_arr);
$resp = $this->curl($this->queryUrl,$this->query_info_arr);
$resp_obj = simplexml_load_string($resp);
// foreach ($resp_obj->details->detail as $key => $query_order) {
// $order = new stdClass();
// $order->check = true;
// $order->data = $query_order;
// $this->ipaylinks_notice($order);
// }
$this->output->set_content_type('application/json')->set_output(json_encode(simplexml_load_string($resp)));
return;
}
/*!
* 订单业务处理
* * 查询写入交易记录 iPayLinks_log
* * 异步通知更新 iPayLinks_log
* * 邮件通知外联 定时处理
* * 更新订单收款状态
*/
/*!
* 根据查询得到的结果入库
* 支付订单,单笔查询
* @author LYT < lyt @ hainatravel . com >
* @date 2017-08-29
* @param ArrayObject $query_resp->check 验签结果 [boolean]
* $query_resp->data 查询得到的交易结果 [SimpleXMLElement Object]
*/
public function iPayLinks_log($query_resp)
{
bcscale(2);
$detail = $query_resp->data->details->detail;
if (true === $this->if_note_exists($detail->dealId)) {
// 已存在记录,更新stateCode,payAmount,payer,payerEmail
$this->Note_model->update_query(
strval($detail->dealId),
strval($detail->stateCode),
strval(bcdiv(floatval($detail->payAmount), 100) )
);
return false;
}
}
public function if_note_exists($dealId)
{
return $this->Note_model->note_exists($dealId) ? true : false;
}
/*!
* 邮件外联
* @author LYT < lyt @ hainatravel . com >
* @date 2017-08-29
* @param string $orderid 订单号
*/
public function batch_send_note($pn_txn_id = false, $old_ssje=NULL, $pn_id=NULL)
{
$data = array();
$int = 0;
//优先处理指定的交易号,用于修正交易号直接发送通知
if ( ! empty($pn_txn_id)) {
$data['unsend_list'] = array($this->Note_model->note($pn_txn_id, $pn_id));
}
// 待处理的
if (empty($data['unsend_list'])) {
$data['unsend_list'] = $this->Note_model->unsend(10);
}
//没有未处理的数据再查找处理失败的数据
if (empty($data['unsend_list'])) {
$data['unsend_list'] = $this->Note_model->failnote(20);
}
$handpick = empty($pn_txn_id) ? false : true;
$show_index = 0;
foreach ($data['unsend_list'] as $item) {
//已经发送的不处理,防止重复发送
if ($item->IPL_sent == 'send' & & empty($pn_txn_id)) {
continue;
}
//退款状态默认为已经处理,陆燕在退款前手动通知外联了,系统跳过处理
if ($item->IPL_payType == 'refund') {
$this->send_refund($item, $old_ssje, $handpick);
// $this->Note_model->update_send($item->IPL_dealId, 'send');
continue;
}
//只处理完成状态,其他状态由陆燕处理
if (strcmp(trim($item->IPL_resultCode), "0000") !== 0 ) {
$this->Note_model->update_send($item->IPL_dealId, 'sendfail');
continue;
}
//检测是否是APP订单,默认不处理
// if ((strpos($item->pn_memo, 'China Train Booking') !== false) || (strpos($item->pn_memo, 'ChinaTrainBooking') !== false)) { //APP自动出票的订单不需要处理
// $this->Note_model->update_send($item->IPL_dealId, 'send');
// continue;
// }
//根据note信息找到订单号
$orderid_info = $this->analysis_orderid($item->IPL_orderId);
//找不到订单号,设置为发送失败标示
if (empty($orderid_info)) {
$this->Note_model->update_send($item->IPL_dealId, 'sendfail');
continue;
}
//根据订单号查找外联信息
$orderid_info = json_decode($orderid_info);
$advisor_info = $this->IPayLinks_model->get_order($orderid_info->orderid, false, $orderid_info->ordertype, $handpick);
//查不到订单信息
if (empty($advisor_info)) {
$this->Note_model->update_send($item->IPL_dealId, 'sendfail');
continue;
}
//更新正确的订单信息到记录中,以这个为主
$this->Note_model->set_invoice($item->IPL_dealId, $orderid_info->orderid . '_' . $orderid_info->ordertype);
//检测是否是APP订单,默认不处理
// if ($orderid_info->ordertype == 'A') { //APP自动出票的订单不需要处理
// $this->Note_model->update_send($item->IPL_dealId, 'send');
// continue;
// }
//添加支付信息入库
//没有分配订单之前先添加付款记录,这个过程可能会执行多次,必须在添加记录前查找是否有数据
if (!empty($orderid_info)) {
$currencyCode = str_replace("CNY", "RMB", trim(mb_strtoupper($item->IPL_currencyCode)));
$ssje = $this->IPayLinks_model->get_ssje($item->IPL_orderAmount, $currencyCode);
$ssje = $old_ssje===NULL ? $ssje : $old_ssje;
$USD_amount = $this->IPayLinks_model->get_USD($item->IPL_orderAmount, $currencyCode);
//更新还没有填的客邮和交易号de收款记录( 商务订单)
if (isset($advisor_info->order_type) & & $advisor_info->order_type == 0) {
$ht_memo = '交易号(自动录入):' . $item->IPL_dealId;
$GAI_COLI_SN = isset($advisor_info->COLI_SN) ? $advisor_info->COLI_SN : 0;
//CHTAPP订单添加记录前判断是否有记录, 以前的APP版本没有交易号, 只能拿金额来判断
if (substr($advisor_info->COLI_WebCode, 0, 6) == 'CHTAPP' & & strstr($advisor_info->COLI_WebCode, "-") != '-biz') {
//只判断前6位字符, CHTAPP-fr CHTAPP-jp等各语种都属于APP订单
$this->IPayLinks_model->add_account_info_forAPP(
$GAI_COLI_SN,
$advisor_info->COLI_ID,
$item->IPL_orderAmount,
$item->IPL_completeTime,
$currencyCode,
$ssje,
$item->IPL_completeTime,
$item->IPL_completeTime,
$item->IPL_acquiringTime,
$item->IPL_payerName,
$item->IPL_payerEmail,
$item->IPL_dealId,
$ht_memo);
if ($advisor_info->COLI_WebCode == 'CHTAPP' & & $advisor_info->COLI_State == 11) {
//只修改APP组的订单状态, 并且订单进度是我的订单
$this->IPayLinks_model->update_biz_coli_state($GAI_COLI_SN, 8); //把订单状态改为已付款
$this->IPayLinks_model->insert_biz_order_log($GAI_COLI_SN, 'BS8');
}
} else {
// 把订单状态设置为13-新订单已支付
if (false == $this->IPayLinks_model->if_biz_gai_exists($item->IPL_dealId) ) {
$this->IPayLinks_model->update_biz_coli_state($GAI_COLI_SN, 13);
$this->IPayLinks_model->insert_biz_order_log($GAI_COLI_SN, 'BS13');
}
$this->IPayLinks_model->add_account_info(
$GAI_COLI_SN,
$advisor_info->COLI_ID,
$item->IPL_orderAmount,
$item->IPL_completeTime,
$currencyCode,
$USD_amount,
$ssje,
$item->IPL_completeTime,
$item->IPL_completeTime,
$item->IPL_acquiringTime,
$item->IPL_payerName,
$item->IPL_payerEmail,
$item->IPL_dealId,
$ht_memo
);
// 更新订单主表付款方式,防止没访问thankyou-train.asp
if (empty($advisor_info->COLI_PayManner)) {
$this->IPayLinks_model->update_paymanner($GAI_COLI_SN);
}
}
}
//更新还没有填的客邮和交易号de收款记录( 传统订单)
elseif (isset($advisor_info->order_type) & & $advisor_info->order_type == 1) {
$ht_memo = '交易号(自动录入):' . $item->IPL_dealId;
$GAI_COLI_SN = isset($advisor_info->COLI_SN) ? $advisor_info->COLI_SN : 0;
$gai_sn = $this->IPayLinks_model->add_tour_account_info(
$GAI_COLI_SN,
$item->IPL_orderAmount,
$item->IPL_acquiringTime,
$currencyCode,
$ssje,
$item->IPL_completeTime,
$item->IPL_completeTime,
$item->IPL_acquiringTime,
$item->IPL_payerName,
$item->IPL_payerEmail,
$item->IPL_dealId,
$ht_memo
);
//添加汉特的订单提醒
$this->IPayLinks_model->update_coli_introduction($GAI_COLI_SN, '已支付 ' . mb_strtoupper($item->IPL_currencyCode) . $item->IPL_orderAmount);
// 添加HT任务
$this->IPayLinks_model->exec_addToTask($gai_sn);
}
}
$opi_email = !empty($advisor_info->OPI_Email) ? $advisor_info->OPI_Email : ''; //lussie@chinahighlights.net
$opi_firstname = !empty($advisor_info->OPI_FirstName) ? $advisor_info->OPI_FirstName : !empty($advisor_info->OPI_Name) ? $advisor_info->OPI_Name : ''; //lussie
if ($opi_email===''
& & in_array(strtoupper($advisor_info->COLI_WebCode), array('CHTAPP-JA', 'JP'))
) {
$opi_email = 'contact@arachina.com';
$opi_firstname = 'contact@arachina.com';
}
//没有外联信息表示订单未分配
if (empty($opi_email) || empty($opi_firstname)) {
$this->Note_model->update_send($item->IPL_dealId, 'sendfail');
continue;
}
//添加邮件发送记录
$fromName = 'iPayLinks';
$fromEmail = '';
// 1.给外联发送通知邮件
$toName = !empty($opi_firstname) ? $opi_firstname : '';
$toEmail = !empty($opi_email) ? $opi_email : '';
$subject = $orderid_info->orderid . '_' . $orderid_info->ordertype . ' / ' . $item->IPL_orderAmount . $item->IPL_currencyCode . ' / ' . $fromName;
$body = $this->load->view('receipt_mail', $item, true);
$M_RelatedInfo = $item->IPL_sn;
$M_AddTime = $item->IPL_completeTime;
$M_State = 0;
$this->IPayLinks_model->save_automail($fromName, $fromEmail, $toName, $toEmail, $subject, $body, $M_RelatedInfo, $M_State, $M_AddTime, 'iPayLinks note');
// 2.给客人发邮件,通知账单
if (empty($pn_txn_id)) {
$toName2 = !empty($item->IPL_payerName) ? $item->IPL_payerName : '';
$toEmail2 = !empty($item->IPL_payerEmail) ? $item->IPL_payerEmail : '';
// Zac170919039_T( 订单号) / 996.00USD / iPayLinks
$subject2 = $orderid_info->orderid . '_' . $orderid_info->ordertype . ' / ' . $item->IPL_orderAmount . $item->IPL_currencyCode . ' / China Highlights';
// lang
$remark_info = json_decode($item->IPL_memo);
(isset($remark_info->remark)) ? $remark_info = json_decode($remark_info->remark) : NULL;
$ln = (isset($remark_info->ln)) ? $remark_info->ln : "en";
$ln = strtolower(explode('_', $ln)[0]);
$ln = $ln==='ja' ? 'jp' : $ln;
$this->lang->load('ipl_common',$ln);
$this->lang->load('ipl_buyer_email',$ln);
$item->text = $this->lang->language;
// # lang end
$body2 = $this->load->view('receipt_buyer', $item, true);
$M_RelatedInfo2 = $item->IPL_sn;
$M_AddTime2 = $item->IPL_completeTime;
$M_State2 = 0;
$this->IPayLinks_model->save_automail($fromName, $fromEmail, $toName2, $toEmail2, $subject2, $body2, $M_RelatedInfo2, $M_State2, $M_AddTime2, 'China Highlights Has Received Your Payment');
}
// ---- 添加邮件发送记录 end
$this->Note_model->update_send($item->IPL_dealId, 'send');
$int++;
}
// 批量结果
if (empty($pn_txn_id)) {
echo "count:" . count($data['unsend_list']);
echo "\r\ndone. recorde count:".$int;
}
return;
}
/*!
* 退款处理
* @date 2019-05-08
* * TODO APP组的退款没有原始订单
*/
public function send_refund($item, $old_ssje=NULL, $handpick)
{
if ($item->IPL_stateCode != 2) {
return false;
}
// 原始收款订单
$raw_memo = json_decode($item->IPL_memo);
$parent_order = $raw_memo->orderId;
// 查询原始收款的交易号
$parent_payment = $this->query_pay($parent_order, false);
if (empty($parent_payment)) {
$this->Note_model->update_send($item->IPL_dealId, 'sendfail');
return false;
}
$parent_payment = $parent_payment->detail;
$parent_dealId = $parent_payment->dealId;
$parent_note = $this->Note_model->note($parent_dealId);
// APP 组的退款查不到原始收款记录
$pure_orderid = strstr($parent_order,"_",true);
$pure_orderid = $pure_orderid===false ? $parent_order : $pure_orderid;
if (true === $this->IPayLinks_model->if_APP_order($pure_orderid) ) {
$parent_note = $parent_payment;
// 补充字段
$parent_note->IPL_orderId = $parent_order . '_B';
$parent_note->IPL_currencyCode = $parent_payment->currencyCode;
$parent_note->IPL_payerName = strval("''");
$parent_note->IPL_payerEmail = strval("''");
}
//订单号
$orderid_info = $this->analysis_orderid($parent_note->IPL_orderId);
$orderid_info = json_decode($orderid_info);
//根据订单号查找外联信息
$advisor_info = $this->IPayLinks_model->get_order($orderid_info->orderid, false, $orderid_info->ordertype, $handpick);
//查不到订单信息
if (empty($advisor_info)) {
$this->Note_model->update_send($item->IPL_dealId, 'sendfail');
return false;
}
//更新正确的订单信息到记录中,以这个为主
$this->Note_model->set_invoice($item->IPL_dealId, $orderid_info->orderid . '_' . $orderid_info->ordertype);
//添加支付信息入库
//没有分配订单之前先添加付款记录,这个过程可能会执行多次,必须在添加记录前查找是否有数据
if (!empty($orderid_info)) {
$currencyCode = str_replace("CNY", "RMB", trim(mb_strtoupper($parent_note->IPL_currencyCode)));
$currencyCode = mb_strtoupper(trim($currencyCode));
$ssje = $this->IPayLinks_model->get_ssje($item->IPL_orderAmount, $currencyCode, '15018');
$ssje = $old_ssje===NULL ? $ssje : $old_ssje;
$USD_amount = $this->IPayLinks_model->get_USD($item->IPL_orderAmount, $currencyCode);
//更新还没有填的客邮和交易号de收款记录( 商务订单)
if (isset($advisor_info->order_type) & & $advisor_info->order_type == 0) {
$ht_memo = '(自动录入)退款号:' . $item->IPL_dealId . "\n. ";
$ht_memo .= '原收款号:' . $parent_dealId;
$GAI_COLI_SN = isset($advisor_info->COLI_SN) ? $advisor_info->COLI_SN : 0;
//CHTAPP订单添加记录前判断是否有记录, 以前的APP版本没有交易号, 只能拿金额来判断
if (substr($advisor_info->COLI_WebCode, 0, 6) == 'CHTAPP' & & strstr($advisor_info->COLI_WebCode, "-") != '-biz') {//只判断前6位字符, CHTAPP-fr CHTAPP-jp等各语种都属于APP订单
$this->IPayLinks_model->add_account_info_forAPP(
$GAI_COLI_SN,
$advisor_info->COLI_ID,
$item->IPL_orderAmount,
$item->IPL_completeTime,
$currencyCode,
$ssje,
$item->IPL_completeTime,
$item->IPL_completeTime,
$item->IPL_acquiringTime,
$parent_note->IPL_payerName,
$parent_note->IPL_payerEmail,
$item->IPL_dealId,
$ht_memo);
$this->IPayLinks_model->insert_biz_order_log($GAI_COLI_SN, 'Refunded');
} else {
if (false == $this->IPayLinks_model->if_biz_gai_exists($item->IPL_dealId) ) {
$this->IPayLinks_model->insert_biz_order_log($GAI_COLI_SN, 'Refunded');
}
$this->IPayLinks_model->add_account_info(
$GAI_COLI_SN,
$advisor_info->COLI_ID,
$item->IPL_orderAmount,
$item->IPL_completeTime,
$currencyCode,
$USD_amount,
$ssje,
$item->IPL_completeTime,
$item->IPL_completeTime,
$item->IPL_acquiringTime,
$parent_note->IPL_payerName,
$parent_note->IPL_payerEmail,
$item->IPL_dealId,
$ht_memo);
}
}
//更新还没有填的客邮和交易号的收款记录(传统订单)
elseif (isset($advisor_info->order_type) & & $advisor_info->order_type == 1) {
$ht_memo = '(自动)退款号:' . $item->IPL_dealId . "\n. ";
$ht_memo .= '原交易号:' . $parent_dealId;
$GAI_COLI_SN = isset($advisor_info->COLI_SN) ? $advisor_info->COLI_SN : 0;
$gai_sn = $this->IPayLinks_model->add_tour_account_info(
$GAI_COLI_SN,
$item->IPL_orderAmount,
$item->IPL_completeTime,
$currencyCode,
$ssje,
$item->IPL_completeTime,
$item->IPL_completeTime,
$item->IPL_acquiringTime,
$parent_note->IPL_payerName,
$parent_note->IPL_payerEmail,
$item->IPL_dealId,
$ht_memo);
//添加汉特的订单提醒
$this->IPayLinks_model->update_coli_introduction($GAI_COLI_SN, '已退款 ' . mb_strtoupper($currencyCode) . $item->IPL_orderAmount);
}
}
$opi_email = !empty($advisor_info->OPI_Email) ? $advisor_info->OPI_Email : ''; //lussie@chinahighlights.net
$opi_firstname = !empty($advisor_info->OPI_FirstName) ? $advisor_info->OPI_FirstName : !empty($advisor_info->OPI_Name) ? $advisor_info->OPI_Name : ''; //lussie
//没有外联信息表示订单未分配
if (empty($opi_email) || empty($opi_firstname)) {
$this->Note_model->update_send($item->IPL_dealId, 'sendfail');
return false;
}
//添加邮件发送记录
// if (true) { // test
if ($item->IPL_sent !== 'send' & & substr($item->IPL_sent, 0, 5) !== 'send-') {
// 客人邮件中的外联落款
// $web_code = 'cht'; // 默认cht
$web_lgc = 1;
$web_code = strtolower($advisor_info->COLI_WebCode);
$site_info = $this->config->item('site');
if (isset($site_info[$web_code])) {
$site_info = $site_info[$web_code];
$item->site = $site_info['site_url'];
$web_lgc = $site_info['site_lgc'];
}
$advisor_detail = $this->IPayLinks_model->get_advisor_detail($advisor_info->COLI_SN, $advisor_info->OPI_SN, $web_lgc);
$item->advisor_detail = $advisor_detail;
//给外联发送通知邮件
$fromName = !empty($parent_note->IPL_payerName) ? $parent_note->IPL_payerName : '';
$fromEmail = !empty($parent_note->IPL_payerEmail) ? $parent_note->IPL_payerEmail : '';
$toName = !empty($opi_firstname) ? $opi_firstname : '';
$toEmail = !empty($opi_email) ? $opi_email : '';
$subject = $orderid_info->orderid . '_' . $orderid_info->ordertype . ' / ' . $item->IPL_orderAmount . $currencyCode . ' / ' . $fromName;
$body = $this->load->view('receipt_mail', $item, true);
$M_RelatedInfo = $item->IPL_sn;
$M_AddTime = $item->IPL_completeTime;
$M_State = 0;
$this->IPayLinks_model->save_automail($fromName, $fromEmail, $toName, $toEmail, $subject, $body, $M_RelatedInfo, $M_State, $M_AddTime, 'iPayLinks note');
// 通知客人, 客人邮箱
$customer_detail = $this->IPayLinks_model->get_customer_detail($advisor_info->COLI_SN, $orderid_info->ordertype);
$c_fromName = $advisor_detail->fullname;
$opi_email_list = explode(";", $advisor_detail->email); // 解析外联的邮件
$c_fromEmail = trim($opi_email_list[0]);
$c_toName = $customer_detail->fullname;
$c_toEmail = $customer_detail->email;
$c_subject = $currencyCode . " " . str_replace('-', '', $item->IPL_orderAmount) . " Refunded to your account, booking number " . $item->IPL_orderId;
// 修改一些字段名, 为了和Alipay等用同一个邮件模板
$item->payer = $customer_detail->fullname;
$item->payer_email = $customer_detail->email;
$item->total_amount = $item->IPL_orderAmount;
$item->payment_date = $item->IPL_completeTime;
$item->payment_status = "Refunfed";
$item->currency = $currencyCode;
$item->invoice = $item->IPL_orderId;
$c_body = $this->load->view('refund_buyer', $item, true);
$c_M_RelatedInfo = $item->IPL_sn;
$c_M_AddTime = $item->IPL_completeTime;
$c_M_State = 0;
$this->IPayLinks_model->save_automail(
$c_fromName,
$c_fromEmail,
$c_toName,
$c_toEmail,
$c_subject,
$c_body,
$c_M_RelatedInfo,
$c_M_State,
$c_M_AddTime,
'ChinaHighlights refund receipt');
$this->Note_model->update_send($item->IPL_dealId, 'send-customer');
}
//添加邮件发送记录 end
// 如果已做账, 标记需要通知财务send-to-finance, 通知时间用订单日志记录
// 更新是否需要发送财务
$refund_finance_day = 20;
$now_day = date('d');
$late_entry_date_set = $now_day< $refund_finance_day ? date('Y-m-01', strtotime("-1 month")) : date('Y-m-01');
if ($this->payment_model->if_finance_done($advisor_info->COLI_GRI_SN, $late_entry_date_set) === true) {
$this->Note_model->update_send($item->IPL_dealId, 'send-to-finance');
}
return ;
}
//解析出订单号
public function analysis_orderid($note_invoice_string) {
$data = array();
//空字符串或者小于8位都属于不正确的订单号
if (empty($note_invoice_string) || strlen($note_invoice_string) < 8 ) {
return false;
}
//APP订单处理, 如标题China Train Booking-160617462
if ((strpos($note_invoice_string, 'China Train Booking') !== false) || (strpos($note_invoice_string, 'ChinaTrainBooking') !== false)) {
$note_invoice_string = explode('-', $note_invoice_string);
if (isset($note_invoice_string[1]) & & $note_invoice_string[1] !== "ChinaTrainBooking") {
$note_invoice_string = trim($note_invoice_string[1]);
} elseif (isset($note_invoice_string[0]) & & $note_invoice_string[0] !== "China Train Booking") {
$note_invoice_string = trim($note_invoice_string[0]);
}
return json_encode(array('orderid' => $note_invoice_string, 'ordertype' => 'A')); //APP订单, 不需要处理交易记录和通知
}
//订单号例子 160420021_B--9608
//Tracking code:2016-05-06-JJ160319027 /Travel advisor:Fiona Jiang /Content:Shanghai, Beijing, Pingyao, Xian, Guilin, Yangshuo, S
if (strpos($note_invoice_string, 'Tracking Code:') !== false) {
$note_invoice_string = explode('Tracking Code:', $note_invoice_string);
$note_invoice_string = explode('Travel Advisor', $note_invoice_string[1]);
$note_invoice_string = trim($note_invoice_string[0]);
}
//订单号过滤
$note_invoice_string = explode('--', $note_invoice_string);
$note_invoice_string = $note_invoice_string[0];
$note_invoice_string = explode('_', $note_invoice_string);
//订单类型识别
$ordertype = 'N';
if (isset($note_invoice_string[1])) {
$ordertype_temp = trim($note_invoice_string[1]);
if (substr($ordertype_temp, 0, 1) == 'T') {
$ordertype = 'T';
} elseif (substr($ordertype_temp, 0, 1) == 'B') {
$ordertype = 'B';
}
}
//手机订单、机票订单都没有加标示,在这里帮加上,暂时的,今后还是要在网前设置好
if ($ordertype == 'N' & & isset($note_invoice_string[0])) {
$orderid_temp = $note_invoice_string[0];
if (strlen($orderid_temp) == 9 & & substr($orderid_temp, 0, 2) == '16') {
$ordertype = 'B';
}
}
//前台预付款订单, 以45开头, 如45117640类型的订单号, 这个类型的订单会分配到某个新订单去, 需要查找COLI_AddCode来找新订单号, 然后再发送通知
if ($ordertype == 'N' & & isset($note_invoice_string[0])) {
$orderid_temp = $note_invoice_string[0];
if (strlen($orderid_temp) == 8 & & substr($orderid_temp, 0, 2) == '45') {
$ordertype = 'M';
}
}
//新的订单号14733661876255
if ($ordertype == 'N' & & isset($note_invoice_string[0])) {
$orderid_temp = $note_invoice_string[0];
if (strlen($orderid_temp) == 14 & & substr($orderid_temp, 0, 2) == '14') {
$ordertype = 'M';
}
}
if ($ordertype == 'N') {
return false; //没有编号的订单直接显示错误,由人工分配
}
$note_invoice_string = $note_invoice_string[0];
$note_invoice_string = explode(',', $note_invoice_string);
$orderid = trim($note_invoice_string[0]);
$temp_orderid = explode('-', $orderid);
if (isset($temp_orderid[1])) {
$orderid = trim($temp_orderid[1]);
}
$tempid = explode(' ', $orderid);
$pm_orderid = $tempid[0]; //订单号
if (empty($pm_orderid) || strlen($pm_orderid) < 8 ) {
return false;
}
return json_encode(array('orderid' => $pm_orderid, 'ordertype' => $ordertype));
}
/*!
* 接收异步通知
* 返回200
* @author LYT < lyt @ hainatravel . com >
* @date 2017-08-30
* @param string $resp 原始xml
*/
public function ipaylinks_notice($resp=NULL)
{
if ($resp !== NULL) {
$asyns_resp = $resp_arr = $resp;
} else {
$resp_arr = $this->input->post();
log_message('error','iPayLinks asyn notify: ' . $this->input->post("orderId"));
$asyns_resp = $this->verify_sign($resp_arr);
}
log_message('error','iPayLinks asyn notify body: ' . json_encode($asyns_resp->data));
// 未得到结果
// if (empty($asyns_resp->data->orderId)) {
// return;
// }
// dealId
$dealId = trim($asyns_resp->data->dealId) ;
$tmp_deal = $dealId ? $dealId : $this->create_guid();
// payer info
if (isset($asyns_resp->data->remark)) {
$payer_info = json_decode($asyns_resp->data->remark);
$payer_name = $payer_info->n;
$payer_email = $payer_info->e;
}
bcscale(2);
/** 退款成功 */
if (isset($asyns_resp->data->refundOrderId) & & strcmp($asyns_resp->data->resultCode, '2') == 0) {
$notice_time = $asyns_resp->data->completeTime=='' ? time() : strtotime($asyns_resp->data->completeTime);
$this->Note_model->save_refund(
strval($asyns_resp->data->dealId)
, strval($asyns_resp->data->orderId)
, strval("-" . bcdiv(floatval($asyns_resp->data->refundAmount), 100))
, strval(date('Y-m-d H:i:s',strtotime($asyns_resp->data->refundTime)))
, strval(date('Y-m-d H:i:s',$notice_time))
, $asyns_resp->data->resultCode
, null
, json_encode($asyns_resp->data)
, "refund"
);
return;
}
// 支付成功
// 查询支付结果;入库处理
// if ( ! empty($dealId)) {
$this->Note_model->save_ipl(
strval($tmp_deal)
,strval($asyns_resp->data->orderId)
,strval($asyns_resp->data->currencyCode)
,strval(bcdiv(floatval($asyns_resp->data->orderAmount), 100))
,NULL
,isset($asyns_resp->data->stateCode) ? $asyns_resp->data->stateCode : NULL
,strval(date('Y-m-d H:i:s',strtotime($asyns_resp->data->acquiringTime)))
,strval(date('Y-m-d H:i:s',strtotime($asyns_resp->data->completeTime)))
,json_encode($asyns_resp->data)
,strval("pay")
,strval($asyns_resp->data->resultCode)
,strval($asyns_resp->data->resultMsg)
,strval($payer_name)
,strval($payer_email)
);
if (strval($asyns_resp->data->resultCode) === "0000") {
$query = $this->query_pay_result($asyns_resp->data);
}
// }
// 返回状态码200
return;
}
/*!
* 生成签名串
* @author LYT < lyt @ hainatravel . com >
* @date 2017-08-17
* @param array $request 待签名的请求数据/返回结果
* @return string 签名字符串
*/
protected function generate_sign($request)
{
ksort($request);
unset($request['signMsg']);
$request['pkey'] = "30819f300d06092a864886f70d010101050003818d00308189028181008c903972be5509375edec0d6793d8d3eb533334d146069b5dfcdafd24e5c7d0a05d1774488ea257d504a18c9098d798c0f523f3ad722e3e9c32ae7fecd7e734b340b9c8ff805aa32d0a49cb6df9eca3bb6954d966f6148533a8d667aabb55b2762dcd06308c94d24d257dfdb2ad86b46702774c51e7627e5b707d52224ef794b0203010001";
// $request['pkey'] = $this->config->item('pkey');
$param_str = "";
foreach ($request as $sysParamKey => $sysParamValue) {
if ($sysParamKey == "details") {
$param_str .= trim($sysParamKey)."=[";
$value_cnt = count($sysParamValue);
$value_int = 0;
foreach ($sysParamValue as $vk => $detail) {
$value_int++;
$param_str .= "{";
$v_cnt = count($detail);
$v_int = 0;
foreach ($detail as $dk => $dv) {
$v_int ++;
if (false === $this->checkEmpty($dv)) {
$param_str .= trim($dk)."=" . trim($this->characet($dv,"UTF-8"));
if ($v_int != $v_cnt) {
$param_str .= ",";
}
}
}
$param_str .= "}";
if ($value_int != $value_cnt) {
$param_str .= ",";
}
}
$param_str .= "]&";
continue;
}
if (false === $this->checkEmpty($sysParamValue)) {
$param_str .= trim($sysParamKey)."=" . trim($this->characet($sysParamValue,"UTF-8")) . "&";
}
}
$param_str = substr($param_str, 0, -1);
$param_str = md5($param_str);
$request['signMsg'] = $param_str;
unset($request['pkey']);
return $param_str;
}
/*!
* 验证签名
* @author LYT < lyt @ hainatravel . com >
* @date 2017-08-17
* @param mix $resp API返回的原始xml或异步返回的post数组
*/
protected function verify_sign($resp=NULL, $sign=true)
{
$ret = new ArrayObject();
$ret->check = false;
$ret->data = NULL;
if (is_array($resp)) {
// 异步通知接收到的是post数组
$ret->data = $respObject = (Object) $resp;
$ref = "";
} else {
$ref = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : NULL;
$r = iconv("UTF-8", "UTF-8//IGNORE", $resp);
$ret->data = $respObject = @ simplexml_load_string($resp);
// test
// log_message("error", "xml result: \n $resp");
if (false === $respObject) {
log_message('error','iPayLinks return ERROR ! Unknow ERROR ! Original return:'.$resp."; From: ".$ref);
return $ret;
}
}
if ($sign === true) {
$rep_sign = $this->generate_sign((array)$respObject);
if (strcmp($rep_sign,$respObject->signMsg)) {
log_message('error','iPayLinks sign ERROR ! orderId:'.$respObject->orderId.'; dealId:'.$respObject->dealId . "; Original return:".$resp."; From: ".$ref);
return $ret;
}
// partnerId
if (strcmp($respObject->partnerId, $this->pay_info_arr['partnerId'])) {
log_message("error", " iPayLinks ERROR partnerId verify failed ".$respObject->partnerId." !== ".$this->pay_info_arr['partnerId'].'; orderId:'.$respObject->orderId.'; dealId:'.$respObject->dealId."; From: ".$ref);
return $ret;
}
// resultCode payment failed
if (strcmp(strval($respObject->resultCode), "0000")) {
log_message('error',"iPayLinks payment failed! error code:".$respObject->resultCode."; result Msg: ".$respObject->resultMsg.'; orderId:'.$respObject->orderId.'; dealId:'.$respObject->dealId."; From: ".$ref);
}
}
$ret->check = true;
return $ret;
}
/*!
* 转换字符集编码
* @param $data
* @param $targetCharset
* @return string
*/
protected function characet($data, $targetCharset) {
if (!empty($data)) {
$fileType = "UTF-8";
if (strcasecmp($fileType, $targetCharset) != 0) {
$data = mb_convert_encoding($data, $targetCharset, $fileType);
// $data = iconv($fileType, $targetCharset.'//IGNORE', $data);
}
}
return $data;
}
protected function curl($url, $postFields = null) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FAILONERROR, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$postBodyString = "";
if (is_array($postFields) & & 0 < count ( $ postFields ) ) {
foreach ($postFields as $k => $v) {
if ("@" != substr($v, 0, 1)) //判断是不是文件上传
{
$postBodyString .= "$k=" . urlencode($this->characet($v, "UTF-8")) . "&";
}
}
unset($k, $v);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, substr($postBodyString, 0, -1));
}
$headers = array('content-type: application/x-www-form-urlencoded;charset=UTF-8');
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$reponse = curl_exec($ch);
if (curl_errno($ch)) {
log_message('error', " iPayLinks curl error code: ".curl_error($ch)."; curl postBodyString: ".substr($postBodyString, 0, -1));
} else {
$httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (200 !== $httpStatusCode) {
log_message('error', " iPayLinks Request html Status Code: ".$httpStatusCode."; curl postBodyString: ".substr($postBodyString, 0, -1));
}
}
curl_close($ch);
return $reponse;
}
public function test_curl()
{
$url = $this->input->get_post('url');
$data = $this->curl($url);
$json = json_decode($data);
echo $json->tls_version;
var_dump($json);
return;
}
/*!
* 检验非空
* @author LYT < lyt @ hainatravel . com >
* @date 2017-08-17
* @param [type] $value [description]
* @return boolean true-空;false-非空
*/
protected function checkEmpty($value) {
if (!isset($value))
return true;
if ($value === null)
return true;
if (trim($value) === "")
return true;
return false;
}
/*!
* [result_to_return_url description]
* 返回 和其他支付方式统一 的结果给支付结果页面
* @author LYT < lyt @ hainatravel . com >
* @date 2017-08-28
* @param [type] $code [description]
* @return [type] [description]
*/
protected function result_2_return_url($code,$msg)
{
$ret['code'] = 0;
$ret['msg'] = "";
$ret['error_code'] = $code ? $code : "Unknow";
$ret["error_code"] .= ".";
$tmp_msg = $msg ? strstr($msg,":",true)."." : false; // result msg的英文部分
$code_msg = $tmp_msg ? $tmp_msg : "Please contact your advisor.";
$ret['error_code'] .= $code_msg;
switch ($code) {
case '0000':
$ret['code'] = 0;
$ret['msg'] = "success";
break;
default:
$ret['code'] = $code;
$ret['msg'] = "Payment Failed.";
break;
}
return $ret;
}
protected function create_guid() {
return strtolower(md5(uniqid(mt_rand(), true)));
}
protected function payment_status()
{
return array(
0 => "Denied",
1 => "Pending",
2 => "Payment success",
3 => "Denied"
);
}
public function gai_modal($pn_txn_id=null, $pn_invoice=null, $pn_id = null, $neworder=null)
{
$this->permission->is_admin(true);
$data = array();
$data['note'] = $this->Note_model->note($pn_txn_id, $pn_id);
$orderid_info = $this->analysis_orderid($pn_invoice);
if (!empty($orderid_info)) {
$orderid_info = json_decode($orderid_info);
if ($orderid_info->ordertype === 'T') {
$data['gai_info'] = $this->IPayLinks_model->get_money_t($pn_txn_id);
} elseif ($orderid_info->ordertype === 'B') {
$data['gai_info'] = $this->IPayLinks_model->get_money_b($pn_txn_id);
}
}
$data['old_order'] = $pn_invoice;
$data['new_order'] = $neworder;
$data['order_info'] = null;
if ($neworder !== null) {
$neworder_id = $this->analysis_orderid($neworder);
$neworder_id = json_decode($neworder_id);
if ( ! empty($neworder_id)) {
$data['order_info'] = $this->IPayLinks_model->get_order($neworder_id->orderid, true, $neworder_id->ordertype, true);
}
}
echo json_encode($this->load->view('gai_setting', $data, true));
}
public function gai_modal_save()
{
$data = array();
$old_ssje = NULL;
$pn_txn_id = $this->input->post('pn_txn_id');
$pn_id = $this->input->post('pn_id');
$neworder = $this->input->post('pn_invoice');
$data['note'] = $this->Note_model->note($pn_txn_id, $pn_id);
$orderid_info = $this->analysis_orderid($data['note']->IPL_orderId);
if (empty($orderid_info) & & $data['note']->IPL_payType == 'refund'
& & true === $this->IPayLinks_model->if_APP_order($data['note']->IPL_orderId)
) {
// APP 组的退款订单是没有后缀的
$orderid_info = $this->analysis_orderid($data['note']->IPL_orderId . '_B');
}
if (!empty($orderid_info)) {
$orderid_info = json_decode($orderid_info);
if ($orderid_info->ordertype === 'T') {
$data['gai_info'] = $this->IPayLinks_model->get_money_t($pn_txn_id);
if ( ! empty($data['gai_info'])) {
$old_ssje = $data['gai_info'][0]->GAI_SSJE;
$this->IPayLinks_model->delete_money_t($pn_txn_id);
}
} elseif ($orderid_info->ordertype === 'B') {
$data['gai_info'] = $this->IPayLinks_model->get_money_b($pn_txn_id);
if ( ! empty($data['gai_info'])) {
$old_ssje = $data['gai_info'][0]->GAI_SSJE;
$this->IPayLinks_model->delete_money_b($pn_txn_id);
}
}
}
if (!empty($pn_txn_id) & & !empty($neworder)) {
$orderid_info = $this->analysis_orderid($neworder);
if (!empty($orderid_info)) {
$orderid_info = json_decode($orderid_info);
$advisor_info = $this->IPayLinks_model->get_order($orderid_info->orderid, false, $orderid_info->ordertype, true);
if (!empty($advisor_info)) {
$this->Note_model->set_invoice($pn_txn_id, $neworder);
$this->batch_send_note($pn_txn_id, $old_ssje, $pn_id);
echo json_encode('修改成功!');
return true;
}
}
}
echo json_encode('没找到数据!');
return;
}
public function closeGai($pn_txn_id)
{
$data = array();
$data['note'] = $this->Note_model->note($pn_txn_id);
if (!empty($data['note'])) {
$this->Note_model->update_send($pn_txn_id, 'closeRecord');
echo json_encode('该收款记录已经忽略!');
return true;
}
echo json_encode('没找到数据!');
return;
}
//获取note详情, 以便后续修改各项数据
public function note_modal($pn_txn_id = false, $pn_invoice = false, $pn_id = null) {
$this->permission->is_admin(true);
$data = array();
$data['IPL_orderId'] = $pn_invoice;
if (!empty($pn_txn_id)) {
$data['note'] = $this->Note_model->note($pn_txn_id, $pn_id);
if (!empty($data['note'])) {
if (!empty($pn_invoice)) {
$orderid_info = $this->analysis_orderid($pn_invoice);
} else {
$orderid_info = $this->analysis_orderid($data['note']->IPL_orderId);
}
if (!empty($orderid_info)) {
$orderid_info = json_decode($orderid_info);
$data['order_info'] = $this->IPayLinks_model->get_order($orderid_info->orderid, true, $orderid_info->ordertype, true);
}
$data["paytext"] = $this->payment_status();
echo json_encode($this->load->view('note_setting', $data, true));
return true;
}
}
echo json_encode('没找到数据!');
return;
}
public function note_order_modal($old_order,$pn_invoice = false ,$notice_time = false) {
$data = array();
$data['IPL_orderId'] = $pn_invoice;
if (!empty($pn_invoice)) {
$data['note'] = $this->Note_model->note_order($old_order,$notice_time);
if (!empty($data['note'])) {
if (!empty($pn_invoice)) {
$orderid_info = $this->analysis_orderid($pn_invoice);
} else {
$orderid_info = $this->analysis_orderid($data['note']->IPL_orderId);
}
if (!empty($orderid_info)) {
$orderid_info = json_decode($orderid_info);
$data['order_info'] = $this->IPayLinks_model->get_order($orderid_info->orderid, true, $orderid_info->ordertype, true);
}
$data["paytext"] = $this->payment_status();
echo json_encode($this->load->view('note_setting', $data, true));
return true;
}
}
echo json_encode('没找到数据!');
return;
}
//关闭note通知, 用于手动处理通知后
public function close_note($pn_txn_id) {
$data = array();
$data['note'] = $this->Note_model->note($pn_txn_id);
if (!empty($data['note'])) {
$this->Note_model->update_send($pn_txn_id, 'send');
echo json_encode('通知已经关闭!');
return true;
}
echo json_encode('没找到数据!');
return;
}
//修改订单名
public function note_modal_save() {
$this->gai_modal_save();
// $data = array();
// $pn_txn_id = $this->input->post('pn_txn_id');
// $pn_invoice = $this->input->post('pn_invoice');
// if (!empty($pn_txn_id) & & !empty($pn_invoice)) {
// $orderid_info = $this->analysis_orderid($pn_invoice);
// if (!empty($orderid_info)) {
// $orderid_info = json_decode($orderid_info);
// $advisor_info = $this->IPayLinks_model->get_order($orderid_info->orderid, false, $orderid_info->ordertype);
// if (!empty($advisor_info)) {
// $this->Note_model->set_invoice($pn_txn_id, $pn_invoice);
// $this->batch_send_note($pn_txn_id);
// echo json_encode('修改成功!');
// return true;
// }
// }
// }
// echo json_encode('没找到数据!');
return;
}
//用于HT--交易详情
public function receipt($pm_transaction_id) {
if ( ! $pm_transaction_id) {
return false;
}
$data = array();
$data = $this->Note_model->note($pm_transaction_id);
$this->load->view('receipt_mail', $data);
}
public function alipay_return()
{
redirect('https://www.chinahighlights.com');
}
public function cal_ssje($amount, $currency='USD')
{
$ssje = $this->IPayLinks_model->get_ssje($amount, $currency);
var_dump($ssje);
}
/*!
* 每天请求一次,批量取回退款记录保存
* @author LYT < lyt @ hainatravel . com >
* @date 2017-11-06
*/
public function get_refund_list($daylength=3)
{
return false; // ipaylinks的批量查询接口已关闭
bcscale(2);
$ret = array();
$list = $this->refund_list_info($daylength);
foreach ($list as $key => $refund) {
if ($refund->stateCode == 1) continue;
$ret[] = $this->Note_model->save_refund(
strval($refund->dealId)
, strval($refund->orderId)
, strval("-" . bcdiv(floatval($refund->refundAmount), 100))
, strval(date('Y-m-d H:i:s',strtotime($refund->refundTime)))
, strval(date('Y-m-d H:i:s',strtotime($refund->completeTime)))
, $refund->stateCode
, ($refund->stateCode==2) ? "0000" : null
, json_encode($refund)
, "refund"
);
}
echo "Got record count: " . count($ret);
return;
}
/*!
* 批量取回退款记录
* @author LYT < lyt @ hainatravel . com >
* @date 2017-11-03
*/
public function refund_list_info($daylength)
{
$this->query_info_arr["queryOrderId"] = $this->create_guid();
$this->query_info_arr['mode'] = '2';
$this->query_info_arr['type'] = '2';
$this->query_info_arr["beginTime"] = date('Ymd000000', strtotime("-$daylength days"));
$this->query_info_arr["endTime"] = date('Ymd235959');
$this->query_info_arr["signMsg"] = $this->generate_sign($this->query_info_arr);
$resp = $this->curl($this->queryUrl,$this->query_info_arr);
$query_resp = $this->verify_sign($resp, false);
// 未得到结果
if (false === $query_resp->data) {
// echo "No record.";
return false;
}
$refund_list_obj = @ json_decode(@ json_encode($query_resp->data->refundDetails));
$refund_list = $refund_list_obj->detail;
foreach ($refund_list as $key => $refund) {
// 由于ipaylinks批量查询的bug,这里要用单笔查询校对
$this_info = $this->get_refund($refund->refundOrderId);
if ($this_info !== false) {
$refund->stateCode = $this_info->stateCode;
$refund->refundTime = $this_info->refundTime;
$refund->completeTime = $this_info->completeTime;
}
}
return $refund_list;
}
/*!
* 单笔查询退款信息
* ipaylinks的批量查询有问题,所以这个需要用单笔查询确认信息
* @author LYT < lyt @ hainatravel . com >
* @date 2017-11-06
* @param string $refund_order_id 退款信息中的refundOrderId
*/
public function get_refund($refund_order_id)
{
$this->query_info_arr["queryOrderId"] = $this->create_guid();
$this->query_info_arr["orderId"] = $refund_order_id;
$this->query_info_arr['mode'] = '1';
$this->query_info_arr['type'] = '2';
$this->query_info_arr["signMsg"] = $this->generate_sign($this->query_info_arr);
$resp = $this->curl($this->queryUrl,$this->query_info_arr);
$query_resp = $this->verify_sign($resp, false);
// 未得到结果
if (false === $query_resp->data) {
return false;
}
return $query_resp->data->refundDetails->detail;
}
public function auto_update_statement()
{
set_time_limit(0);
// $target_folder = date("Y-m", strtotime("-1 day"));
// $target_folder = str_replace("-", "\\", $target_folder);
$today_time = strtotime(date('Ymd000000'));
// 解析excel
$target_folder = $this->input->get_post("f");
$files = json_decode($this->input->get_post("fjson"));
$statement_folder = FCPATH.'download_statement\statement_files\\' . $target_folder;
if ( ! is_dir($statement_folder)) {
return;
}
$files = array_values(array_diff(scandir($statement_folder), array('.', '..')));
if (empty($files)) {
echo "none excel.";
return;
}
$settle_cnt = 0;
$update_cnt = 0;
bcscale(4);
// 仅处理今天新增的新文件
foreach ($files as $k => $fe) {
$file_path = $statement_folder . '\\' . $fe;
$modify_time = filemtime($file_path);
if ($modify_time < $today_time) {
continue;
}
$settlement_record = $this->read_excel($file_path);
if (empty($settlement_record)) {
continue;
}
foreach ($settlement_record as $settle) {
// old data
$orderid_info = $this->analysis_orderid(trim($settle['orderid']));
$orderid_info = json_decode($orderid_info);
if (empty($orderid_info)) {
continue;
}
if (strcasecmp($orderid_info->ordertype, "B") === 0) {
$old_info = $this->IPayLinks_model->get_money_b(trim($settle['pn_invoice']));
} else if (strcasecmp($orderid_info->ordertype, "T") === 0){
$old_info = $this->IPayLinks_model->get_money_t(trim($settle['pn_invoice']));
} # 没有重复的交易号, 不处理了
if (empty($old_info)) {
continue;
}
$entry_sum_RMB = $entry_sum = bcadd(floatval($settle['entry_security']), floatval($settle['entry_basic']));
if (strcasecmp(trim($settle['entry_currency']), "CNY")) {
$entry_sum_RMB = $this->IPayLinks_model->get_ssje($entry_sum, trim($settle['entry_currency']), 0);
}
$warrant["PW_GAI_AccreditNo"] = trim($settle['pn_invoice']);
$warrant["PW_GAI_Type"] = 15018;
$warrant["PW_entry_currency"] = trim($settle['entry_currency']);
$warrant["PW_entry_amount"] = $entry_sum;
$warrant["PW_GAI_SSJE_new"] = $entry_sum_RMB;
$warrant["PW_COLI_SN"] = $old_info[0]->GAI_COLI_SN;
$warrant["PW_GAI_SQJECurrency_pre"] = $old_info[0]->GAI_SQJECurrency;
$warrant["PW_GAI_SSJE_pre"] = $old_info[0]->GAI_SSJE;
$warrant["PW_orderType"] = $orderid_info->ordertype;
$this->Note_model->new_warrant($warrant);
// 2018.02.05 暂不更新付款记录, 测试观察一段
if (strcasecmp($orderid_info->ordertype, "B") === 0) {
// $this->IPayLinks_model
// ->update_money_b($entry_sum_RMB, trim($settle['pn_invoice']));
} else if (strcasecmp($orderid_info->ordertype, "T") === 0){
// $this->IPayLinks_model
// ->update_money_t($entry_sum_RMB, trim($settle['pn_invoice']));
}
$warrant = NULL;
$update_cnt++;
}
$settlement_record = null; // reset
$settle_cnt++;
}
$result = "auto_update_statement result: " . date('Y-m-d H:i:s') . " ------ \r\n";
$result .= "Found $settle_cnt Excels; Updated $update_cnt records;";
log_message('error', $result);
echo $result;
return;
}
public function read_excel($filePath)
{
$tarr1=array();
$this->load->library('PHPExcel');
$PHPExcel = new PHPExcel();
/**默认用excel2007读取excel, 若格式不对, 则用之前的版本进行读取*/
$PHPReader = new PHPExcel_Reader_Excel2007();
if(!$PHPReader->canRead($filePath)){
$PHPReader = new PHPExcel_Reader_Excel5();
if(!$PHPReader->canRead($filePath)){
echo 'no Excel';
return ;
}
}
$PHPExcel = $PHPReader->load($filePath);
/**读取excel文件中的第一个工作表*/
$currentSheet = $PHPExcel->getSheet(0);
/**取得最大的列号*/
$allColumn = $currentSheet->getHighestColumn();
/**取得一共有多少行*/
$allRow = $currentSheet->getHighestRow();
$col_titles = $this->col_title();
/**从第二行开始输出, 因为excel表中第一行为列名*/
for($currentRow = 2;$currentRow < = $allRow;$currentRow++){
$row_tmp = array();
/**从第A列开始输出*/
for($currentColumn= 'A';$currentColumn< = $allColumn; $currentColumn++){
/**ord()将字符转为十进制数*/
$val = $currentSheet->getCellByColumnAndRow(ord($currentColumn) - 65,$currentRow)->getValue();
$col_mean = $col_titles[$currentColumn];
if($col_mean == 'data_type' & & strcasecmp('清算', $val) !== 0)
{
break;
}
if ($col_mean == 'settlement_amount' & & floatval($val) < = 0) {
break;
}
$row_tmp[$col_mean] = $val;
}
if (isset($row_tmp['settlement_amount'])) {
$tarr1[] = $row_tmp;
}
}
return $tarr1;
}
public function col_title()
{
return array(
"A" => "complete_date",
"B" => "pn_invoice",
"C" => "orderid",
"D" => "data_type",
"E" => "currency",
"F" => "order_amount",
"G" => "settlement_rate",
"H" => "settlement_amount",
"I" => "service_fee",
"J" => "transaction_fee",
"K" => "mark_memo",
"L" => "entry_currency",
"M" => "entry_security",
"N" => "entry_basic"
);
}
public function export_list()
{
$from_date = $this->input->post("from_date");
$to_date = $this->input->post("to_date");
$currency = $this->input->post("currency");
$export_list = $this->Note_model->date_range($from_date, $to_date, $currency);
if ($export_list == false) {
echo "Not found any records for export.";
return false;
}
$this->load->library('PHPExcel');
$objPHPExcel = new PHPExcel();
$objPHPExcel->setActiveSheetIndex(0);
//set width
$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(5);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(30);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(30);
$objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(20);
// 对齐
$objPHPExcel->getActiveSheet()->getStyle('B')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
$objPHPExcel->getActiveSheet()->getStyle('C')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
// 表标题行
$objPHPExcel->getActiveSheet()
->SetCellValue('A1', '#')
->SetCellValue('B1', '团号')
->SetCellValue('C1', '金额')
->SetCellValue('D1', '付款人')
->SetCellValue('E1', '付款人邮箱')
->SetCellValue('F1', '交易号')
->SetCellValue('G1', '收单时间');
$currency_sum = array();
bcscale(2);
$rowCount = 2;
foreach ($export_list as $key => $row) {
if( trim($row->IPL_currencyCode) != "") {
$currency_sum[trim($row->IPL_currencyCode)] = @ bcadd($currency_sum[trim($row->IPL_currencyCode)], $row->IPL_orderAmount);
}
$payer = $row->IPL_payerName ? ($row->IPL_payerName . "< " . $row->IPL_payerEmail . ">") : "退款";
$objPHPExcel->getActiveSheet()
->SetCellValue('A'.$rowCount, ($rowCount-1))
->setCellValueExplicit('B'.$rowCount, $row->IPL_orderId,PHPExcel_Cell_DataType::TYPE_STRING)
->setCellValueExplicit('C'.$rowCount, trim($row->IPL_currencyCode) . number_format($row->IPL_orderAmount, 2, ".", ""),PHPExcel_Cell_DataType::TYPE_STRING)
->SetCellValue('D'.$rowCount, $row->IPL_payerName)
->SetCellValue('E'.$rowCount, $row->IPL_payerEmail)
->setCellValueExplicit('F'.$rowCount, $row->IPL_dealId,PHPExcel_Cell_DataType::TYPE_STRING)
->SetCellValue('G'.$rowCount, $row->IPL_acquiringTime);
$payer = "";
$rowCount++;
}
$rowCount++; // 隔一行
// 汇总行
$objPHPExcel->getActiveSheet()
->SetCellValue('A' . $rowCount, '合计');
foreach ($currency_sum as $kc => $cur) {
$objPHPExcel->getActiveSheet()
->SetCellValue('B' . $rowCount, $kc)
->setCellValueExplicit('C' . $rowCount, number_format($cur, 2, ".", ""),PHPExcel_Cell_DataType::TYPE_STRING);
$rowCount++;
}
$filename = "export_ipaylinks_" . date('Y-m-d');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="' . $filename . '.xls"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
}
public function sign_fun()
{
$req = $this->input->post();
$str = $this->generate_sign($req);
return $this->output->set_content_type('application/json')->set_output(json_encode(array("str" => $str)));
}
public function test()
{
$this->Note_model->test();
return ;
}
}