WordPress添加支付宝网关到woocomerce

Published
2023-08-12
浏览次数 :  69

首先添加woo的支付关口的class:

include_once( plugin_dir_path( __FILE__ ) . '../woocommerce/includes/gateways/class-wc-payment-gateway.php' );

然后创建支付宝支付的class延续自woo的支付class :

class WC_Gateway_Alipay extends WC_Payment_Gateway {

  public function __construct() {
    // Initialize gateway settings
    $this->id = 'alipay'; 
    $this->icon = ''; 
    $this->has_fields = false;
    $this->method_title = 'Alipay';
    $this->method_description = 'Allows payments via Alipay';
   
    // Load the settings
    $this->init_form_fields();
    $this->init_settings(); 
    
    // Define user set variables
    $this->title = $this->get_option('title');
    $this->description = $this->get_option('description');
    $this->alipay_pid = $this->get_option('alipay_pid');
    $this->alipay_key = $this->get_option('alipay_key');
    
    // Actions
    add_action('woocommerce_update_options_payment_gateways_' . $this->id, array($this, 'process_admin_options'));
  }

  public function process_payment( $order_id ) {
    // Payment processing
  }  

  public function init_form_fields() {
    // Define all settings fields here
  }

}

然后注册支付宝网关:

add_filter( 'woocommerce_payment_gateways', 'add_alipay_gateway' );
function add_alipay_gateway( $gateways ) {
  $gateways[] = 'WC_Gateway_Alipay'; 
  return $gateways;
}

在支付界面展示支付宝接口:

function add_custom_alipay_option() {
    if (is_checkout() && class_exists('Custom_Alipay_Gateway')) {
        $gateway = new Custom_Alipay_Gateway();
        $gateway->payment_fields();
    }
}
add_action('woocommerce_review_order_before_payment', 'add_custom_alipay_option');

接入支付宝接口

用guzzle来发送请求

composer require guzzlehttp/guzzle

用alipai api创建支付url

$apiUrl = 'https://openapi.alipay.com/gateway.do'; // Alipay API endpoint

$params = [
    'app_id' => 'YOUR_APP_ID',
    'method' => 'alipay.trade.page.pay',
    'charset' => 'utf-8',
    'sign_type' => 'RSA2',
    'timestamp' => date('Y-m-d H:i:s'),
    'version' => '1.0',
    'notify_url' => 'YOUR_NOTIFY_URL',
    'biz_content' => json_encode([
        'subject' => 'Order Title',
        'out_trade_no' => 'YOUR_ORDER_ID',
        'total_amount' => 'TOTAL_AMOUNT',
        // ... other required parameters
    ]),
];

// Sign the request
// ... code to sign the request using your private key

// Make the API call
// ... use Guzzle or another HTTP library to send a POST request

执行返回的动作

// Handle the return URL
if ($_GET['trade_status'] === 'TRADE_SUCCESS') {
    // Payment successful, update your database or perform necessary actions
} else {
    // Payment failed, handle accordingly
}

// Handle the notification callback
// ... validate the Alipay callback signature and process payment status

接入的完整代码

<?php

// Composer autoload
require 'vendor/autoload.php';

use GuzzleHttp\Client;

// Alipay API configuration
$appId = 'YOUR_APP_ID';
$privateKey = 'YOUR_APP_PRIVATE_KEY';
$publicKey = 'ALIPAY_PUBLIC_KEY';
$notifyUrl = 'https://yourdomain.com/notify.php'; // Callback URL for notifications

// Create an HTTP client
$client = new Client();

// Prepare parameters for creating a payment URL
$params = [
    'app_id' => $appId,
    'method' => 'alipay.trade.page.pay',
    'charset' => 'utf-8',
    'sign_type' => 'RSA2',
    'timestamp' => date('Y-m-d H:i:s'),
    'version' => '1.0',
    'notify_url' => $notifyUrl,
    'biz_content' => json_encode([
        'subject' => 'Order Title',
        'out_trade_no' => uniqid(), // Replace with your order ID generation logic
        'total_amount' => '10.00',  // Replace with the actual total amount
        // ... other required parameters
    ]),
];

// Generate the sign
ksort($params);
$paramString = urldecode(http_build_query($params));
$sign = openssl_sign($paramString, $signature, $privateKey, OPENSSL_ALGO_SHA256);
$sign = base64_encode($signature);
$params['sign'] = $sign;

// Make the API call to get the payment URL
$response = $client->request('POST', 'https://openapi.alipay.com/gateway.do', [
    'form_params' => $params,
]);

$data = json_decode($response->getBody(), true);

// Redirect the user to Alipay payment page
if ($data['alipay_trade_page_pay_response']['code'] === '10000') {
    header('Location: ' . $data['alipay_trade_page_pay_response']['qr_code']);
    exit;
} else {
    echo 'Error creating payment URL.';
}

?>

添加支付程序,对接到 alipay api

public function process_payment( $order_id ) {

  global $woocommerce;
    
  // Get order details
  $order = new WC_Order( $order_id );

  // Prepare payment data
  $data = array(
    'out_trade_no' => $order_id, 
    'total_amount' => $order->get_total(),
    'subject' => get_bloginfo('name'),
  );
  
  // Convert to urlencoded string
  $params = http_build_query($data); 

  // Alipay API
  $alipay_url = "https://mapi.alipay.com/gateway.do?{$params}";

  // Redirect to Alipay
  return array(
    'result' => 'success',
    'redirect' => $alipay_url
  );

}

public function successful_request( $posted ) {

  // Check Alipay signature
  if( !$this->verify_alipay_signature($posted) ) {
    return;
  }

  // Payment details posted by Alipay   
  $order_id = $posted['out_trade_no'];
  $paid_amount = $posted['total_amount'];

  // Update order
  $order = wc_get_order($order_id);
  $order->payment_complete($paid_amount);

  $woocommerce->cart->empty_cart();
        
  // Redirect to success page
  wp_redirect($this->get_return_url($order));
  exit;

}

private function verify_alipay_signature($data) {
  // Verify signature
  // Details here: https://global.alipay.com/docs/ac/Associate/verify
  // Return true or false
}

标签:, ,
Top