代码拉取完成,页面将自动刷新
<?php
/**
* Plugin Name: WooCommerce 支付FM Gateway
* Plugin URI: https://zhifu.fm/
* Description: 支付FM,聚合主流收款通道支付接口服务,支持支付宝微信等收款码通道,同时支持多种签约支付接口通道。一次接入多平台,资金直达客户收款账号。
* Version: 1.0.0
* Author: zhifu.fm
* Author URI: ttps://zhifu.fm/
*/
if (!defined('ABSPATH')) {
exit;
}
add_action('plugins_loaded', 'woocommerce_gateway_zhifufm_init');
add_action("activated_plugin", "make_sure_this_plugin_loaded_lastly");
function make_sure_this_plugin_loaded_lastly()
{
$plugin = plugin_basename(__FILE__);
$active_plugins = get_option('active_plugins');
$this_plugin_key = array_search($plugin, $active_plugins);
if ($this_plugin_key != count($active_plugins) - 1) {
array_splice($active_plugins, $this_plugin_key, 1);
array_unshift($active_plugins, $plugin);
update_option('active_plugins', $active_plugins);
}
}
function woocommerce_gateway_zhifufm_init()
{
require_once 'lib/core.php';
global $logger;
if (!defined('ZHIFUFM_GATEWAY')) {
define('ZHIFUFM_GATEWAY', 'ZHIFUFM');
} else {
return;
}
define('ZHIFUFM_VERSION', '1.0.1');
define('ZHIFUFM_ID', 'zhifufm-wc');
define('ZHIFUFM_FILE', __FILE__);
define('ZHIFUFM_DIR', rtrim(plugin_dir_path(ZHIFUFM_FILE), '/'));
define('ZHIFUFM_URL', rtrim(plugin_dir_url(ZHIFUFM_FILE), '/'));
define('ZHIFUFM_BASENAME', plugin_basename(__FILE__)); // woocommerce-gateway-zhifufm/init.php
define('ZHIFUFM_NAME', dirname(ZHIFUFM_BASENAME)); // woocommerce-gateway-zhifufm
load_plugin_textdomain(ZHIFUFM_GATEWAY, false, ZHIFUFM_NAME . '/languages/');
add_filter('plugin_action_links_' . ZHIFUFM_BASENAME, 'zhifufm_gateway_plugin_action_links', 10, 1);
/**
* 插件管理连接
*
* @param array $links old links
*
* @return array new links
*/
function zhifufm_gateway_plugin_action_links($links)
{
$baseURL = 'admin.php?page=wc-settings&tab=checkout§ion=' . ZHIFUFM_ID;
$payTypes = array('alipay', 'wechat','alipaysign','alipay-facetoface');
$extraLinks = array();
foreach ($payTypes as $payType) {
$settingsURL = admin_url($baseURL . '-' . $payType);
$settingsTitle = __('settings:' . $payType, ZHIFUFM_GATEWAY);
$extraLinks['settings ' . $payType] = "<a href=\"$settingsURL\">$settingsTitle</a>";
}
return array_merge($extraLinks, $links);
}
if (!class_exists('WC_Payment_Gateway')) {
return;
}
class ZHIFUFM_WC_Payment_Gateway extends WC_Payment_Gateway
{
const payType = null;
private static $instance;
public function __construct()
{
$zhifufmZFB = new ZHIFUFM_Gateway_Alipay();
$zhifufmWXN = new ZHIFUFM_Gateway_WeChat();
$zhifufmZFBWEB = new ZHIFUFM_Gateway_Alipay_WEB();
$zhifufmZFBFACE = new ZHIFUFM_Gateway_Alipay_FACE();
}
public function notifyFilter()
{
global $logger;
$logger->debug("////////////////////////////////////////////////");
$logger->debug(__class__ . '/' . __FUNCTION__);
$data = $_GET;
if (!isset($data['sign'])
|| !isset($data['orderNo'])) {
return;
}
$result = "success";
$logger->debug("++++++++++++++++++++notify+++++++++++++++++++++++");
$data['merchantNum'] = $this->get_option('api_user');
$data['key'] = $this->get_option('api_key');
$newSignature = $this->generate_sign($data);
if ($data['sign'] != $newSignature) {
$logger->debug($data['sign'] ."+++++++++++++++签名不匹配++++++++++++++++".$newSignature);
return;
}
$order = wc_get_order($data['orderNo']);
try {
if (!$order) {
throw new Exception('Unknown Order (id:' . $data['orderNo'] . ')');
}
$logger->debug(" >>>>>>>>>>>>>>>".$order->get_status());
if (!(method_exists($order, 'is_paid') ? $order->is_paid() : in_array($order->get_status(), array('processing', 'completed'))) && $data['state'] == '1') {
$logger->debug("+++++++++++++++支付完成+++++++++++++++++");
$order->payment_complete();
$woocommerce->cart->empty_cart(); // clear cart
$result = "success";
}
$logger->debug("////////////////////////////////////////////////");
} catch (Exception $e) {
$logger->debug('notify error: ' . $e->getMessage());
ob_clean();
}
// $params['hash'] = $this->generate_hash($params, $appKey);
ob_clean();
// 不能exit因为要继续执行core里面的notify
// print $result;
//exit;
}
public function woocommerce_add_gateway($methods)
{
global $logger;
$logger->debug(__class__ . '/' . __FUNCTION__);
$methods[] = $this;
return $methods;
}
public function process_payment($order_id)
{
global $logger;
$logger->debug(__class__ . '/' . __FUNCTION__);
$order = wc_get_order($order_id);
$payType = $order->payment_method;
$payType = str_replace("zhifufm-wc-","",$payType);
//var_dump($payType);die;
if (!$order || (method_exists($order, 'is_paid') ? $order->is_paid() : in_array($order->get_status(), array('processing', 'completed')))) {
return array(
'result' => 'success',
'redirect' => $this->get_return_url($order)
);
}
$expire_rate = floatval($this->get_option('exchange_rate', 1));
if ($expire_rate <= 0) {
$expire_rate = 1;
}
$total_amount = round($order->get_total() * $expire_rate, 2);
$payURL = home_url('index.php?zhifufm-act=pay&id=' . $order_id . '&price=' . $total_amount . '&type='.$payType);
if ('yes' === get_option('woocommerce_force_ssl_checkout') || is_ssl()) {
$payURL = str_replace('http:', 'https:', $payURL);
}
return array(
'result' => 'success',
'redirect' => $payURL,
);
}
public function isWebApp()
{
global $logger;
$logger->debug(__class__ . '/' . __FUNCTION__);
if (!isset($_SERVER['HTTP_USER_AGENT'])) {
return false;
}
$u = strtolower($_SERVER['HTTP_USER_AGENT']);
if ($u == null || strlen($u) == 0) {
return false;
}
preg_match('/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/', $u, $res);
if ($res && count($res) > 0) {
return true;
}
if (strlen($u) < 4) {
return false;
}
preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/', substr($u, 0, 4), $res);
if ($res && count($res) > 0) {
return true;
}
$ipadchar = "/(ipad|ipad2)/i";
preg_match($ipadchar, $u, $res);
return $res && count($res) > 0;
}
private function http_post($url, $data)
{
global $logger;
$logger->info('POST ' . $url . ' # ' . var_export($data, true));
if (!function_exists('curl_init')) {
throw new Exception('php curl not found', 500);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_REFERER, get_option('siteurl'));
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);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$tmpLogFile = tmpfile();
if ($tmpLogFile === false) {
$timeStr = date_format(date_create(), 'Ymd-His-u');
$tmpLogPath = ZHIFUFM_WWW_DIR . '/logs/curl-' . $timeStr . '.log';
$tmpLogFile = fopen($tmpLogPath, 'w+');
} else {
$tmpLogFileInfo = stream_get_meta_data($tmpLogFile);
$tmpLogPath = $tmpLogFileInfo['uri'];
}
$logger->debug('create a tmp file for curl log: ' . $tmpLogPath);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_STDERR, $tmpLogFile);
$response = curl_exec($ch);
fflush($tmpLogFile);
$logger->debug('HTTP Request Details' . PHP_EOL . file_get_contents($tmpLogPath));
// fseek($tmpLogFile, 0);
// while (($buffer = fgets($tmpLogFile)) !== FALSE) {
// $logger->debug($buffer);
// }
fclose($tmpLogFile);
if (file_exists($tmpLogPath)) {
unlink($tmpLogPath);
}
$httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);
if ($httpStatusCode != 200) {
throw new Exception("invalid httpstatus:{$httpStatusCode} ,response:$response,detail_error:" . $error, $httpStatusCode);
}
return $response;
}
public function generate_sign(array $params)
{
global $logger;
$logger->debug(__class__ . '/' . __FUNCTION__);
return md5($params['state'].$params['merchantNum'].$params['orderNo'].$params['amount']. $params['key']);
}
public function thankyou_page()
{
global $logger;
$logger->debug(__class__ . '/' . __FUNCTION__);
if ($this->instructions) {
echo wpautop(wptexturize($this->instructions));
}
}
/**
* Add content to the WC emails.
*
* @access public
* @param WC_Order $order
* @param bool $sent_to_admin
* @param bool $plain_text
*/
public function email_instructions($order, $sent_to_admin, $plain_text = false)
{
global $logger;
$logger->debug(__class__ . '/' . __FUNCTION__);
$method = method_exists($order, 'get_payment_method') ? $order->get_payment_method() : $order->payment_method;
if ($this->instructions && !$sent_to_admin && $this->id === $method) {
echo wpautop(wptexturize($this->instructions)) . PHP_EOL;
}
}
/**
* Initialise Gateway Settings Form Fields
*
* @access public
* @return void
*/
public function init_form_fields()
{
global $logger;
$logger->debug(__class__ . '/' . __FUNCTION__);
$this->form_fields = array(
'title' => array(
'title' => __('gateway title : key', ZHIFUFM_GATEWAY),
'type' => 'text',
'default' => __('zhifufm:' . static::payType, ZHIFUFM_GATEWAY),
'desc_tip' => true,
'css' => 'width:400px',
'section' => 'default',
),
'description' => array(
'title' => __('gateway description : key', ZHIFUFM_GATEWAY),
'type' => 'textarea',
'default' => __('gateway description : value', ZHIFUFM_GATEWAY),
'desc_tip' => true,
'css' => 'width:400px',
'section' => 'default'
),
'instructions' => array(
'title' => __('gateway instruction : key', ZHIFUFM_GATEWAY),
'type' => 'textarea',
'css' => 'width:400px',
'description' => __('gateway instruction : tips', ZHIFUFM_GATEWAY),
'default' => '',
'section' => 'default'
),
'api_user' => array(
'title' => '商户号',
'type' => 'text',
'css' => 'width:400px',
'section' => 'default',
'default' => ZHIFUFM_API_USER
),
'api_key' => array(
'title' => '接入密钥',
'type' => 'text',
'css' => 'width:400px',
'default' => ZHIFUFM_API_KEY,
'section' => 'default'
)
);
}
public function get_order_title($order, $limit = 98)
{
global $logger;
$logger->debug(__class__ . '/' . __FUNCTION__);
$order_id = method_exists($order, 'get_id') ? $order->get_id() : $order->id;
$title = "#{$order_id}";
$order_items = $order->get_items();
if ($order_items) {
$qty = count($order_items);
foreach ($order_items as $item_id => $item) {
$title .= "|{$item['name']}";
break;
}
if ($qty > 1) {
$title .= '...';
}
}
$title = mb_strimwidth($title, 0, $limit, 'utf-8');
return apply_filters('xh-payment-get-order-title', $title, $order);
}
public function apiConfig()
{
$apiUser = $this->get_option('api_user');
$apiKey = $this->get_option('api_key');
zhifufmOrder::apiConfig($apiUser, $apiKey);
}
public function do_actions()
{
global $logger;
$this->apiConfig();
$action = isset($_GET['zhifufm-act']) ? $_GET['zhifufm-act'] : null;
$invalidActions = array('check', 'notify', 'return', 'pay', 'result', 'viewdb', 'test');
// 生产环境建议关闭 'viewdb', 'test'
$invalidActions = array('check', 'notify', 'return', 'pay', 'result', 'viewdb', 'test');
if (!$action || !in_array($action, $invalidActions)) {
return;
}
$logger->debug('[ACT:' . $action . '] ----- action start -----');
$zhifufm = new zhifufmCore();
$methodName = 'api' . ucfirst(strtolower($action));
$logger->debug('[ACT:' . $action . '] => zhifufm.' . $methodName);
echo call_user_func(array($zhifufm, $methodName));
$logger->debug('[ACT:' . $action . '] ------ action end ------');
exit();
}
public function initPaymentGateway()
{
global $logger;
$payType = static::payType;
$logger->debug("init payment gateway: $payType");
$this->id = ZHIFUFM_ID . '-' . $payType;
$this->icon = ZHIFUFM_URL . "/images/zhifufm-$payType.png";
$this->has_fields = false;
$this->method_title = __('zhifufm', ZHIFUFM_GATEWAY);
$this->method_description = __('zhifufm : functions', ZHIFUFM_GATEWAY);
$this->title = $this->get_option('title');
$logger->debug('title: ' . $this->method_title);
$logger->debug('title: ' . $this->title);
$this->description = $this->get_option('description');
$this->instructions = $this->get_option('instructions');
$this->init_form_fields();
$this->init_settings();
$logger->debug('settings: ' . json_encode($this->settings));
add_filter('woocommerce_payment_gateways', array($this, 'woocommerce_add_gateway'));
add_action('woocommerce_update_options_payment_gateways_' . $this->id, array($this, 'process_admin_options'));
add_action('woocommerce_update_options_payment_gateways', array($this, 'process_admin_options'));
add_action('woocommerce_email_before_order_table', array($this, 'email_instructions'), 10, 3);
add_action('woocommerce_thankyou_' . $this->id, array($this, 'thankyou_page'));
}
}
class ZHIFUFM_Gateway_Base extends ZHIFUFM_WC_Payment_Gateway
{
public function __construct()
{
$this->initPaymentGateway();
add_action('init', array($this, 'notifyFilter'), 10);
add_action('template_redirect', array($this, 'do_actions'), 0);
}
}
/**
* 支付宝免签扫码支付
* @author zhifu.fm
*
*/
class ZHIFUFM_Gateway_Alipay extends ZHIFUFM_Gateway_Base
{
const payType = 'alipay';
}
class ZHIFUFM_Gateway_Alipay_WEB extends ZHIFUFM_Gateway_Base
{
const payType = 'alipaysign';
}
class ZHIFUFM_Gateway_Alipay_FACE extends ZHIFUFM_Gateway_Base
{
const payType = 'alipay-facetoface';
}
class ZHIFUFM_Gateway_WeChat extends ZHIFUFM_Gateway_Alipay
{
const payType = 'wechat';
}
/* if (!session_id()) {
@session_start();
} */
$logger->debug('===> Current URI: ' . $_SERVER['REQUEST_URI']);
new ZHIFUFM_WC_Payment_Gateway();
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。