如何获取WooCommerce货运跟踪API并将其呈现在React Native中

时间:2019-02-15 10:37:24

标签: react-native woocommerce-rest-api

我目前已经尝试在React Native App上实现“ WooCommerce货运跟踪” API。因此,基本上,我只是希望客户可以看到他们的跟踪号,并且可以单击跟踪号(作为url)以在我的React Native App中打开。

当前,我的应用程序“查看订单”(作为客户)如下所示: view order

这是我在src / containers / MyOrders / index.js中的代码

        /** @format */

import React, { PureComponent } from "react";
import {
  Animated,
  Platform,
  RefreshControl,
  FlatList,
  View,
} from "react-native";
import { connect } from "react-redux";
import { AnimatedHeader } from "@components";
import { Languages, withTheme } from "@common";
import styles from "./styles";
import OrderEmpty from "./Empty";
import OrderItem from "./OrderItem";

const AnimatedFlatList = Animated.createAnimatedComponent(FlatList);

class MyOrders extends PureComponent {
  state = { scrollY: new Animated.Value(0) };

  componentDidMount() {
    this.fetchProductsData();
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.carts.cartItems != nextProps.carts.cartItems) {
      this.fetchProductsData();
    }
  }

  fetchProductsData = () => {
    const { user } = this.props.user;
    if (typeof user === "undefined" || user === null) return;

    this.props.fetchMyOrder(user);
  };

  renderError(error) {
    return (
      <OrderEmpty
        text={error}
        onReload={this.fetchProductsData}
        onViewHome={this.props.onViewHomeScreen}
      />
    );
  }

  renderRow = ({ item, index }) => {
    return (
      <OrderItem key={index.toString()} item={item} theme={this.props.theme} />
    );
  };

  render() {
    const data = this.props.carts.myOrders;
    const {
      theme: {
        colors: { background },
      },
    } = this.props;

    if (typeof data === "undefined" || data.length == 0) {
      return (
        <OrderEmpty
          text={Languages.NoOrder}
          onReload={this.fetchProductsData}
          onViewHome={this.props.onViewHomeScreen}
        />
      );
    }

    return (
      <View style={[styles.listView, { backgroundColor: background }]}>
        <AnimatedHeader
          scrollY={this.state.scrollY}
          label={Languages.MyOrder}
          activeSections={this.state.activeSection}
        />
        <AnimatedFlatList
          data={data}
          onScroll={Animated.event(
            [{ nativeEvent: { contentOffset: { y: this.state.scrollY } } }],
            { useNativeDriver: Platform.OS !== "android" }
          )}
          scrollEventThrottle={1}
          keyExtractor={(item, index) => `${item.id} || ${index}`}
          contentContainerStyle={styles.flatlist}
          renderItem={this.renderRow}
          refreshControl={
            <RefreshControl
              refreshing={this.props.carts.isFetching}
              onRefresh={this.fetchProductsData}
            />
          }
        />
      </View>
    );
  }
}
const mapStateToProps = ({ user, carts }) => ({ user, carts });
function mergeProps(stateProps, dispatchProps, ownProps) {
  const { dispatch } = dispatchProps;
  const { actions } = require("@redux/CartRedux");
  return {
    ...ownProps,
    ...stateProps,
    fetchMyOrder: (user) => {
      actions.fetchMyOrder(dispatch, user);
    },
  };
}
export default connect(
  mapStateToProps,
  null,
  mergeProps
)(withTheme(MyOrders));

这是我的代码在src / containers / MyOrders / OrderItem.js中,显示“查看订单”屏幕:

/** @format */

import React from "react";
import { TouchableOpacity, FlatList, Text, View } from "react-native";
import Accordion from "react-native-collapsible/Accordion";

import { Constants, Languages } from "@common";
import styles from "./styles";

const cardMargin = Constants.Dimension.ScreenWidth(0.05);

export default class OrderItem extends React.PureComponent {
  state = { activeSections: [] };

  _setSections = () => {
    this.setState({
      activeSections: this.state.activeSections.length ? [] : [0],
    });
  };

