Skip to main content

WeChatClient

Struct WeChatClient 

Source
pub struct WeChatClient { /* private fields */ }
Expand description

The main entry point for the WeChat Official Account SDK.

Implementations§

Source§

impl WeChatClient

Source

pub async fn send_customer_service_message( &self, message: &CustomerServiceMessage, ) -> Result<()>

Send a customer service message.

Source

pub async fn send_text(&self, to_user: &str, content: &str) -> Result<()>

Send a text message via customer service.

Source

pub async fn send_image(&self, to_user: &str, media_id: &str) -> Result<()>

Send an image via customer service.

Source

pub async fn send_voice(&self, to_user: &str, media_id: &str) -> Result<()>

Send a voice message via customer service.

Source

pub async fn send_video( &self, to_user: &str, media_id: &str, thumb_media_id: &str, title: Option<&str>, description: Option<&str>, ) -> Result<()>

Send a video via customer service.

Source

pub async fn send_news( &self, to_user: &str, articles: Vec<NewsArticle>, ) -> Result<()>

Send news articles via customer service.

Source

pub async fn set_typing(&self, to_user: &str, typing: bool) -> Result<()>

Set typing status for a user.

Source§

impl WeChatClient

Source

pub async fn upload_temp_media( &self, media_type: MaterialType, file_name: &str, file_data: Vec<u8>, ) -> Result<UploadTempMediaResponse>

Upload a temporary media file.

Temporary media is valid for 3 days.

Source

pub async fn get_temp_media(&self, media_id: &str) -> Result<Vec<u8>>

Get a temporary media file.

Returns the raw bytes of the media file.

Source

pub async fn upload_permanent_media( &self, media_type: MaterialType, file_name: &str, file_data: Vec<u8>, ) -> Result<UploadPermanentMediaResponse>

Upload a permanent media file (image, voice, thumb).

Source

pub async fn upload_permanent_video( &self, file_name: &str, file_data: Vec<u8>, description: &VideoDescription, ) -> Result<UploadPermanentMediaResponse>

Upload a permanent video file.

Source

pub async fn get_material_count(&self) -> Result<MaterialCountResponse>

Get permanent material count.

Source

pub async fn get_material_list( &self, media_type: MaterialType, offset: i32, count: i32, ) -> Result<MaterialListResponse>

Get permanent material list.

Source

pub async fn delete_material(&self, media_id: &str) -> Result<()>

Delete a permanent material.

Source§

impl WeChatClient

Source

pub async fn create_menu(&self, buttons: Vec<MenuButton>) -> Result<()>

Create a custom menu.

Source

pub async fn get_menu(&self) -> Result<GetMenuResponse>

Get the current menu configuration.

Source

pub async fn delete_menu(&self) -> Result<()>

Delete all menus (including conditional menus).

Source

pub async fn create_conditional_menu( &self, buttons: Vec<MenuButton>, match_rule: MatchRule, ) -> Result<i64>

Create a conditional menu (personalized menu).

Source

pub async fn delete_conditional_menu(&self, menu_id: i64) -> Result<()>

Delete a conditional menu by menu ID.

Source

pub async fn try_match_menu(&self, user_id: &str) -> Result<Menu>

Test which menu a user would see.

Source§

impl WeChatClient

Source

pub fn verify_signature( &self, signature: &str, timestamp: &str, nonce: &str, ) -> bool

Verify the callback signature from WeChat server.

This should be called when WeChat sends a verification request (GET request with signature, timestamp, nonce, echostr).

Returns true if the signature is valid.

Source

pub fn parse_message(&self, xml_body: &str) -> Result<IncomingMessage>

Parse an incoming message or event from WeChat.

The xml_body is the raw XML POST body from WeChat callback.

Source

pub fn verify_msg_signature( &self, msg_signature: &str, timestamp: &str, nonce: &str, encrypt_msg: &str, ) -> bool

Verify the encrypted message signature.

Used to verify incoming encrypted messages from WeChat.

Source

pub fn parse_encrypted_message( &self, xml_body: &str, msg_signature: &str, timestamp: &str, nonce: &str, ) -> Result<IncomingMessage>

Parse an encrypted incoming message or event from WeChat.

This should be used when your server is configured in “safe mode” or “compatible mode”.

§Arguments
  • xml_body: The raw XML POST body containing the encrypted message
  • msg_signature: The signature from query parameter
  • timestamp: The timestamp from query parameter
  • nonce: The nonce from query parameter
§Example
let msg = client.parse_encrypted_message(
    &xml_body,
    &query.msg_signature,
    &query.timestamp,
    &query.nonce,
)?;
Source

pub fn decrypt_echostr(&self, encrypted_echostr: &str) -> Result<String>

Decrypt the echostr for server verification in encrypted mode.

When WeChat verifies your server URL in encrypted mode, it sends an encrypted echostr. You need to decrypt it and return the decrypted content.

§Arguments
  • encrypted_echostr: The encrypted echostr from query parameter
§Returns

The decrypted echostr that should be returned to WeChat.

Source

pub fn encrypt_reply( &self, reply_xml: &str, timestamp: &str, nonce: &str, ) -> Result<String>

