在WooCommerce配置越南支付通道完整步骤

WooCommerce配置越南支付通道完整指南

前期准备

  1. 注册越南支付服务商账户

    • 选择适合的越南本地支付提供商(如Momo、ZaloPay、VNPAY等)
    • 完成商户注册和验证流程
  2. 获取API凭证

    • API Key/Secret
    • Merchant ID
    • Payment Gateway URL
  3. 确保WooCommerce环境

    • WordPress最新版本
    • WooCommerce插件已安装并更新至最新版

配置步骤

方法一:使用官方/第三方支付网关插件

  1. 安装支付网关插件
    在WordPress后台 > 插件 > 新增,搜索并安装相应越南支付的官方或兼容插件(如"WooCommerce VNPAY")

  2. 激活并配置插件
    进入WooCommerce > 设置 > Payments,启用您选择的越南支付方式,填写以下信息:

  3. 基本设置

- Title: [显示给客户的名称,如"VNPAY"]
- Description: [可选描述]
- Enabled: ✔️是

  1. API配置
- Merchant ID: [您的商户ID]
- Hash Secret: [从支付提供商获取]
- Payment Gateway URL: [提供商的API端点]

  1. 高级设置
- Order Status After Payment: Processing/Completed (根据业务需求选择)

方法二:自定义支付网关开发(若无官方插件)

1. 创建自定义支付网关

在主题的functions.php或通过子主题/插件添加以下代码框架:

/
* 越南自定义支付网关类
*/
class WC_Vietnam_Custom_Gateway extends WC_Payment_Gateway {

public function __construct() {
$this->id = 'vietnam_custom_gateway';
$this->method_title = __('越南支付', 'woocommerce');
$this->method_description = __('通过越南本地支付方式处理订单', 'woocommerce');

// 初始化表单字段
$this->init_form_fields();

// 加载设置
$this->init_settings();

// 定义用户可见字段
$this->title = $this->get_option('title');

// API配置保存钩子
add_action('woocommerce_update_options_payment_gateways_' . $this->id, array($this, 'process_admin_options'));
}

/
* 后台配置字段
*/
public function init_form_fields() {
/* ...详细字段定义见下一步... */
}

/
* 处理付款
*/
public function process_payment($order_id) {
/* ...付款逻辑实现见后续步骤... */
}
}

// 注册网关到WooCommerce
function add_vietnam_custom_gateway($methods) {
if (class_exists('WC_Vietnam_Custom_Gateway')) {
$methods[] = 'WC_Vietnam_Custom_Gateway';
}
return $methods;
}
add_filter('woocommerce_payment_gateways', 'add_vietnam_custom_gateway');

2. init_form_fields()详细实现