  _renderItemOrder = ({ item, index }) => {
    return (
      <View
        style={{
          flexDirection: "row",
          justifyContent: "space-between",
        }}>
        <Text
          style={{
            margin: 4,
            color: "#333",
            width: Constants.Dimension.ScreenWidth(0.6),
          }}
          numberOfLines={2}
          ellipsizeMode="tail">
          {item.name}
        </Text>

        <Text
          style={{
            margin: 4,
            color: "#333",
            alignSelf: "center",
          }}>
          {`x${item.quantity}`}
        </Text>

        <Text
          style={{
            margin: 4,
            color: "#333",
            alignSelf: "center",
          }}>
          {item.total}
        </Text>
      </View>
    );
  };

  render() {
    const {
      theme: {
        colors: { text },
      },
      item,
    } = this.props;

    const order = item;

    if (typeof order.line_items === "undefined") {
      return this.renderError(Languages.NoOrder);
    }

    const renderAttribute = (label, context, _style) => {
      return (
        <View style={styles.row}>
          <Text style={[styles.rowLabel, { color: text }]}>{label}</Text>
          <Text style={[styles.rowLabel, _style, { color: text }]}>
            {context}
          </Text>
        </View>
      );
    };

    const dateFormat = (date) => {
      const year = date.substr(0, 4);
      const month = date.substr(5, 2);
      const day = date.substr(8, 2);
      return `${day}/${month}/${year}`;
    };

    return (
      <View style={{ margin: cardMargin, marginBottom: 0 }}>
        <View style={styles.labelView}>
          <Text style={styles.label}>#{order.number}</Text>
        </View>
        <View style={{ padding: 5 }}>
          {renderAttribute(Languages.OrderDate, dateFormat(order.date_created))}
          {renderAttribute(Languages.OrderStatus, order.status.toUpperCase())}
          {renderAttribute(Languages.OrderPayment, order.payment_method_title)}
          {renderAttribute(
            Languages.OrderTotal,
            `${order.currency} ${order.total}`,
            {
              fontWeight: "bold",
              fontSize: 16,
              fontFamily: Constants.fontHeader,
              color: "#333",
            }
          )}
          <Accordion
            activeSections={this.state.activeSections}
            underlayColor="transparent"
            sections={[{}]}
            onChange={this._setSections}
            renderHeader={() => {
              return (
                <TouchableOpacity
                  style={{ flex: 1, alignItems: "flex-end" }}
                  onPress={this._setSections}>
                  <Text style={styles.orderDetailLabel}>
                    {Languages.OrderDetails}
                  </Text>
                </TouchableOpacity>
              );
            }}
            renderContent={() => {
              return (
                <FlatList
                  overScrollMode="never"
                  contentContainerStyle={{ backgroundColor: "#FFF" }}
                  enableEmptySections
                  keyExtractor={(obj, i) => `${i}`}
                  data={order.line_items}
                  renderItem={this._renderItemOrder}
                />
              );
            }}

          />
        </View>
      </View>
    );
  }
}

令我困惑的是端点。 WooCommerce Order API端点为/ wp-json / wc / v2 / orders / 我使用邮递员查看订单的数组,这里是:

