API, command and message handling for WeChat in Rails
Install / Use
/learn @Eric-Guo/WechatREADME
WeChat


Wechat is a Chinese multi-purpose messaging, social media and mobile payment app developed by Tencent. It was first released in 2011, and by 2018 it was one of the world's largest standalone mobile apps by monthly active users, with over 1 billion monthly active users (902 million daily active users). (According to wiki)
WeChat gem helps Rails developers integrate WeChat Official Accounts Platform or Wechat mini program easily, including features:
- Sending message API(can be both accessed via console or rails server)
- Receiving message(rails server is required to be running)
- Wechat JS-SDK config signature
- OAuth 2.0 authentication
- Record session when receiving message from user (Optional)
wechat command shares the same API in console, so you can interact with wechat server quickly without starting up web environment/code.
A responder DSL can be used in Rails controller, which gives an event based interface to handle messages sent by end users.
If Wechat OAuth 2.0 is required by your app, omniauth-wechat-oauth2 is recommended in order to apply devise authentication.
If tencent's weui UI style is adoped in your project, gem weui-rails is available for you.
For web page only wechat application, please use wechat_api, which only contains web features, compared with traditional message type wechat_responder.
There is a more complete wechat-starter demo available, which futher includes the payment SDK feature.
Installation
Use gem install
gem install "wechat"
# If your ruby version < 2.6
# gem install wechat -v 0.12.4
Or add it to your app's Gemfile:
gem 'wechat'
# If your rails version < 6.0
# gem 'wechat', '~> 0.12.4'
Run the following command to install it:
bundle install
Run the generator:
rails generate wechat:install
rails g wechat:install will generate the initial wechat.yml configuration file, including an sample wechat controller and corresponding routes.
Enable session record:
rails g wechat:session
rake db:migrate
Enabling session will generate two files in Rails folder, you can add more columns to wechat_session table and add declaration to link to users table, it's also possible to store data directly in hash_store. If you are using PostgreSQL, using hstore/json maybe better, but the best way is to add a dedicated column to record the data (the Rails way).
Using Redis to store wechat token and ticket:
rails g wechat:redis_store
Redis storage supports Rails application running in multiple servers. It is recommended to use default file storage if there is only one single server. Besides that, wechat command won't read token/ticket stored in Redis.
Enable database wechat configurations:
rails g wechat:config
rake db:migrate
After running the migration, a wechat_configs table will be created that allows storage of multiple wechat accounts.
Configuration
Configure wechat for the first time
Make sure to finish all the setup on rails side first, then submit those setting to Tencent wechat management website. Otherwise, wechat will raise error.
URL address for wechat created by running rails g wechat:install is http://your-server.com/wechat
How to setup appid/corpid and secret see below section.
Configure wechat by record-based mode
Make sure the record attributes include access_token, token_expires_in, got_token_at.
def client
@client ||= Wechat::Api.new(app_id, app_secret, token_file, network_setting, jsapi_ticket_file, record)
end
Configure for command line
To use standalone wechat command, you need to create configuration file ~/.wechat.yml and include content below for public account. The access_token will be written to file /var/tmp/wechat_access_token.
appid: "my_appid"
secret: "my_secret"
access_token: "/var/tmp/wechat_access_token"
For enterprise account, you need to use corpid instead of appid as enterprise account supports multiply application (Tencent calls them agents) in one enterprise account. Obtaining the corpsecret is a little bit tricky, must be created at management mode->privilege setting and create any of management group to obtain. Due to Tencent currently only providing Chinese interface for their management console, it's highly recommended you find a colleague knowing Mandarin to help you to obtain the corpsecret.
Windows users need to store .wechat.yml at C:/Users/[user_name]/ (replace with your user name), also pay attention to the direction of folder separator.
corpid: "my_appid"
corpsecret: "my_secret"
agentid: 1 # Integer, which can be obtained from application settings
access_token: "C:/Users/[user_name]/wechat_access_token"
Configure for Rails
Rails configuration file supports different environment similar to database.yml, after running rails generate wechat:install you can find configuration file at config/wechat.yml
Public account configuration example:
default: &default
appid: "app_id"
secret: "app_secret"
token: "app_token"
access_token: "/var/tmp/wechat_access_token"
jsapi_ticket: "/var/tmp/wechat_jsapi_ticket"
production:
appid: <%= ENV['WECHAT_APPID'] %>
secret: <%= ENV['WECHAT_APP_SECRET'] %>
token: <%= ENV['WECHAT_TOKEN'] %>
access_token: <%= ENV['WECHAT_ACCESS_TOKEN'] %>
jsapi_ticket: <%= ENV['WECHAT_JSAPI_TICKET'] %>
oauth2_cookie_duration: <%= ENV['WECHAT_OAUTH2_COOKIE_DURATION'] %> # seconds
development:
<<: *default
trusted_domain_fullname: "http://your_dev.proxy.qqbrowser.cc"
test:
<<: *default
Although it's optional for public account, but highly recommended to enable encrypt mode by adding these two items to wechat.yml
default: &default
encrypt_mode: true
encoding_aes_key: "my_encoding_aes_key"
Enterprise account must use encrypt mode (encrypt_mode: true is on by default, no need to configure).
The token and encoding_aes_key can be obtained from management console -> one of the agent application -> Mode selection, select callback mode and get/set.
default: &default
corpid: "corpid"
corpsecret: "corpsecret"
agentid: 1
access_token: "C:/Users/[user_name]/wechat_access_token"
token: ""
encoding_aes_key: ""
jsapi_ticket: "C:/Users/[user_name]/wechat_jsapi_ticket"
production:
corpid: <%= ENV['WECHAT_CORPID'] %>
corpsecret: <%= ENV['WECHAT_CORPSECRET'] %>
agentid: <%= ENV['WECHAT_AGENTID'] %>
access_token: <%= ENV['WECHAT_ACCESS_TOKEN'] %>
token: <%= ENV['WECHAT_TOKEN'] %>
timeout: 30,
skip_verify_ssl: true # not recommend
encoding_aes_key: <%= ENV['WECHAT_ENCODING_AES_KEY'] %>
jsapi_ticket: <%= ENV['WECHAT_JSAPI_TICKET'] %>
oauth2_cookie_duration: <%= ENV['WECHAT_OAUTH2_COOKIE_DURATION'] %>
development:
<<: *default
trusted_domain_fullname: "http://your_dev.proxy.qqbrowser.cc"
test:
<<: *default
# Multiple Accounts
#
# wx2_development:
# <<: *default
# appid: "my_appid"
# secret: "my_secret"
# access_token: "tmp/wechat_access_token2"
# jsapi_ticket: "tmp/wechat_jsapi_ticket2"
#
# wx2_test:
# <<: *default
# appid: "my_appid"
# secret: "my_secret"
#
# wx2_production:
# <<: *default
# appid: "my_appid"
# secret: "my_secret"
Notes about supporting multiple accounts of WeChat Official Accounts Platform / WeChat Enterprise (for example, adding account wx2):
-
Configuration for multiple accounts is similar to multi-database configuration in
config/database.yml, wheredevelopment,test,productionsegments are the default configuration, one needs to addwx2_development,wx2_test,wx2_productionin order to add additional account namedwx2. -
Declaration of additional
wechat_responder:wechat_responder account: :wx2 -
Use
Wechat.apiorWechat.api(:default)to represent the default wechat api. UseWechat.api(:wx2)to call for wechat api of accountwx2. -
When using
Wechat command line, one can switch to another wechat account by adding optional parameters-a ACCOUNT [--account=ACCOUNT].
For details about supporting multiple accounts, please check PR 150
For wechat mini program, can specified by the item type:
# Mini Program Accounts
mini_development:
<<: *default
appid: "my_appid"
secret: "my_secret"
# `mp` is short for **mini program**
type: 'mp'
Database wechat account configuration
After
