Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,11 @@

package com.facebook.ads.sdk.serverside;


import com.facebook.ads.sdk.APIContext;
import com.facebook.ads.sdk.APIException;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
Expand Down Expand Up @@ -104,7 +103,12 @@ private Request createRequest(final List<Event> events, final String pixelId) {
final Map<String, Object> bodyParams = new HashMap();
bodyParams.put("accessKey", accessKey);
bodyParams.put("data", events);
final RequestBody requestBody = RequestBody.create(JSON, new Gson().toJson(bodyParams));
final RequestBody requestBody = RequestBody.create(
JSON,
new GsonBuilder()
.registerTypeAdapterFactory(new UserData.PostalCodeAdapterFactory())
.create()
.toJson(bodyParams));
return new Request.Builder()
.url(endpointURL + "/capi/" + pixelId + "/events")
.post(requestBody)
Expand Down Expand Up @@ -139,4 +143,4 @@ public void onResponse(final okhttp3.Call call, final okhttp3.Response response)
});
return future;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,7 @@ public EventRequest(String pixelId, APIContext context, List<Event> data,
.disableHtmlEscaping()
.registerTypeAdapter(CustomData.class, new CustomDataAdapter())
.registerTypeAdapter(AppData.class, new AppDataAdapter())
.registerTypeAdapterFactory(new UserData.PostalCodeAdapterFactory())
.create();
}

Expand Down
75 changes: 74 additions & 1 deletion src/main/java/com/facebook/ads/sdk/serverside/UserData.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,20 @@
package com.facebook.ads.sdk.serverside;

import com.facebook.ads.utils.ServerSideApiConstants;
import com.facebook.ads.utils.ServerSideApiUtil;
import com.facebook.ads.sdk.serverside.utils.Sha256GenderEnumListAdaptor;
import com.facebook.ads.sdk.serverside.utils.Sha256StringAdaptor;
import com.facebook.ads.sdk.serverside.utils.Sha256StringListAdaptor;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
Expand All @@ -35,7 +43,7 @@
/**
* UserData is a set of identifiers Facebook can use for targeted attribution.
*/
public class UserData {
public class UserData implements Cloneable {

@SerializedName(ServerSideApiConstants.EMAIL)
@JsonAdapter(Sha256StringListAdaptor.class)
Expand Down Expand Up @@ -1604,4 +1612,69 @@ private List<String> dedup(List<String> values) {
}
return new ArrayList(set);
}

private UserData copyWithNormalizedPostalCodes() {
if (zipcodes == null || countryCodes == null
|| countryCodes.size() != 1
|| countryCodes.get(0) == null) {
return this;
}

try {
UserData copy = (UserData) super.clone();
copy.zipcodes = new ArrayList<>(zipcodes.size());

for (String zipcode : zipcodes) {
if (zipcode == null || ServerSideApiUtil.isAlreadyHashed(zipcode)) {
copy.zipcodes.add(zipcode);
} else {
String normalized = ServerSideApiUtil.normalizePostalCode(
zipcode, countryCodes.get(0));

copy.zipcodes.add(normalized == null
? null
: ServerSideApiUtil.hash(normalized));
}
}

return copy;
} catch (CloneNotSupportedException e) {
throw new AssertionError(e);
}
}

static final class PostalCodeAdapterFactory implements TypeAdapterFactory {

@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!UserData.class.isAssignableFrom(type.getRawType())) {
return null;
}

final TypeAdapter<T> delegate =
gson.getDelegateAdapter(this, type);

return new TypeAdapter<T>() {

@Override
@SuppressWarnings("unchecked")
public void write(JsonWriter out, T value) throws IOException {
if (value == null) {
delegate.write(out, null);
return;
}

UserData copy =
((UserData) value).copyWithNormalizedPostalCodes();

delegate.write(out, (T) copy);
}

@Override
public T read(JsonReader in) throws IOException {
return delegate.read(in);
}
};
}
}
}
46 changes: 46 additions & 0 deletions src/main/java/com/facebook/ads/utils/ServerSideApiUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,52 @@ private static String validateEmail(String email) {
return email;
}

/**
* Normalizes a postal code using its country when available.
* Falls back to the existing behavior for unknown countries.
*/
public static String normalizePostalCode(String postalCode, String countryCode) {
if (postalCode == null) {
return null;
}

String country = countryCode == null
|| ServerSideApiUtil.isAlreadyHashed(countryCode)
? null
: countryCode.trim()
.toLowerCase(Locale.ROOT)
.replaceAll("[^a-z]", "");

if (!ISO_COUNTRY_LIST.contains(country)) {
return normalize(postalCode, ServerSideApiConstants.ZIP_CODE);
}

postalCode = postalCode.trim().toLowerCase(Locale.ROOT);
if (postalCode.isEmpty()) {
return null;
}

postalCode = postalCode.replaceAll("\\s+", "");
String normalized = postalCode.replace("-", "");

if (normalized.isEmpty()) {
throw new IllegalArgumentException(
"Invalid postalcode for the passed postalCode: '" + postalCode + "'.");
}

if (normalized.length() < 2) {
throw new IllegalArgumentException(
"Invalid postalcode format for the passed postalCode:" + normalized
+ ". Please check the passed postalcode.");
}

if ("us".equals(country) && normalized.length() > 5) {
normalized = normalized.substring(0, 5);
}

return normalized;
}

