diff --git a/mailchimp.go b/mailchimp.go index 6bf2faf..158810a 100644 --- a/mailchimp.go +++ b/mailchimp.go @@ -101,3 +101,15 @@ func (c *Client) Subscribe(email string, listId string) (interface{}, error) { } return v, nil } + +func (c *Client) UpdateMemberName(email string, listId string, firstName string, lastName string) (interface{}, error) { + data := &map[string]interface{}{ + "merge_fields": &map[string]interface{}{"FNAME": firstName, "LNAME": lastName}, + } + userID := memberIDFromEmail(email) + v, err := c.Do("PATCH", fmt.Sprintf("/lists/%s/members/%s", listId, userID), data) + if err != nil { + return v, err + } + return v, nil +} diff --git a/mailchimp_test.go b/mailchimp_test.go index 4d553c4..1c7807c 100644 --- a/mailchimp_test.go +++ b/mailchimp_test.go @@ -69,3 +69,25 @@ func TestSubscribe(t *testing.T) { t.Fatal(err) } } + +func TestUpdateMemberName(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { + rw.WriteHeader(200) + rw.Header().Set("Content-Type", "application/json") + fmt.Fprintln(rw, `{"member_fields":{"FNAME":"bob","LNAME":"brown"}}`) + })) + defer server.Close() + + transport := &http.Transport{ + Proxy: func(req *http.Request) (*url.URL, error) { + return url.Parse(server.URL) + }, + } + + client, _ := NewClient("a-lit11", &http.Client{Transport: transport}) + client.BaseURL, _ = url.Parse("http://localhost/") + _, err := client.UpdateMemberName("me@matthewbrown.io", "abc_test", "bob", "brown") + if err != nil { + t.Fatal(err) + } +} diff --git a/util.go b/util.go new file mode 100644 index 0000000..d40c4fc --- /dev/null +++ b/util.go @@ -0,0 +1,18 @@ +package mailchimp + +import ( + "crypto/md5" + "encoding/hex" +) + +// From http://developer.mailchimp.com/documentation/mailchimp/guides/manage-subscribers-with-the-mailchimp-api/?_ga=1.198202223.1371869516.1465805004 +// "In previous versions of the API, we exposed internal database IDs eid and leid +// for emails and list/email combinations. In API 3.0, we no longer use or expose +// either of these IDs. Instead, we identify your subscribers by the MD5 hash of the +// lowercase version of their email address so you can easily predict the API URL +// of a subscriber’s data." +func memberIDFromEmail(email string) string { + idData := []byte(email) + id := md5.Sum(idData) + return hex.EncodeToString(id[:]) +}