go-workwx SDK

repository·v2·Indexed 19 days ago

https://github.com/xen0n/go-workwx

A production-tested Golang SDK for the Work Weixin (Wechat Work) API. It features type safety, idiomatic Go patterns, and robust access token management with automatic retrieval and exponential backoff retries. The SDK provides full support for message sending/receiving and Enterprise Weixin login, with partial support for address book, customer contact, and material management. Version v2 requires Go 1.24 or higher.

Tokens
53.3K
Snippets
180
Records
228
Agent score
73%

What's inside go-workwx

  1. Core features and design principles of go-workwx

    v2

    The go-workwx SDK is designed for production-grade Work Weixin integration with a focus on type safety and minimal public surface area. Key features include:

    • Customizable Networking: Supports overriding the API Host (useful for gateways or debugging) and using a custom http.Client.
    • Robust Access Token Management:
      • Automatic token retrieval during API calls.
      • Option to start a background goroutine for continuous token refreshing.
      • Built-in exponential backoff retries.
    • Type Safety: The SDK uses idiomatic Go types (e.g., UserInfo, Recipient) rather than exposing raw API request/response structures. It prioritizes static dispatch and avoids unnecessary polymorphism.
    • Stability: The library avoids panic in standard business logic; panics are reserved for unit tests or internal test commands.
  2. Understand the structure of received messages (rxMessageCommon)

    v2

    All incoming messages from the platform share a common structure defined by rxMessageCommon. This structure contains metadata required to identify the sender, receiver, message type, and timing. You must check MsgType to determine how to parse the specific content of the message.

    Common Fields:

    • ToUserName: The CorpID of the enterprise.
    • FromUserName: The UserID of the member.
    • CreateTime: Message creation timestamp (int64).
    • MsgType: The type of message (e.g., text, image, event).
    • MsgID: Unique 64-bit integer ID for the message.
    • AgentID: The ID of the enterprise application.
    • Event: The event type (present if MsgType is event).
    • ChangeType: The change type (present if Event is change_external_contact).
    type MessageType string
    
    const (
    	MessageTypeText    MessageType = "text"
    	MessageTypeImage   MessageType = "image"
    	MessageTypeVoice   MessageType = "voice"
    	MessageTypeVideo   MessageType = "video"
    	MessageTypeLocation MessageType = "location"
    	MessageTypeLink     MessageType = "link"
    	MessageTypeEvent    MessageType = "event"
    )
  3. Note on sending confidential (safe) messages

    v2

    The SDK includes an isSafe parameter in message sending methods to support confidential messaging.

    Warning: Currently, message types like Markdown do not support being sent as confidential messages. Attempting to send them with isSafe: true will result in an error from the Work Weixin service. The parameter is retained in the API to allow for future service-side support without requiring SDK recompilation.

  4. Manage `ExternalProfile` attributes

    v2

    An ExternalProfile contains a list of ExternalAttr (attributes) that describe the contact. Attributes currently support three types:

    1. Text (type: 0): Requires the text field with a value (max 12 UTF-8 characters).
    2. Web (type: 1): Requires web field with url (must include http/https) and title (max 12 UTF-8 characters). To clear this attribute, both url and title must be empty.
    3. Miniprogram (type: 2): Requires miniprogram field with appid (must be installed in the enterprise), pagepath, and title. To clear this attribute, both appid and title must be empty.

    Note: The name of the attribute must already exist in the management console, otherwise it will be ignored.

    {
      "external_profile": {
        "external_attr": [
          {
            "type": 0,
            "name": "Occupation",
            "text": { "value": "Manager" }
          },
          {
            "type": 1,
            "name": "Website",
            "web": { "url": "https://example.com", "title": "Example" }
          }
        ]
      }
    }
  5. Understand `FollowUserInfo` and customer follow details

    v2

    The FollowUserInfo model describes how an enterprise member added an external contact. It provides context on the relationship, such as:

    • userid: The ID of the external contact.
    • remark & description: The member's notes and description for the contact.
    • createtime: When the contact was added.
    • add_way: The source of the addition (e.g., QR code, mobile number, group chat).
    • oper_userid: The user who initiated the addition.
    • tag_id: A list of enterprise tags applied to the contact by this member (personal tags are not returned in this specific view).

    Note on Tags: When using FollowInfo, only enterprise tag_ids are returned; personal tags are excluded.

    // FollowUserAddWay 该成员添加此客户的来源
    type FollowUserAddWay int
    
    const (
    	FollowUserAddWayUnknown FollowUserAddWay = 0
    	FollowUserAddWayQRCode FollowUserAddWay = 1
    	FollowUserAddWayMobile FollowUserAddWay = 2
    	FollowUserAddWayCard FollowUserAddWay = 3
    	FollowUserAddWayGroupChat FollowUserAddWay = 4
    	FollowUserAddWayAddressBook FollowUserAddWay = 5
    	FollowUserAddWayWeChatContact FollowUserAddWay = 6
    	FollowUserAddWayWeChatFriendApply FollowUserAddWay = 7
    	FollowUserAddWayThirdParty FollowUserAddWay = 8
    	FollowUserAddWayEmail FollowUserAddWay = 9
    	FollowUserAddWayInternalShare FollowUserAddWay = 201
    	FollowUserAddWayAdmin FollowUserAddWay = 202
    )
  6. Populate form control values with `OAContentValue`

    v2

    The OAContentValue model is used to assign data to specific form controls within an application. The field you use depends on the control type defined in the OAContent object.

    Control TypeJSON KeyDescription
    Text or TextareatextPlain text or multi-line text
    Numbernew_numberNumeric value (as string)
    Moneynew_moneyMonetary amount (as string)
    DatedateUses OAContentDate object
    SelectorselectorUses OAContentSelector object
    Contactmembers or departmentsUse members for users, departments for departments
    FilefilesList of OAContentFile objects
    TablechildrenList of OAContentTableList objects
    VacationvacationUses OAContentVacation object
    Attendanceattendance or punch_correctionUses specialized attendance objects
    LocationlocationUses OAContentLocation object
    DateRangedate_rangeUses OAContentDateRange object
    BankAccountbank_accountUses OAContentBankAccount object
  7. Upload temporary media assets

    v2
    Use the media upload functionality to upload temporary assets such as images, voice recordings, videos, or general files. Upon a successful upload, the system returns a MediaUploadResult containing a unique identifier that is valid for 3 days.
  8. Install and import go-workwx v2

    v2

    To use the Work Weixin (Wechat Work) client SDK in your Go project, import the v2 module.

    Note that the v2.x branch requires Go 1.24 or higher (as of January 2026). If you need to support older Go versions (down to Go 1.17), use the v1.x version instead.

    import (
        "github.com/xen0n/go-workwx/v2"
    ) // package workwx
  9. Handle specific message types (Text, Image, Voice, Video, Location, Link)

    v2

    Depending on the MsgType, you must parse additional fields.

    Text Message (rxTextMessageSpecifics)

    • Content: The actual text content.

    Image Message (rxImageMessageSpecifics)

    • PicURL: URL of the image.
    • MediaID: Media file ID (valid for 3 days; use media interfaces to download).

    Voice Message (rxVoiceMessageSpecifics)

    • MediaID: Voice media file ID (valid for 3 days).
    • Format: Audio format (e.g., amr, speex).

    Video Message (rxVideoMessageSpecifics)

    • MediaID: Video media file ID (valid for 3 days).
    • ThumbMediaID: Thumbnail media ID.

    Location Message (rxLocationMessageSpecifics)

    • Lat: Latitude.
    • Lon: Longitude.
    • Scale: Map zoom level.
    • Label: Location description.
    • AppType: Always wxwork in Enterprise WeChat.
    • Title: Link title.
    • Description: Link description.
    • URL: Destination URL.
    • PicURL: Thumbnail URL.
  10. Handle Member and App Events

    v2

    Member Lifecycle Events

    • rxEventChangeTypeCreateUser: Triggered when a new member is added. Includes Name, Department, Mobile, Position, Gender, Email, Status, Avatar, Alias, Telephone, Address, and ExtAttr (Extended Attributes).
    • rxEventChangeTypeUpdateUser: Triggered when member info changes. Includes NewUserID if the ID was changed.

    Application Menu and Subscription Events

    • rxEventAppMenuClick / rxEventAppMenuView: Triggered when a user interacts with the app menu. Includes EventKey.
    • rxEventAppSubscribe / rxEventAppUnsubscribe: Triggered by user subscription status changes. Includes EventKey.

    Customer Service (Kf) Events

    • rxEventKfMsgOrEvent: Triggered by customer service interactions. Includes OpenKfID and a Token required for pulling messages via the sync_msg interface.
  11. Handle External Contact Events

    v2

    Events related to external customers (contacts outside the enterprise) use specific models. Most include UserID (the employee) and ExternalUserID (the customer).

    Add/Edit/Half-Add Contact

    • rxEventAddExternalContact: Triggered when a customer is added.
    • rxEventEditExternalContact: Triggered when customer info is edited.
    • rxEventAddHalfExternalContact: Triggered when a member is added without verification.
    • Key Fields: State (used to identify the channel/source via 'Contact Me' config) and WelcomeCode (used to send welcome messages).

    Delete/Transfer Events

    • rxEventDelExternalContact: Customer deleted.
    • rxEventDelFollowUser: Follower deleted.
    • rxEventTransferFail: Customer transfer failed. Includes FailReason (customer_refused or customer_limit_exceed).

    Group Changes

    • rxEventChangeExternalChat: Triggered by changes in customer groups. Includes ChatID.
  12. Define Template Card types

    v2

    The TemplateCardType defines the visual and functional category of a message card. Use these constants to specify the CardType in a TemplateCard object.

    Available types:

    • text_notice: Text notification style.
    • news_notice: Image and text display style.
    • button_interaction: Button-based interaction style.
    • vote_interaction: Voting and selection style.
    • multiple_interaction: Multiple selector style.
    type TemplateCardType string
    
    const (
    	CardTypeTextNotice          TemplateCardType = "text_notice"
    	CardTypeNewsNotice          TemplateCardType = "news_notice"
    	CardTypeButtonInteraction   TemplateCardType = "button_interaction"
    	CardTypeVoteInteraction     TemplateCardType = "vote_interaction"
    	CardTypeMultipleInteraction TemplateCardType = "multiple_interaction"
    )