Git Product home page Git Product logo

wechat's Introduction

Wechat

Wechat API wrapper in Elixir.

CI Hex.pm Hex.pm

Installation

def deps do
  [{:wechat, "~> 0.4.0"}]
end

Configuration (optional)

config :wechat,
  adapter_opts: {Wechat.Adapters.Redis, ["redis://localhost:6379/0"]},
  httpoison_opts: [recv_timeout: 300_000]

Create a client to call APIs

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
  }}

Create a Wechat implementation

You can implement the Wechat module to simplify the usage.

First, create an implementation by use Wechat :

defmodule MyApp.Wechat do
  use Wechat, otp_app: :my_app

  def users do
    client() |> Wechat.User.get()
  end
end

Config the implementation with Wechat credentials:

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 mode

Wechat implementation examples

JS-SDK

https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html

<script type="text/javascript" src="//res.wx.qq.com/open/js/jweixin-1.4.0.js"></script>
<%= raw MyApp.Wechat.wechat_config_js(@conn, debug: false, api: ~w(previewImage closeWindow)) %>

<script>
$(function() {
  var urls = [];
  $('img').map(function(){
    url = window.location.origin + $(this).attr('src'),
    urls.push(url);
  });

  $('img').click(function(e) {
    wx.previewImage({
      current: window.location.origin + $(this).attr('src'),
      urls: urls
    });
  })
});
</script>

Process message in Phoenix

https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Receiving_standard_messages.html

  • router.ex
defmodule MyApp.Router do
  scope "/wechat", MyApp do
    resources "/", WechatController, [:index, :create]
  end
end
  • wechat_controller.ex
defmodule MyApp.WechatController do
  use MyApp.Web, :controller

  # Validate signature param
  plug Wechat.Plugs.RequestValidator, module: MyApp.Wechat

  # Parse message
  plug Wechat.Plugs.MessageParser, [module: MyApp.Wechat] when action in [:create]

  def index(conn, %{"echostr" => echostr}) do
    text conn, echostr
  end

  def create(conn, _params) do
    %{"ToUserName" => to, "FromUserName" => from, "Content" => content} = conn.body_params
    reply = %{from: to, to: from, content: content}

    msg = Phoenix.View.render_to_string(EvercamWechatWeb.WechatView, "text.xml", reply: reply)

    # Return encrypted message if possible
    case Wechat.encrypt_message(msg) do
      {:ok, reply} ->
        render(conn, "encrypt.xml", reply: reply)

      {:error, _} ->
        text(conn, msg)
    end
  end
end
  • text.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>
  • encrypt.xml.eex
<xml>
  <Encrypt><![CDATA[<%= @reply.msg_encrypt %>]]></Encrypt>
  <MsgSignature><![CDATA[<%= @reply.msg_signature %>]]></MsgSignature>
  <TimeStamp><%= @reply.timestamp %></TimeStamp>
  <Nonce><![CDATA[<%= @reply.nonce %>]]></Nonce>
</xml>

Users

wechat's People

Contributors

1ternal avatar dependabot-preview[bot] avatar gitter-badger avatar goofansu avatar linjunpop avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

wechat's Issues

Is this package for 微信公众号开发者模式 or 微信开放平台第三方平台 ?

请问这个package是为 微信公众号开发者模式 还是 微信开放平台第三方平台 接入服务的?

Sorry for the silly question, but I couldn't make sure of it from the information provided in the Readme file.

At first glance, it seems like is for 公众号开发者模式, because, as stated in README file, you can specify encoding_aes_key, which is only available in 公众号开发者模式.

But the code also provides Wechat.access_token call to fetch access token, which might be a 微信开放平台第三方平台 thing.

Please clarify, Thanks.

Best,
J

use Wechat 中client()的access_token一直为nil,导致每次请求微信api会重新申请access_token

版本: 0.4.8

config.exs:

config :wechat,
  adapter_opts: {Wechat.Adapters.Sandbox, []},
  httpoison_opts: [recv_timeout: 300_000]

demo:

defmodule MyApp.Wechat do
  use Wechat, otp_app: :my_app

  def users do
    client() |> Wechat.User.get()
  end
end

若使用 MyApp.Wechat.client()会输出:

%Wechat.Client{
  access_token: nil,
  appid: "wx00000000000",
  encoding_aes_key: nil,
  endpoint: "http://************",
  secret: "***********************",
  token: nil
}

access_token一直为nil

每次请求微信的api, MyApp.Wechat.access_token 每次都不同,会消耗完access_token的限制次数。


看过源码后,加入了Map.put(:access_token, access_token())就能解决access_token每次都需要重新获取的问题。

实现:

defmodule BeautyMotherland.Wechat do
  use Wechat, otp_app: :beauty_motherland

  def users do
    client()
    |> Map.put(:access_token, access_token())
    |> Wechat.User.get()
  end

  def sign_jsapi(url) do
    client()
    |> Map.put(:access_token, access_token())
    |> Wechat.Client.sign_jsapi(url)
  end

  def jssdk(url, js_api_list \\ []) do
    %{timestamp: timestamp, noncestr: nonce, signature: signature} = sign_jsapi(url)

    %{
      jsApiList: js_api_list,
      appId: client().appid,
      timestamp: timestamp,
      nonceStr: nonce,
      signature: signature
    }
  end

  def user_info(openid) do
    client()
    |> Map.put(:access_token, access_token())
    |> Wechat.User.info(openid)
  end
end

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.