myparcelnl / woocommerce

MyParcel plug-in for WooCommerce
https://developer.myparcel.nl/nl/documentatie/10.woocommerce.html
MIT License
13 stars 21 forks source link

Non-NL postcode returns error but doesn't block shipping #645

Open wgroenewold opened 3 years ago

wgroenewold commented 3 years ago

Describe the bug When you set WooCommerce to only ship to "Nederland" it's still possible to place an order with a non-NL postcode.

Steps to reproduce this behaviour

  1. Place order.
  2. Use non-NL postal code e.g. 3360 (= Belgium)
  3. Console gives {"errors":[{"code":3505,"message":"postal_code doesn't look like a postal code for country NL"}],"message":""}
  4. Place order.

Expected behaviour Block order and give notification feedback on frontend.

Details

Mitchell-MyParcel commented 3 years ago

@wgroenewold: We understand your wish, but the error you are referring to is generated by our delivery options module. This module is not built as a means to do some kind of address check.

We are aware of the wish to add an address check to our plugin. It is on our backlog but we don't have any plans to develop it soon. In the mean time we advise you to use the address check from wp-overnight: https://wpovernight.com/downloads/woocommerce-postcode-checker/

wgroenewold commented 3 years ago
use GuzzleHttp;

/**
 * Check if address is marked valid by PostNL.
 */
class pnlf_invalidaddress {
    /**
     * Class constructor.
     */
    public function __construct() {
        add_action( 'woocommerce_after_checkout_validation', array( $this, 'validate' ), 10, 2 );
    }

    public function validate($fields, $errors) {
            $data = array(
                'package_type' => 'package',
                'include' => 'shipment_options',
                'platform' => 'myparcel',
                'carrier' => 'postnl',
                'cc' => 'nl',
                'city' => $fields['shipping_city'],
                'number' => $fields['shipping_house_number'],
                'postal_code' => $fields['shipping_postcode'],
            );

            $client = new GuzzleHttp\Client(['base_uri' => 'https://api.myparcel.nl//delivery_options/']);

            $result = $client->request('GET', '?' . http_build_query($data));

            $result = (string) $result->getBody();
            $result = json_decode( $result, true );

            if(array_key_exists('errors', $result) && is_array($result['errors'])){
                foreach($result['errors'] as $item){
                    $errors->add('validation', $item['message']);
                }
            }
    }
}