Encrypt a reply XML for sending back to WeChat.

This should be used when your server is configured in “safe mode”.

§Arguments
  • reply_xml: The plain reply XML (e.g., from TextReply::to_xml())
  • timestamp: The timestamp to use (can be current time or from the original request)
  • nonce: The nonce to use (can generate a new one or use from the original request)
§Returns

The encrypted XML that should be returned to WeChat.

§Example
let reply = TextReply::new(&to_user, &from_user, "Hello!");
let encrypted_xml = client.encrypt_reply(&reply.to_xml(), &timestamp, &nonce)?;
Source

pub fn encrypt_reply_auto(&self, reply_xml: &str) -> Result<String>

Encrypt a reply XML with auto-generated timestamp and nonce.

Convenience method that generates timestamp and nonce automatically.

Source§

impl WeChatClient

Source

pub async fn add_draft(&self, articles: Vec<Article>) -> Result<String>

Add a new draft with one or more articles.

Returns the media_id of the created draft.

Source

pub async fn get_draft(&self, media_id: &str) -> Result<DraftContent>

Get a draft by media_id.

Source

pub async fn delete_draft(&self, media_id: &str) -> Result<()>

Delete a draft by media_id.

Source

pub async fn update_draft( &self, media_id: &str, index: i32, article: Article, ) -> Result<()>

Update an article in a draft.

  • media_id: The draft media_id
  • index: The article index (0-based)
  • article: The updated article content
Source

pub async fn get_draft_count(&self) -> Result<i32>

Get the total count of drafts.

Source

pub async fn get_draft_list( &self, offset: i32, count: i32, no_content: bool, ) -> Result<DraftListResponse>

Get draft list.

  • offset: Starting position (0-based)
  • count: Number of items to return (1-20)
  • no_content: Whether to exclude article content (true = faster)
Source

pub async fn submit_publish(&self, media_id: &str) -> Result<String>

Submit a draft for publishing.

This is for “发布” (not 群发). Published articles won’t appear in followers’ feeds but can be accessed via URL.

Returns the publish_id to track publishing status.

Source

pub async fn get_publish_status( &self, publish_id: &str, ) -> Result<PublishStatusResponse>

Get the status of a publish job.

Source

pub async fn delete_publish(&self, article_id: &str, index: i32) -> Result<()>

Delete a published article.

  • article_id: The article_id from publish
  • index: Article index (0-based), use 0 for single article
Source

pub async fn get_publish(&self, article_id: &str) -> Result<PublishContent>

Get a published article by article_id.

Source

pub async fn get_publish_list( &self, offset: i32, count: i32, no_content: bool, ) -> Result<PublishListResponse>

Get list of published articles.

  • offset: Starting position (0-based)
  • count: Number of items (1-20)
  • no_content: Whether to exclude article content
Source

pub async fn mass_send_article( &self, media_id: &str, tag_id: Option<i32>, ignore_reprint: bool, ) -> Result<MassSendResponse>

Mass send an article to all followers or by tag.

This is for “群发” - articles will appear in followers’ feeds and push notifications.

  • media_id: Draft media_id to send
  • tag_id: Optional tag to filter recipients (None = all followers)
  • ignore_reprint: Whether to continue if original check fails (default true)
Source

pub async fn mass_preview(&self, media_id: &str, to_user: &str) -> Result<i64>

Preview a mass send to a specific user (for testing).

  • media_id: Draft media_id
  • to_user: OpenID of the recipient
Source

pub async fn mass_delete( &self, msg_id: i64, article_idx: Option<i32>, ) -> Result<()>

Delete a mass send message.

Can only delete within 30 minutes after sending.

Source

pub async fn mass_get_status(&self, msg_id: i64) -> Result<MassStatusResponse>

Get mass send status.

Source

pub async fn upload_article_image( &self, file_name: &str, file_data: Vec<u8>, ) -> Result<String>

Upload an image for use in article content.

Returns the URL of the uploaded image (can be used in article HTML). This is different from material upload - these images are specifically for embedding in article content.

Source§

impl WeChatClient

Source

pub async fn create_qrcode( &self, scene_id: u32, action: QrCodeAction, expire_seconds: Option<i64>, ) -> Result<QrCodeResponse>

Create a QR code with a numeric scene value.

  • scene_id: Scene value (32-bit non-zero integer)
  • action: QR code type (temporary or permanent)
  • expire_seconds: Expiration time for temporary QR codes (max 2592000 = 30 days)
Source

pub async fn create_qrcode_str( &self, scene_str: &str, action: QrCodeAction, expire_seconds: Option<i64>, ) -> Result<QrCodeResponse>

Create a QR code with a string scene value.

  • scene_str: Scene value string (max 64 characters)
  • action: QR code type (use TemporaryStr or PermanentStr)
  • expire_seconds: Expiration time for temporary QR codes
Source

pub fn get_qrcode_url(ticket: &str) -> String

Get the URL to display a QR code image.

The ticket should be URL-encoded when used.

Source

pub async fn download_qrcode(&self, ticket: &str) -> Result<Vec<u8>>

Download QR code image as bytes.

Source

