WooCommerce对接第三方支付插件开发(二)

2023-11-17 14:09:10 浏览数 (3)

前言

又有了新的需求,需要对接uepay。在 WooCommerce对接第三方支付插件开发 基础上修改,第三方接口大同小异,无非是更改需要提交的参数和加密方式。本次需要将返回的支付链接转换成二维码。直接调用google接口实现。

获取支付链接

代码语言:javascript复制
        public function generate_form($order_id)
        {
            global $woocommerce, $wpdb;
            $order = new WC_Order( $order_id );

            //打开订单检查页面
            define( 'WOOCOMMERCE_CHECKOUT', true );


             //商品信息
            foreach ($order->get_items() as $item_id => $item ) {
                    $name = $item -> get_name();
                    $quantity = $item -> get_quantity();
                }

            //订单号
            $mref = "REF".date("YmdHis", time() 8*60*60).substr(md5(uniqid(rand(), true)), 0, 9);

                    WC()->cart->calculate_totals();
                    $amountcents = round($order->get_total() * 100);

                    if($amountcents==0){
                        $order_id = wc_get_order_id_by_order_key($_GET['key']);
                        $order    = wc_get_order( $order_id );
                        $amountcents = round($order->get_total() * 100);
                    }

            //商户信息
            $MerchantNo  =  $this->uepay_merchantno;

                    //用户邮箱
                    $customer_mail = $order->get_billing_email();

              //收货人和收货地址
                $shipping_formatted_name = $order->get_formatted_billing_full_name();
                $shipping_formatted_address = $order->get_formatted_billing_address();

                //币种
                //$currency_code = get_woocommerce_currency();
                $currency_code = 'MOP';

            //基本url
                        $base_url = esc_url( home_url( '/' ));

            //同步回调url
            $return_url = WC()->api_request_url( 'wc_uepay_return' ) ;
            $check = strpos($return_url, '?');
            if ( $check !== false) {
                $return_url = $return_url . "&mref=" . $mref;
            } else {
                $return_url = $return_url . "?mref=" . $mref;
            }

             // 构造提交参数
                $arguments = array(
                    "orderNo"       => $mref,
                    "body"          => "聚合支付",
                    "detail"        => "{ "goods_detail":[ { "goods_name":"" . $name ."", "quantity":" . $quantity . ","price": " . $amountcents . " } ], "consignee":"" . $shipping_formatted_name . "" , "consignee_addres":"" . $shipping_formatted_address . "" }",
                    "amount"        => $amountcents,      // 分
                    "cny"           => $currency_code,
                    "time"          => time(),
                    "notifyUrl"     => WC()->api_request_url( 'wc_uepay_notify' ),   //异步,注意去掉  woocommerce_api_
                    "backUrl"       => $return_url,   //同步回调地址
                    "extendInf"     => "{ "subMerNo":"30011 ","subMerName":"H5商戶", "storeId":"test1", "storeName":"H5門店", "terminalId":"P00001" }"
                );

                //构造提交参数
                $Body = array(
                    "appSource"          => "2",
                    "appVersion"         => "1.4",
                    "merchantNo"         => $MerchantNo,
                    "requestType"        => "UNIFIEDORDER",
                    "tradeType"          => "INTAPI"
                );

                $unsign_arr = array_merge($Body, $arguments);
                ksort($unsign_arr);
                //error_log(__METHOD__ . PHP_EOL .print_r($unsign_arr, true));

                //待签名字符串拼接
                $unsign_str = "";

                foreach ($unsign_arr as $k => $v){
                    $unsign_str = $unsign_str . $k . '=' . $v . '&';
                }

                $unsign_str = $unsign_str . 'key=' . $this->uepay_paykey;

                //error_log(__METHOD__ . PHP_EOL .print_r($unsign_str, true));

                #签名
                $clientSign = md5($unsign_str);

                $Body["arguments"]  = $arguments;

                $Body["clientSign"] = strtoupper($clientSign);

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

            //构建提交变量
            $args = array(
                                'headers'    => array( 'Content-Type' => 'application/json', 'charset' => 'utf-8' ),
                                'timeout'     => 45,
                                'redirection' => 5,
                                'httpversion' => '1.0',
                                'blocking'    => true,
                                'body'        => json_encode($Body),
                        );

            $postRequest = wp_remote_post($this->uepay_api, $args);

            if ($postRequest['response']['code'] === 200) {
                        $result = json_decode($postRequest['body'], true, 512, JSON_BIGINT_AS_STRING);
                    } else {
                        error_log(__METHOD__ . PHP_EOL . 'Code:' . $postRequest['response']['code'] . PHP_EOL. ' Error:' . $postRequest['response']['message']);
                        throw new Exception("Unable to reach Viva Payments (" . $postRequest['response']['message'] . ")");
                    }

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

                    if ($result['retCode'] === '0000') {
                            $OrderNo = $result['results']['orderNo'];
                               $PayUrl = $result['results']['payUrl'];
                    } else {
                            throw new Exception("Unable to create order code (" . $result['Msg'] . ")");
                    }

                    $query = "insert into {$wpdb->prefix}uepay_data (ref, ordercode, email, orderid, total_cost, currency, order_state, timestamp) values ('".$mref."', '".$OrderNo."','". $customer_mail ."','". $order_id . "',$amountcents,'".$currency_code."','I', now())";
                    $wpdb->query($query);


                return
                         'Scan the QR code to complete the payment'.
                        ''.
                            ''.
                        ''.
                        ''.
                            ''.__('Pay Completed', 'uepay-for-woocommerce').''.
                            ''.__('Cancel', 'uepay-for-woocommerce').''.
                        '';
        }