private static String normalizePostalCode(String postalCode) {

// Remove space characters in the Zip Code
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,4 +56,46 @@ public void filterAllEvents() throws APIException.FailedRequestException {
assertEquals(response.message, "No events to send");
assertEquals(response.responseCode, null);
}

@Test
public void NormalizeGatewayPostalCodeTest() throws Exception {
CAPIGatewayEndpoint endpoint =
new CAPIGatewayEndpoint("https://example.com", "ACCESS_KEY");

UserData userData = new UserData()
.countryCode("jp")
.zipcode("100-0001");

Event event = new Event().userData(userData);

java.lang.reflect.Method method =
CAPIGatewayEndpoint.class.getDeclaredMethod(
"createRequest", List.class, String.class);

method.setAccessible(true);

okhttp3.Request request = (okhttp3.Request) method.invoke(
endpoint,
java.util.Collections.singletonList(event),
"pixelId");

okio.Buffer buffer = new okio.Buffer();
request.body().writeTo(buffer);

String actual = com.google.gson.JsonParser
.parseString(buffer.readUtf8())
.getAsJsonObject()
.getAsJsonArray("data")
.get(0)
.getAsJsonObject()
.getAsJsonObject("user_data")
.getAsJsonArray("zp")
.get(0)
.getAsString();

assertEquals(
com.facebook.ads.utils.ServerSideApiUtil.hash("1000001"),
actual);
}

}
139 changes: 139 additions & 0 deletions src/test/java/com/facebook/ads/sdk/serverside/UserDataTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -196,4 +196,143 @@ public void EqualsAndHashCodeNotSameTest() {
assertNotEquals(userData1, userData2);
assertNotEquals(userData1.hashCode(), userData2.hashCode());
}

@Test
public void NormalizeLuxembourgPostalCodeTest() {
assertNormalizedPostalCode("lu", "L-9133", "l9133");
}

@Test
public void NormalizeJapanesePostalCodeTest() {
assertNormalizedPostalCode("jp", "100-0001", "1000001");
}

@Test
public void NormalizeUSPostalCodeTest() {
assertNormalizedPostalCode("us", "98121-9431", "98121");
}

private void assertNormalizedPostalCode(
String country, String postalCode, String expected) {
UserData userData = new UserData()
.countryCode(country)
.zipcode(postalCode);

String json = EventRequest.getGson().toJson(userData);

String actual = com.google.gson.JsonParser.parseString(json)
.getAsJsonObject()
.getAsJsonArray("zp")
.get(0)
.getAsString();

assertEquals(
com.facebook.ads.utils.ServerSideApiUtil.hash(expected),
actual);
}

@Test
public void NormalizeUSPostalCodeWithoutDashTest() {
assertNormalizedPostalCode("us", "021081234", "02108");
}

@Test
public void NormalizePostalCodeWithoutCountryTest() {
assertNormalizedPostalCode(null, "98121-9431", "98121");
}

@Test
public void PreserveAlreadyHashedPostalCodeTest() {
String hashed = com.facebook.ads.utils.ServerSideApiUtil
.hash("1000001");
assertNormalizedPostalCode("jp", hashed, "1000001");
}

@Test
public void PostalCodeSerializationDoesNotMutateUserDataTest() {
UserData userData = new UserData()
.zipcode("100-0001")
.countryCode("JP");

EventRequest.getGson().toJson(userData);

assertEquals("100-0001", userData.getZipcode());
assertEquals("JP", userData.getCountryCode());
}

@Test
public void NormalizeMultiplePostalCodesTest() {
UserData userData = new UserData()
.countryCode("jp")
.zipcodes(Arrays.asList("100-0001", "150-0001"));

com.google.gson.JsonArray actual =
com.google.gson.JsonParser.parseString(
EventRequest.getGson().toJson(userData))
.getAsJsonObject()
.getAsJsonArray("zp");

assertEquals(2, actual.size());

assertEquals(true, actual.contains(
new com.google.gson.JsonPrimitive(
com.facebook.ads.utils.ServerSideApiUtil.hash("1000001"))));

assertEquals(true, actual.contains(
new com.google.gson.JsonPrimitive(
com.facebook.ads.utils.ServerSideApiUtil.hash("1500001"))));
}

@Test
public void MultipleCountriesPreserveLegacyNormalizationTest() {
UserData userData = new UserData()
.countryCodes(Arrays.asList("us", "jp"))
.zipcode("100-0001");

String actual = com.google.gson.JsonParser.parseString(
EventRequest.getGson().toJson(userData))
.getAsJsonObject()
.getAsJsonArray("zp")
.get(0)
.getAsString();

assertEquals(
com.facebook.ads.utils.ServerSideApiUtil.hash("100"),
actual);
}

private static class ExtendedUserData extends UserData {
private String customField = "preserved";
}

@Test
public void PreserveExtendedUserDataFieldsTest() {
UserData userData = new ExtendedUserData()
.zipcode("100-0001")
.countryCode("jp");

Event event = new Event().userData(userData);

com.google.gson.JsonObject actual =
com.google.gson.JsonParser.parseString(
EventRequest.getGson().toJson(event))
.getAsJsonObject()
.getAsJsonObject("user_data");

assertEquals(
new com.google.gson.JsonPrimitive("preserved"),
actual.get("customField"));
}

@Test
public void NormalizePostalCodeWithFormattedCountryTest() {
assertNormalizedPostalCode("J.P.", "100-0001", "1000001");
}

@Test
public void PostalCodeWithHashedCountryTest() {
String country = com.facebook.ads.utils.ServerSideApiUtil.hash("jp");
assertNormalizedPostalCode(country, "100-0001", "100");
}

}