XiWechatCorp
Toolkits for Tencent Wechat Corp development
Installation
Add this line to your application's Gemfile:
gem 'xi_wechat_corp'
And then execute:
$ bundle
Or install it yourself as:
$ gem install xi_wechat_corp
Usage
Rack Middleware
use XiWechatCorp::Callback::Rack do |request|
corp_id 'wx1234'
if request.path_info == '/wechat'
token 'secret'
aes_key 'secret'
elsif request.path_info == '/another'
token 'secret'
aes_key 'secret'
end
end
The middleware is enabled for requests when corp_id
, token
and aes_key
are all configured.
The GET
request is handled by the middleware directly. Just implement the
logic for POST
requests. All post params can be get through rack env
xi_wechat_corp.params
, including decrypted params. The handler just return
the plain XML, The middleware will encrypt response and sign it.
Used in Grape
require 'xi_wechat_corp'
class MyAPI < Grape::API
use XiWechatCorp::Callback::Rack do |req|
corp_id 'wx1234'
token 'secret'
aes_key 'secret'
end
parser :xml, XiWechatCorp::Callback::Grape::Parser
formatter :xml, XiWechatCorp::Callback::Grape::Formatter
end
Handle Callback Manually
Verify and decrypt Request
cryptor = XiWechatCorp::AesCrypt.new(aes_key, corp_id)
signer = XiWechatCorp::SHA1Signer.new(token)
request = XiWechatCorp::Callback::Request.new(cryptor, signer, query_params, xml_body)
request.verify!
# Get decrypted echostr for GET
request.challenge
# Decrypt Encrypt field for POST
request.decrypt
# Pack response
response = request.build_response
response.assign(xml_response)
response.to_s
API
conn = XiWechatCorp::Client::Connection.new
conn.get_access_token(corp_id, secret)
conn.post(
'message/send',
touser: 'UserID1|UserID2|UserID3',
toparty: ' PartyID1 | PartyID2 ',
totag: ' TagID1 | TagID2 ',
touser: 'user1|user2',
msgtype: 'text',
agentid: '1',
text: {
content: 'Holiday Request for Pony'
},
safe: 0
)
Contributing
- Fork it ( https://github.com/3pjgames/xi_wechat_corp/fork )
- Create your feature branch (
git checkout -b my-new-feature
) - Commit your changes (
git commit -am 'Add some feature'
) - Push to the branch (
git push origin my-new-feature
) - Create a new Pull Request