pub async fn create_short_url(&self, long_url: &str) -> Result<String>

Convert a long URL to a short URL.

Note: This API may be deprecated. Consider using other URL shorteners.

Source

pub async fn get_callback_ip_list(&self) -> Result<Vec<String>>

Get the WeChat server IP list.

Useful for configuring firewalls to allow WeChat callbacks.

Source

pub async fn get_api_domain_ip_list(&self) -> Result<Vec<String>>

Get the WeChat API server IP list.

Source

pub async fn check_network(&self) -> Result<bool>

Check if the current network can access WeChat API.

Source§

impl WeChatClient

Source

pub async fn get_user_summary( &self, range: &DateRange, ) -> Result<Vec<UserSummaryItem>>

Get user summary statistics. Date range must be within 7 days.

Source

pub async fn get_user_cumulate( &self, range: &DateRange, ) -> Result<Vec<UserCumulateItem>>

Get user cumulate statistics. Date range must be within 7 days.

Source

pub async fn get_article_summary( &self, range: &DateRange, ) -> Result<Vec<ArticleSummaryItem>>

Get article summary statistics (single day only).

Source

pub async fn get_article_total( &self, range: &DateRange, ) -> Result<Vec<ArticleTotalItem>>

Get article total statistics (single day only).

Source

pub async fn get_user_read( &self, range: &DateRange, ) -> Result<Vec<ArticleSummaryItem>>

Get user read statistics (up to 3 days).

Source

pub async fn get_user_read_hour( &self, range: &DateRange, ) -> Result<Vec<ArticleSummaryItem>>

Get user read hour statistics (single day only).

Source

pub async fn get_user_share( &self, range: &DateRange, ) -> Result<Vec<ArticleSummaryItem>>

Get user share statistics (up to 7 days).

Source

pub async fn get_user_share_hour( &self, range: &DateRange, ) -> Result<Vec<ArticleSummaryItem>>

Get user share hour statistics (single day only).

Source

pub async fn get_upstream_msg( &self, range: &DateRange, ) -> Result<Vec<UpstreamMsgItem>>

Get upstream message statistics (up to 7 days).

Source

pub async fn get_upstream_msg_hour( &self, range: &DateRange, ) -> Result<Vec<UpstreamMsgItem>>

Get upstream message hour statistics (single day only).

Source

pub async fn get_interface_summary( &self, range: &DateRange, ) -> Result<Vec<InterfaceSummaryItem>>

Get interface summary statistics (up to 30 days).

Source

pub async fn get_interface_summary_hour( &self, range: &DateRange, ) -> Result<Vec<InterfaceSummaryItem>>

Get interface summary hour statistics (single day only).

Source§

impl WeChatClient

Source

pub async fn send_template_message( &self, message: &TemplateMessage, ) -> Result<i64>

Send a template message.

Source

pub async fn set_industry( &self, industry_id1: &str, industry_id2: &str, ) -> Result<()>

Set the industry for template messages.

Source

pub async fn get_industry(&self) -> Result<GetIndustryResponse>

Get the current industry setting.

Source

pub async fn add_template(&self, template_id_short: &str) -> Result<String>

Add a template from the template library.

Source

pub async fn get_all_templates(&self) -> Result<TemplateListResponse>

Get all templates.

Source

pub async fn delete_template(&self, template_id: &str) -> Result<()>

Delete a template.

Source§

impl WeChatClient

Source

pub async fn get_user_info( &self, openid: &str, lang: Option<&str>, ) -> Result<UserInfo>

Get user information by OpenID.

Source

pub async fn batch_get_user_info( &self, openids: &[&str], lang: Option<&str>, ) -> Result<BatchUserInfoResponse>

Batch get user information.

Source

pub async fn get_user_list( &self, next_openid: Option<&str>, ) -> Result<UserListResponse>

Get user list (followers).

Source

pub async fn set_user_remark(&self, openid: &str, remark: &str) -> Result<()>

Set user remark.

Source

pub async fn create_tag(&self, name: &str) -> Result<Tag>

Create a user tag.

Source

pub async fn get_tags(&self) -> Result<TagListResponse>

Get all tags.

Source

pub async fn update_tag(&self, tag_id: i32, name: &str) -> Result<()>

Update a tag name.

Source

pub async fn delete_tag(&self, tag_id: i32) -> Result<()>

Delete a tag.

Source

pub async fn get_users_by_tag( &self, tag_id: i32, next_openid: Option<&str>, ) -> Result<UsersByTagResponse>

Get users with a specific tag.

Source

pub async fn batch_tag_users(&self, openids: &[&str], tag_id: i32) -> Result<()>

Batch tag users.

Source

pub async fn batch_untag_users( &self, openids: &[&str], tag_id: i32, ) -> Result<()>

Batch untag users.

Source

pub async fn get_user_tags(&self, openid: &str) -> Result<Vec<i32>>

Get tags of a user.

Source§

impl WeChatClient

Source

pub fn new(config: Config) -> Self

Create a new WeChatClient with the given configuration.

Source

pub async fn access_token(&self) -> Result<String>

Get a valid access token (auto-refreshed if expired).

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more