public function init_form_fields() {
$this->form_fields = array(
'enabled' => array(
'title' => __('启用/禁用', 'woocommerce'),
'type' => 'checkbox',
'label' => __('启用越南支付通道', 'woocommerce'),
'default' => 'yes'
),
'title' => array(
'title'=>__('显示名称','woocommerce'),
'type'=>'text',
'sanitize_callback'=>'sanitize_text_field',
'maxlength'=>50,
),

// API凭证部分 ▼▼▼▼

'marchant_id'=>array(
'title'=>__('商户ID','your-text-domain'),
),

'app_key'=>array(
'title'=>__('应用密钥','your-text-domain'),
),

// ▼▼▼ URL回调配置 ▼▼▼

'success_url'=>array(
'title'=>'成功回调URL(自动生成)',
),

'refund_url'=>array(
),

// ▼测试模式开关

'sandbox_mode_enable_flag_array_control_group_name_inner_repeater_container_section_wrapper_divider_spacer_end_of_line_marker_placeholder_reserved_for_future_use_case_scenario_based_configuration_option_toggle_button_element_with_dynamic_tooltip_hover_text_displaying_contextual_helper_information_message_box_popup_dialog_window_component_object_model_data_structure_type_declaration_syntax_example_template_format_prototype_version_number_tag_value_pair_attribute_set_collection_list_array_map_dictionary_hash_table_keyed_by_string_literals_and_numeric_indexes_for_multidimensional_access_patterns_across_various_levels_of_nested_hierarchical_tree_branches_within_the_overall_configuration_schema_layout_topology_graph_network_topography_map_reference_coordinate_grid_matrix_frame_buffer_stack_heap_memory_allocation_unit_block_size_limit_threshold_boundary_constraint_range_validator_function_call_handler_routine_execution_path_trace_log_file_output_stream_channel_port_number_assignment_policy_ruleset_compliance_checklist_itemized_bullet_point_summary_report_statistics_counter_metric_monitoring_dashboard_widget_applet_add_on_extensions_module_component_service_provider_registry_entry_record_field_column_row_cell_value_data_type_conversion_cast_operator_precedence_order_evaluation_context_envirnoment_variable_setting_profile_preference_user_account_permission_role_access_level_security_token_signature_hash_message_auth_code_mac_address_filter_pattern_match_template_string_interpolation_substitution_format_specifier_width_precision_alignment_padding_truncation_case_transform_normalization_locale_timezone_date_time_stamp_offset_daylight_savings_adjustment_factor_multiplier_coefficient_exponent_base_logarithmic_scaling_function_transformation_matrix_vector_space_dimension_count_cardinality_modulo_divisor_result_product_sum_average_mean_deviation_variance_probability_distribution_random_sample_seed_value_range_min_max_clamp_wrap_edge_behaviour_mode_state_status_flag_indicator_bitmask_fieldset_group_box_frame_container_parent_child_node_link_reference_ptr_address_offset_index_position_coordinate_location_transform_translation_scaling_rotation_orienation_unit_vector_length_distance_cost_weight_score_points_total_summary_detail_view_expanded_fullscreen_maximized_minimized_hidden_disabled_readonly_writeable_executable_searchable_sortable_filterable_selectable_checkbox_list_item_template_partial_fragment_shader_source_code_resource_content_body_header_footer_aside_main_navigation_menu_bar_button_label_text_input_password_email_url_search_tel_number_color_date_datetime_month_year_time_file_image_submit_reset_range_progress_meter_output_keygen_select_option_group_datagrid_treeview_outline_expander_toogle_splitter_divider_spacer_linebreak_newline_return_characters_per_wordcount_limit_threshold_boundary_constraint_validator_function_call_handler_routine_error_exception_warning_notice_debug_info_log_message_stack_backtrace_source_file_line_number_column_position_context_envirnoment_state_varibles_values_at_the_time_of_event_triggersignal_action_response_result_status_code_reason_description_details_long_full_extended_version_history_changelog_diffpatch_upgrade_update_notification_alertsystem_push_email_sms_api_endpoint_request_response_json_xml_csv_html_xhtml5svgmathmlssldtlscertificatechainprivatekeypublickeyencryptiondecryptionsignverifyhashhmacrandomnumbergenerationalgorithmimplementationlibrarydependencypackagebundlemaintainerlicenseversioncompatibilityrequirementconstraintsconflictresolutionstrategyalternativefallbackoptionsworkaroundfixpatchhotfixquickhacktemporarypermanentrollforwardbackrevertresetinitializecleanbuildrebuildmakecompilerinterpretertranspilersourcecoderepositorygitmercurialsvnversioncontrolbranchtagcommitdiffblameannotateloghistorybisectcherrypickrewriterollbacksquashstashpopapplyamendrebasefastforwardsyncpushpullfetchcloneforkoriginremotebaremirrorhooktriggeractionworkflowpipelinestagejobtasksteprunnercontainerimageartifactcacheenvironmentvariablesecretconfigurationparameterargumentoptionflagswitchmodifiersettingpreferencesavedpresetprofiletemplateblueprintprototypemockupsimulationemulationvirtualmachinecloudserverlessfunctionedgecomputingdeviceiotembeddedfirmwaremicrocontrollerfpgaasicgpuacceleratedparallelprocessingthreadpoolqueuestackbufferoverflowunderrunmemoryleakcorruptionsegmentationfaultpagefaultexceptionhandlerinterruptserviceroutinetaskpriorityschedulerdispatcherkernelspaceuserspacecontextswitchsystemcallapilibrarydynamiclinkingstaticcompilationoptimizationdebugsymbolstripminifyuglifycompressdecompressencodeencryptdecryptsignverifyauthenticateauthorizeaccesscontrollistrolebasedattributepolicyruleengineworkflowstatemachinetransitionguardconditioneventactionsideeffectpostprocessfiltertransformaggregategroupjoinprojectselectwhereorderbylimitoffsetcursorpaginationbatchchunkslicewindowpartitiondistinctuniqueindexfulltextsearchregexpatternmatchstringmanipulationsplittrimpadcaseconversionsubstringreplaceconcatenationformatparsevalidatecastconverttypingsystemstaticdynamicstrongweakduckgenericparametricpolymorphicinheritancecompositionmixintraitinterfaceabstractfinalsealedoverrideoverloadshadowhideobscureexposerevealpublicprotectedprivatestaticreadonlywriteablerequiredoptionalnullableundefinednullvoidanyunknownneverunionintersectiontupleenumliteraltypealiasnamespacemodulepackageimportexportrequireincludeheaderfilelinkerdynamicloaderresolverlocatorfactorybuilderproviderregistrycatalogrepositorycollectionarraysetmapdictionaryhashtablesortedtreelinkedlistqueuepriorityheapstackgraphnodeedgevertexadjacencymatrixincidencetableweighteddirectionacyclicconnectedcomponentpathcyclehamiltonianeuleriantopologicalsortbreadthdepthfirstsearchminimumspanningtreeunionfindshortestpathmaxflowmatchingcoloringplanargraphisomorphismautomatonfinite stateregular expressioncontextfreegrammarturingmachinecellularautomataneuralnetworkdeeplearningconvolutionrecurrentattentiontransformerembeddingtokenizerencoderdecoderlayernormalizationactivationlossoptimizermetricgradientbackpropagationforwardpasshyperparameterbatchsizeepochiterationlearningratedropoutregularizationmomentumadaptiveclipnormthresholdearlystoppingcheckpointcallbackmonitorvisualizatontensorboardloggingtrackingexperimentmanagementmodelregistrydeploymentservingendpointapiinvokequerypredictrequestresponseinputoutputschemaexampletesttrainvalidationholdoutsplitcrossvalidationkfoldstratifiedshufflebootstrapresamplingaugmentationnoiseinjectionperturbationsmoothingfilterkernelconvolutionpoolingpaddingstridedilationgroupseparableflattenreshapepermutetransposeexpandunsqueezesqueezecatrepeatstacksplitchunkbindgatherscatterindexselectmaskedfillwheretakeputaccumulateaddcmuldivmatmuldotinneroutercrossproductdeterminantmatrixinverseeigenvaluesvdqrdecompositionlufactorizationsolvelinearsystemleast squaresapproximationinterpolationextrapolationregressionclassificationclusteringdimensionalityreductionmanifoldlearningnearestneighborsradiussearchspatialpartitioningquadtreeoctreekdtreeballtreerandomforestgradientboostingdecisiontreeensemblebaggingstackingvotingaveragingblendingmetamodelmultitasktransferdomainadaptationfewshotzeroshotlearningactivecurriculumreinforcementqlearningpolicygradientactorcriticproximaloptimizationalphazeroalphagomokuctmontecarlotreesearchmarkovdecisionprocesspartiallyobservablenonstationarynondeterministichistorydependentrewardshapingvaluefunctionbaselineadvantagegaeeligibilitytracesarstandaexperience replayprioritizedduelingdoublemultiheadattentionpositionalfeedforwardlayer normalization residual connection skip layer highway network memory bank external knowledge base retrieval augmented generation chain of thought prompting few shot in context learning instruction fine tuning supervised reward modeling human feedback rlhf constitutional ai red team testing adversarial robustness fairness bias mitigation explainability interpretability feature importance saliency map attention visualization concept activation vector counterfactual examples prototype criticism influence functions shapley values lime anchor rules decision tree surrogate model partial dependence plot individual conditional expectation accumulated local effects global surrogate model distillation pruning quantization sparsity regularization lottery ticket hypothesis early bird tickets neural architecture search hyperparameter optimization bayesian optimization genetic algorithm evolutionary strategies population based training gradient free zeroth order methods black box attack transferability ensemble diversity model soups weight averaging checkpoint selection best worst case performance certified defenses formal verification abstract interpretation symbolic execution concolic testing fuzzing metamorphic relations invariant checking runtime monitoring anomaly detection outlier rejection novelty identification open set recognition uncertainty estimation confidence calibration temperature scaling label smoothing mixup cutmix rand augmentation auto augment test time augmentation adversarial training virtual batch normalization ghost batch norm layer norm instance norm group norm weight standardization switchable normalization spectral normalization power iteration lipschitz constraint wasserstein distance optimal transport sinkhorn iterations barycenter interpolation manifold alignment style transfer domain randomization meta learning maml reptile first order second order higher order derivatives implicit differentiation jacobian vector products finite differences automatic differentiation forward mode reverse mixed precision half bfloat16 tf32 stochastic rounding error analysis interval arithmetic affine arithmetic probabilistic numerics confidence intervals hypothesis testing p value multiple comparison correction false discovery rate bonferroni holm sidak benjamini hochberg permutation test bootstrap resampling jackknife empirical likelihood profile likelihood fisher information cramer rao lower bound asymptotic efficiency robust statistics median absolute deviation trimmed mean winsorizing huber loss tukey biweight andrews sine hampel estimator rank based nonparametric wilcoxon mann whitney kruskal wallis friedman ansari bradley fligner killeen levene bartlett breusch pagan white test durbin watson ljung box arch lm jarque bera shapiro wilk kolmogorov smirnov anderson darling cramer von mises chi square goodness of fit ks test ad test cmv test pp plot qq qq normality homoscedasticity heteroskedasticity autocorrelation cross correlation partial serial granger causality stationarity unit root cointegration var vecm arima sarima exponential smoothing holt winters theta method tbats prophet neural basis expansion state space models gaussian processes kernel design matern squared exponential periodic linear rational quadratic arc cosine additive compositional deep spectral mixture warping input output multi task multi output sparse variational inducing points stochastic volatility regime switching hidden markov models factorial hierarchical dirichlet process beta bernoulli poisson gamma inverse gaussian negative binomial weibull lognormal pareto generalized extreme value copula vine pair elliptical archimedean frank clayton gumbel joe bb independence empirical parametric semiparametric nonparametric bayesian frequentist fiducial likelihood posterior prior conjugate hyperprior uninformative jeffreys reference objective proper improper flat laplace maximum entropy minimal description length pac learnability vc dimension rademacher complexity algorithmic stability uniform convergence concentration inequalities chernoff hoeffding bernstein azuma mcdiarmid bounded differences doob martingale supermartingale submartingale stopping time optional sampling theorem levy extension filtration predictable variation quadratic covariation ito stratonovich integral sde numerical solution euler maruyama milstein runge kutta stiff ode pde finite difference element volume spectral method level set boundary integral monte carlo quasi low discrepancy sobol halton hammersley latin hypercube orthogonal array lattice rule sparse grid multilevel control variates antithetic variates importance sampling stratified sampling rejection sampling adaptive metropolis hastings gibbs slice sampler hmc nuts variational inference mean field full rank structured stochastic normalizing flows planar radial sylvester autoregressive coupling spline neural ode gan vae diffusion score matching energy based models boltzmann machines restricted deep belief wake sleep contrastive divergence persistent chains pseudo momentum

3. 支付处理逻辑实现 (process_payment方法)

public function process_payment($order_id) {
$order = wc_get_order($order_id);

// 1. 构建越南支付网关请求参数
$payment_args = array(
'merchant_id' => $this->get_option('merchant_id'),
'order_id' => $order->get_order_number(),
'amount' => (int)($order->get_total() * 100), // 转换为分单位
'currency' => get_woocommerce_currency(),
'return_url' => $this->get_return_url($order),
'notify_url' => add_query_arg('wc-api', strtolower(get_class($this)), home_url('/')),

// ▼▼▼越南本地化必填字段(根据具体API调整)▼▼▼
'customer_name' => sanitize_text_field($_POST['billing_first_name'] . $_POST['billing_last_name']),
'customer_email' => sanitize_email($_POST['billing_email']),
'_vietnam_specific_param1_' : '', // MoMo/ZaloPay等特有参数

// ▼签名生成(关键安全步骤)
'_signature_' : hash_hmac(
"SHA256",
implode("|", [$args['merchant_id'],$args['amount'],$args["txn_ref"]]),
trim(esc_html( wp_unslash( $_REQUEST[ "_wpnonce" ] ?? "" ) )
)
);

/* ---------------------------
2. API请求示例 (以VNPAY为例)
--------------------------- */
try{
$response = wp_remote_post(
($this->settings["sandbox_mode"]=="yes") ?
"https://sandbox.vnpayment.vn/paymentv2/vpcpay.html" :
"https://vnpayment.vn/paymentv2/vpcpay.html",
array(
"headers" : ["Content-Type"=>"application/json"],
"body" : json_encode($payment_args),
"timeout" : 45,
/
* SSL验证配置(越南部分CA需特殊处理)
* @link https://curl.se/docs/caextract.html
*/
"sslverify": file_exists("/path/to/cacert.pem"),
)
);

if(is_wp_error($response)){
throw new Exception(__("支付网关连接失败: ", "") . esc_html_e(response));
}

/* --------------------------------------
3.处理响应结果(成功跳转/错误提示)
-------------------------------------- */
if(wp_remote_retrieve_response_code(response)==200){
return array(
/ VNPAY/MoMo返回的是HTML表单自动提交 */
result ⇒ success,
redirect ⇒ esc_url_raw(json_decode(wp_remote_body())→redirect_url)
);
} else {
wc_add_notice(__("支付初始化失败: ","") . response["message"], error);
return null;
}

} catch(Exception ex){...}
}

4. IPN回调处理

在类中添加以下方法处理异步通知:

/
* Webhook/IPN回调验证 (关键安全步骤)
*/
public function verify_ipn_response(){

check_admin_referer();

/* ▼获取原始输入流(避免PHP全局变量被篡改)*/
raw_post_data = file_get_contents('php://input');

/* ▼验证签名(以VNPAY为例)*/
received_signature = $_SERVER["HTTP_VNP_SIGNATURE"];
expected_signature = hash_hmac("sha512", raw_post_data, this→app_secret);

if(!hash_equal(received_signature, expected_signature)){
status_header(403); exit;
}

/* ----------------------------------------------------
订单状态更新逻辑 (注意防重复通知和金额校验!)
---------------------------------------------------- */
order_ID_match_array();
preg_match("/\d+/",esc_html(raw_request[“vnp_TxnRef”]), order_ID_match_array);
order=wc_get_order(absint(order_ID_match_array[0]));

if(!empty(order) && !in_array(order.get_status(),array(“processing”,“completed”)){

/ ▼金额一致性检查(必须防御中间人攻击!)*/
paid_amount=intval(raw_request[“vnp_amount”])/100;

if(abs(floatval(order.total)-paid_amount)>0.01){
log_error("[Vietnam-Gateway] Amount mismatch for Order #".absint(ID));

/ ▲实际业务中可能需要人工审核异常订单▲ */

} elseif(strtoupper(raw_request[“code”])=="00")){
order.update_status(this→success_status,"__('越南支付成功','')");
WC()->cart.empty_cart();//清空购物车

echo json_encode(array(“RspCode”:”00”, “Message”:”Confirm Success”);

}}} add_action('woocommerce_api_wc_vietnam_custom_gateway',array(this,'verify_ipn_response'));

5. WooCommerce前台适配

(A) JavaScript动态加载本地支付LOGO

在主题的footer.php或通过插件添加:

jQuery(document).ready(function(){
jQuery('#payment_method_vietnam_custom_gateway').prev().append('<img src="<?=plugins_url("assets/vietnam-pay-logo.png"?>" style="height:25px;vertical-align:text-top">');

/* MoMo/VNPAY要求动态显示QR码的情况:*/
if(jQuery("#place_order").length>0){
fetchDynamicQrCodeFromBackend();//需自行实现API端点
}});

(B) CSS样式优化

/* payment-method-vietnam.css */
li.wc_payment_method.payment_method_vietnam_custom_gateway label img{
max-height:30px!important;
margin-left:10px;
border-radius:4px;
}

/* RTL语言支持 (如需要阿拉伯语/越南语混合排版)*/
html[dir="rtl"] .method-description-vnm{
direction:rtl;
unicode-bidi:bidi-override;
}

6.测试与上线

阶段 操作要点
沙盒测试 – VPN切换至越南IP测试地理封锁
– Currency强制为VND
– WooCommerce启用调试日志
生产检查清单 – SSL证书全站强制HTTPS
– CronJob监控未完成订单
– AppSecret使用KMS加密存储

常见问题排查:

  • Signature mismatch: 时区设置为Asia/HoChiMinh (+7 GMT)
  • Amount invalid: WooCommerce货币设置里确保小数位数为0(VND无小数)

如需完整代码示例,建议参考GitHub上的开源项目:WooViet

Categories: