Giter Site home page Giter Site logo

gochimp3's Introduction

gochimp3

GoDoc Build Status Gitter chat

Introduction

Golang client for MailChimp API 3.0.

Install

Install with go get:

$ go get github.com/hanzoai/gochimp3

Usage

package main

import (
	"fmt"
	"os"

	"github.com/hanzoai/gochimp3"
)

const (
	apiKey = "YOUR_API_KEY_HERE"
)

func main() {
	client := gochimp3.New(apiKey)

	// Audience ID
	// https://mailchimp.com/help/find-audience-id/
	listID := "7f12f9b3fz"

	// Fetch list
	list, err := client.GetList(listID, nil)
	if err != nil {
		fmt.Printf("Failed to get list %s", listID)
		os.Exit(1)
	}

	// Add subscriber
	req := &gochimp3.MemberRequest{
		EmailAddress: "[email protected]",
		Status:       "subscribed",
	}

	if _, err := list.CreateMember(req); err != nil {
		fmt.Printf("Failed to subscribe %s", req.EmailAddress)
		os.Exit(1)
	}
}

Set Timeout

client := gochimp3.New(apiKey)
client.Timeout = (5 * time.Second)

gochimp3's People

Contributors

bassettb avatar bradleyfalk avatar cynicaljoy avatar davidtai avatar deep108 avatar eduohe avatar eslam-mahmoud avatar guysmoilov avatar kif11 avatar knd avatar ko30005 avatar leonb avatar michaelshobbs avatar monstarnn avatar nandanrao avatar nferruzzi avatar nmec avatar pinheiroalexandre2 avatar rafecolton avatar rishub21 avatar saromanov avatar seriallink avatar sfriedel avatar tw1nk avatar valicm avatar warmans avatar zeekay avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

gochimp3's Issues

Tags not being set with list.UpdateUser

I'm trying to update a users tags, I don't get an error but the tags are not being updated:

	req := &gochimp3.MemberRequest{
		EmailAddress: "[email protected]",
		Tags:         []string{"verified"},
	}

	m, err := list.UpdateMember("a36670ebcefcd9800c286cfbb101888f", req)
	if err != nil {
		fmt.Printf("Failed to update members %q\n", listID)
		os.Exit(1)
	}

	fmt.Printf("%+v\n", m)

Related: #31 cc @zeekay

Member tags are now objects

Currently the client attempts to decode members into a struct with a tags field defined as a slice of strings:

https://github.com/hanzoai/gochimp3/blob/master/members.go#L38

But actually in the API response tags are an object:

	"tags_count": 1,
	"tags": [
		{
			"id": 111111,
			"name": "foo"
		}
	],

so it fails:

json: cannot unmarshal object into Go struct field Member.members.tags of type string

Maybe this was changed at some point and mailchimp don't have strict BC for their API ๐Ÿคทโ€โ™‚๏ธ

Please fix WebHook struct about webhookID

There is no ID field in WebHook struct .

type WebHook struct {
	WebHookRequest
	ListID string `json:"list_id"`
	withLinks
}

However, it need webHookID as parameter when delete webhook .

func (list ListResponse) DeleteWebHook(id string) (bool, error)

CreateOrder does not capture errors correctly

CreateOrder doesn't error on these types of errors:

{"type":"http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/","title":"Invalid Resource","status":400,"detail":"The resource submitted could not be validated. For field-specific details, see the 'errors' array.","instance":"","errors":[{"field":"id","message":"cannot be empty"}]}

Panic recover during `GetActivity`

Hey,

I'm getting the error when I try to fetch activities for the list:
activities, err := list.GetActivity(&gochimp3.BasicQueryParams{})

The log of error is the following:

runtime error: invalid memory address or nil pointer dereference
 stack trace 2985 bytes
 goroutine 70 [running]:
main.MW.func1.1.1.1(0xc4200aba48)

Perhaps it happens because the activity array for this list doesn't have any data.

"unexpected end of JSON input" is not necessary an API error when status is 204

Hi,

there is a JSON decode error reported by mistake from the function

func (api API) CreateAutomationEmailQueue(workflowID, emailID, emailAddress string) (*AutomationQueue, error) {

basically the Request function attempts to decode and empty body (status 204) as a json and fails with the error unexpected end of JSON input.

But the status is 204 and is ok to be empty, could you please avoid the unmarshalling or make it a non error with status 204 ?

thanks

GetMembers doesn't support Location filter

Forgive me as I'm new to all of this (including go)...
I've been trying to do:

mailchimpConnection := gochimp3.New(mailchimpAPIKey)
mailchimpMembers, err := mailchimpConnection.NewListResponse("XXXXXX").GetMembers(
		&gochimp3.MemberQueryParams{
			ExtendedQueryParams: gochimp3.ExtendedQueryParams{
				BasicQueryParams: gochimp3.BasicQueryParams{
					Fields: []string{"total_items,members.id,members.location"}, // Return less data
				},
				Count: 3,
			},
			Location: &gochimp3.MemberLocation{
				CountryCode: "US",
			},
		},
	)
	if err != nil {
		fmt.Println("Failed to get list...")
		os.Exit(1)
	}

	//// Total US Beta Requestors
	fmt.Printf("Total US Beta Requestors: %d\n", mailchimpMembers.TotalItems)

This kind of works... I get three replies:

{
    "total_items": 53555,
    "_links": null,
    "list_id": "",
    "members": [
        {
            "email_address": "",
            "status": "",
            "language": "",
            "vip": false,
            "location": {
                "latitude": 0,
                "longitude": 0,
                "gmtoff": 0,
                "dstoff": 0,
                "timezone": "",
                "country_code": "US"
            },
            "id": "cbf746b69e309c90552499690c45b6c3",
            "list_id": "",
            "unique_email_id": "",
            "email_type": "",
            "stats": {
                "avg_open_rate": 0,
                "avg_click_rate": 0
            },
            "member_rating": 0,
            "last_changed": "",
            "email_client": "",
            "last_note": {
                "note_id": 0,
                "created_at": "",
                "created_by": "",
                "note": ""
            }
        },
        {
            "email_address": "",
            "status": "",
            "language": "",
            "vip": false,
            "location": {
                "latitude": 0,
                "longitude": 0,
                "gmtoff": 0,
                "dstoff": 0,
                "timezone": "",
                "country_code": "US"
            },
            "id": "e3dc49211a2ed16d3a7e4950dbefd145",
            "list_id": "",
            "unique_email_id": "",
            "email_type": "",
            "stats": {
                "avg_open_rate": 0,
                "avg_click_rate": 0
            },
            "member_rating": 0,
            "last_changed": "",
            "email_client": "",
            "last_note": {
                "note_id": 0,
                "created_at": "",
                "created_by": "",
                "note": ""
            }
        },
        {
            "email_address": "",
            "status": "",
            "language": "",
            "vip": false,
            "location": {
                "latitude": 0,
                "longitude": 0,
                "gmtoff": 0,
                "dstoff": 0,
                "timezone": "",
                "country_code": "AR"
            },
            "id": "9d370d0f280f60805ec59d37f767d7c2",
            "list_id": "",
            "unique_email_id": "",
            "email_type": "",
            "stats": {
                "avg_open_rate": 0,
                "avg_click_rate": 0
            },
            "member_rating": 0,
            "last_changed": "",
            "email_client": "",
            "last_note": {
                "note_id": 0,
                "created_at": "",
                "created_by": "",
                "note": ""
            }
        }
    ]
}
Total US Beta Requestors: 53555

Now, Location params isn't supported currently (as far as I can tell), so I've added them to the members.go:

type MemberQueryParams struct {
	ExtendedQueryParams
	Location *MemberLocation `json:"location,omitempty"`
	Type     string          `json:"type"`
}

// Params MemberQueryParams
func (q MemberQueryParams) Params() map[string]string {
	m := q.ExtendedQueryParams.Params()
	m["location"] = fmt.Sprintf("%v", q.Location)
	m["type"] = q.Type
	return m
}

. . .
func (list ListResponse) GetMembers(params *MemberQueryParams) (*ListOfMembers, error) {
	if err := list.CanMakeRequest(); err != nil {
		return nil, err
	}

	endpoint := fmt.Sprintf(members_path, list.ID)
	response := new(ListOfMembers)

	err := list.api.Request("GET", endpoint, params, nil, response)
	if err != nil {
		return nil, err
	}

	for _, m := range response.Members {
		m.api = list.api
	}

	prettyList1, err := json.MarshalIndent(response, "", "    ")
	if err != nil {
		fmt.Println("Failed to json pretty list...")
		os.Exit(1)
	}
	fmt.Printf("%s\n", string(prettyList1))

	prettyList2, err := json.MarshalIndent(params, "", "    ")
	if err != nil {
		fmt.Println("Failed to json pretty list...")
		os.Exit(1)
	}
	fmt.Printf("%s\n", string(prettyList2))

	return response, nil
}

Results:

{
    "Status": "",
    "SortField": "",
    "SortDirection": "",
    "Fields": [
        "total_items,members.id,members.location.country_code"
    ],
    "ExcludeFields": null,
    "Count": 3,
    "Offset": 0,
    "location": {
        "latitude": 0,
        "longitude": 0,
        "gmtoff": 0,
        "dstoff": 0,
        "timezone": "",
        "country_code": "US"
    },
    "type": ""
}

Shouldn't this return only US country_code entries? Am I misunderstanding how all of this works?

Clarify URL of package

I believe github.com/hanzoai/gochimp3 is the current correct URL for this package, but many docs refer to github.com/zeekay still.

json: cannot unmarshal number into Go struct field Segment.segments.id of type string

Looks like mailchimp API is serving integer tag IDs, and gochimp3 is using strings to represent tag IDs. To reproduce:

	mailchimp := gochimp3.New(os.Getenv("MAILCHIMP_API_KEY"))

	list, err := mailchimp.GetList(mailchimpAudienceID, nil)
	if err != nil {
		return err
	}

	segments, err := list.GetSegments(&gochimp3.SegmentQueryParams{})
	if err != nil {
		return err
	}

	for _, seg := range segments.Segments {
		log.Println(seg.ID, seg.Name)
	}
	return nil

Output is:

json: cannot unmarshal number into Go struct field Segment.segments.id of type string

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.