{
    "id": 7141,
    "parent_id": 0,
    "number": "7141",
    "order_key": "wc_order_xxxxxxxxx",
    "created_via": "admin",
    "version": "3.5.2",
    "status": "processing",
    "currency": "IDR",
    "date_created": "2019-02-15T00:12:56",
    "date_created_gmt": "2019-02-14T17:12:56",
    "date_modified": "2019-02-15T18:27:08",
    "date_modified_gmt": "2019-02-15T11:27:08",
    "discount_total": "0",
    "discount_tax": "0",
    "shipping_total": "0",
    "shipping_tax": "0",
    "cart_tax": "0",
    "total": "240000",
    "total_tax": "0",
    "prices_include_tax": false,
    "customer_id": 3,
    "customer_ip_address": "",
    "customer_user_agent": "",
    "customer_note": "",
    "billing": {
        "first_name": "Demo",
        "last_name": "Demo",
        "company": "",
        "address_1": "",
        "address_2": "",
        "city": "",
        "state": "SU",
        "postcode": "",
        "country": "ID",
        "email": "demo@xxx.xx",
        "phone": "0812"
    },
    "shipping": {
        "first_name": "",
        "last_name": "",
        "company": "",
        "address_1": "",
        "address_2": "",
        "city": "",
        "state": "",
        "postcode": "",
        "country": ""
    },
    "payment_method": "bacs",
    "payment_method_title": "Transfer via Bank",
    "transaction_id": "",
    "date_paid": "2019-02-15T18:27:08",
    "date_paid_gmt": "2019-02-15T11:27:08",
    "date_completed": null,
    "date_completed_gmt": null,
    "cart_hash": "",
    "meta_data": [
        {
            "id": 78913,
            "key": "_vc_post_settings",
            "value": {
                "vc_grid_id": []
            }
        },
        {
            "id": 78914,
            "key": "_wc_shipment_tracking_items",
            "value": [
                {
                    "tracking_provider": "ABC Courier",
                    "custom_tracking_provider": "",
                    "custom_tracking_link": "",
                    "tracking_number": "7141",
                    "date_shipped": "1550188800",
                    "tracking_id": "fc5ac1253e3af5bd46d2d9c70dd35ea2"
                }
            ]
        }
    ],
    "line_items": [
        {
            "id": 622,
            "name": "Dummy Product",
            "product_id": 4158,
            "variation_id": 4159,
            "quantity": 1,
            "tax_class": "",
            "subtotal": "240000",
            "subtotal_tax": "0",
            "total": "240000",
            "total_tax": "0",
            "taxes": [],
            "meta_data": [
                {
                    "id": 10541,
                    "key": "colour",
                    "value": "Red"
                }
            ],
            "sku": "IGLA",
            "price": 240000
        }
    ],
    "tax_lines": [],
    "shipping_lines": [],
    "fee_lines": [],
    "coupon_lines": [],
    "refunds": [],
    "_links": {
        "self": [
            {
                "href": "https://www.xxx.xx/wp-json/wc/v2/orders/7141"
            }
        ],
        "collection": [
            {
                "href": "https://www.xxx.xx/wp-json/wc/v2/orders"
            }
        ],
        "customer": [
            {
                "href": "https://www.xxx.xx/wp-json/wc/v2/customers/3"
            }
        ]
    }
}

您可以使用_wc_shipment_tracking_items键看到位于meta_data内的货运跟踪数据,并且我们也看到由于此处未列出而无法获取货运跟踪URL。

但是,如果我使用WooCommerce货运跟踪API端点/ wp-json / wc / v2 / orders / shipment-trackings /,则为数组:

[
    {
        "tracking_id": "fc5ac1253e3af5bd46d2d9c70dd35ea2",
        "tracking_provider": "ABC Courrier",
        "tracking_link": "https://abc.xx/track/?number=000123",
        "tracking_number": "000123",
        "date_shipped": "2019-02-15",
        "_links": {
            "self": [
                {
                    "href": "https://www.xxx.xx/wp-json/wc/v2/orders/7141/shipment-trackings/fc5ac1253e3af5bd46d2d9c70dd35ea2"
                }
            ],
            "collection": [
                {
                    "href": "https://www.xxx.xx/wp-json/wc/v2/orders/7141/shipment-trackings"
                }
            ],
            "up": [
                {
                    "href": "https://www.xxx.xx/wp-json/wc/v2/orders/7141"
                }
            ]
        }
    }
]

如何获取货运跟踪数据并将其呈现在内部 查看顺序屏幕上的“手风琴”部分?我希望跟踪数据不是meta_data,因此很容易呈现。

我曾尝试用谷歌搜索所有类似内容并添加一些代码,但没有成功。任何帮助将不胜感激。 :)

0 个答案:

没有答案