woocommerce对接第三方支付通道hambit

行云流水
2023-12-20 / 0 评论 / 301 阅读 / 正在检测是否收录...

前言

用wordpress+woocommerce做跨境独立站的朋友为了顺利收款,会对接各种国外的本地收款渠道。主流的用paypal等,不过通道越大。合规查的越严,小众的一些三方或四方通道,限制也会小一点。本文分享巴西通道hambit的对接过程。

接口文档地址

对接流程

一般都是申请通道账号,根据接口文档开发插件,然后测试调试,通过后上线。

核心代码

组织获取支付url的参数

                        $Body = array(
                                "amount"                => $amount,
                                "channelType"           => "PIX",
                                "externalOrderId"       => $mref,
                                "notifyUrl"             => $notify_url,
                                "remark"                => "USER",
                                "returnUrl"             => $return_url,
                                "inputCpf"              => 0
                        );

                        $sign_arr = $Body;
                        $sign_arr['access_key'] = $AccessKey;
                        $sign_arr['timestamp'] = $timestamp;
                        $sign_arr['nonce'] = $uuid_str;

                        $sign_str = $this->get_sign($sign_arr, $this->hambit_secret_key);

                        //请求头
                        $Headers = array(
                                'Content-Type'          => 'application/json;charset=utf-8',
                                'access_key'            => $AccessKey,
                                'timestamp'             => $timestamp,
                                'nonce'                 => $uuid_str,
                                'sign'                  => $sign_str
                        );

提交参数,获取url

                       $req_api = $this->req_api.'/api/v3/bra/createCollectingOrder';

                        $postData = json_encode($Body);

                        //打印参数
                        error_log(__METHOD__ . PHP_EOL .print_r($Body, true));

                         $args = array(
                                'headers'     => $Headers,
                                'timeout'     => 45,
                                'redirection' => 5,
                                'httpversion' => '1.0',
                                'blocking'    => true,
                                'body'        => $postData,
                        );

                        // 提交参数
                        $postRequest = wp_remote_post($req_api, $args);

                        if ($postRequest['response']['code'] === 200) {
                                $result = json_decode($postRequest['body'], true);
                        } else {
                                error_log(__METHOD__ . PHP_EOL . 'Code:' . $postRequest['response']['code'] . PHP_EOL. ' Error:' . $postRequest['response']['message']);

                                //抛出异常
                                throw new Exception("Unable to reach hambit Payments (" . $postRequest['response']['message'] . ")");
                        }

                        error_log(__METHOD__ . PHP_EOL .print_r($result, true));

                        //结果处理
                        if (($result['code'] =='200') && ($result['msgEn'] =='SUCCESS')) {
                                //写入数据库
                                $query = "insert into {$wpdb->prefix}hambit_data (mref, order_id, total_cost, currency, order_state, timestamp)  values ('".$mref."', '". $order_id . "',".$amount.",'". $currency_code."','I', now())";
                                $wpdb->query($query);

                                //支付链接
                                $PayUrl = $result['data']['cashierUrl'];

                                //跳转payurl
                                return array(
                                    'result' => 'success',
                                    'redirect' => $PayUrl
                                );
                        } else {
                                error_log(__METHOD__ .PHP_EOL. print_r($result, true));
                                throw new Exception("Unable to redirect payurl (" . $result['msg'] . ")");
                        }

支付成功后异步处理

                          if (($_SERVER['REQUEST_METHOD'] === 'POST') && preg_match("/wc_hambit_notify/i", $_SERVER['REQUEST_URI'])) {

                                //接收post json的数据
                                $response = file_get_contents("php://input");
                                error_log(__METHOD__ . PHP_EOL .print_r($response, true));

                                //参数
                                $respj = json_decode($response, true, 512, JSON_BIGINT_AS_STRING);

                                //判断
                                if ($respj['orderStatus'] == 'Completed') {
                                        #订单号
                                        $mref = $respj['externalOrderId'];
                                        $sref = $respj['orderId'];

                                        #写入数据库
                                        $query = "update {$wpdb->prefix}hambit_data  set order_state = 'C' where mref = '".addslashes($mref)."'";
                                        $wpdb->query($query);

                                        #后续处理
                                        $check_query = $wpdb->get_results("SELECT order_id FROM {$wpdb->prefix}hambit_data WHERE mref = '".addslashes($mref)."'", ARRAY_A);
                                        $check_query_count = count($check_query);
                                        if($check_query_count >= 1){
                                                $order_id= $check_query[0]['order_id'];

                                                $order = new WC_Order($order_id);
                                                $statustr = $this->hambit_processing;

                                                $order->update_status($statustr, __('Order has been paid by ID: ' . $sref, 'hambit-for-woocommerce'));
                                                wc_reduce_stock_levels( $order->get_id() );

                                                add_post_meta( $order_id, '_paid_date', current_time('mysql'), true );
                                                update_post_meta( $order_id, '_transaction_id', wc_clean($order_id) );

                                                $order->payment_complete(wc_clean($order_id));
                                                $woocommerce->cart->empty_cart();
                                        }

                                }

                                //接口返回
                                $return_resp = array(
                                    "code"   =>  200,
                                    "success"  =>  true
                                );
                                $jsonResponse = json_encode($return_resp);

                                exit($jsonResponse);
                        }

项目完整代码

【支付插件】woocommerce对接第三方支付接口hambit

评论 (0)

取消
只有登录/注册用户才可评论