异步回调代码

代码语言:javascript复制
    function check_ipn_response()
        {
            global $woocommerce, $wpdb;

            if (($_SERVER['REQUEST_METHOD'] === 'POST') && preg_match("/wc_uepay_notify/i", $_SERVER['REQUEST_URI'])) {
                $response = file_get_contents("php://input");
                error_log(__METHOD__ . PHP_EOL .print_r($response, true));

                if ( $response ) {
                    $res_data = json_decode($response, true, 512, JSON_BIGINT_AS_STRING);

                    $statustr = $this->uepay_processing;

                    #待签名字符串拼接
                    $unsign_str = '';
                    foreach ($res_data as $k => $v){
                        if ( $k == 'sign') { continue; }
                        $unsign_str = $unsign_str . $k . '=' . $v . '&';
                    }

                    $unsign_str = $unsign_str . 'key=' . $this->uepay_paykey;


                    #签名
                    $checksum = strtoupper(md5($unsign_str));

                    //error_log(__METHOD__ . PHP_EOL .print_r($unsign_str, true));
                    //error_log(__METHOD__ . PHP_EOL .print_r($checksum, true));

                    if ($checksum == $res_data['sign']) {
                        $tm_ref = $res_data['orderNo'];
                        $check_query = $wpdb->get_results("SELECT orderid,order_state FROM {$wpdb->prefix}uepay_data WHERE ref = '".addslashes($tm_ref)."'", ARRAY_A);
                        $check_query_count = count($check_query);

                        if( $check_query_count >= 1 ) {
                            if($check_query[0]['order_state'] == 'I' && $res_data['tradeState'] == 'SUCCESS') {
                                $query = "update {$wpdb->prefix}uepay_data set order_state='C' where ref='".addslashes($tm_ref)."'";
                                $wpdb->query($query);

                                $inv_id = $check_query[0]['orderid'];
                                $order = new WC_Order($inv_id);

                                $order->update_status($statustr, __('Order has been paid by ID: ' . $res_data['orderNo'], 'uepay-for-woocommerce'));
                                wc_reduce_stock_levels( $order->get_id() );

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

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

                    }
                }
                //接口返回
                exit("SUCCESS");
            }

        }

0 人点赞