Wechat API wrapper in Elixir.
Installation
def deps do
[{:wechat, "~> 0.4.0"}]
end
Warning: 0.4.0 is a rewrite for APIs, don't upgrade if you are using 0.3.0.
Usage
iex(1)> client = Wechat.Client.new(%{appid: "WECHAT_APPID", secret: "WECHAT_SECRET"})
%Wechat.Client{
appid: "WECHAT_APPID",
secret: "WECHAT_SECRET",
endpoint: "https://api.weixin.qq.com/"
}
iex(2)> Wechat.User.get(client)
{:ok,
%{
"count" => 1,
"data" => %{"openid" => ["oi00OuKAhA8bm5okpaIDs7WmUZr4"]},
"next_openid" => "oi00OuKAhA8bm5okpaIDs7WmUZr4",
"total" => 1
}}
Plugs
Parse wechat message (in Phonenix controller)
config.exs
config :my_app, MyApp.Wechat,appid: "APP_ID",secret: "APP_SECRET",token: "TOKEN",encoding_aes_key: "ENCODING_AES_KEY" # Required if you enabled the encrypt modemy_app/wechat.ex
defmodule MyApp.Wechat douse Wechat, otp_app: :beaverdef users doclient() |> Wechat.User.get()endendrouter.ex
defmodule MyApp.Router doscope "/wechat", MyApp doresources "/", WechatController, [:index, :create]endendwechat_controller.ex
defmodule MyApp.WechatController douse MyApp.Web, :controllerplug Wechat.Plugs.RequestValidator, module: MyApp.Wechatplug Wechat.Plugs.MessageParser, [module: MyApp.Wechat] when action in [:create]def index(conn, %{"echostr" => echostr}) dotext conn, echostrenddef create(conn, _params) domsg = conn.body_paramsreply = echo_reply(msg, msg["Content"])render conn, "text.xml", reply: replyenddefp echo_reply(%{"ToUserName" => to, "FromUserName" => from}, content) do%{from: to, to: from, content: content}endendtext.xml.eex
<xml><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[<%= @reply.content %>]]></Content><ToUserName><![CDATA[<%= @reply.to %>]]></ToUserName><FromUserName><![CDATA[<%= @reply.from %>]]></FromUserName><CreateTime><%= DateTime.to_unix(DateTime.utc_now) %></CreateTime></xml>