Giter Site home page Giter Site logo

elixir_wechat's Introduction

ElixirWeChat

hex.pm hex.pm hex.pm github.com

Elixir API wrapper for WeChat.

Introduction

At present, there are two ways to build application in WeChat Official Account open ecosystem:

  • Integrates public APIs after turn on your WeChat Official Account into the developer mode (see details), here named it as common application in document of elixir_wechat, the same below;

  • Authorizes your WeChat Official Account to the WeChat Official Account third-party platform application (see details), here named it as component application in document of elixir_wechat, the same below.

This library wants to provide a flexible way to explicitly call all of WeChat's API functions, meanwhile helps to maintain the fetch-expiry-refresh loop cycle of access_token, you can choose your way to storage access_token, jssdk-ticket and card-ticket as well.

Background

Refer the official document's recommend there needs the centralization nodes to maintain the life cycle of access_token (fetch/storage/refresh).

This library is designed for these four use scenarios:

Application Scenario Storage Behaviour
common client WeChat.Storage.Client
common hub WeChat.Storage.Hub
component client WeChat.Storage.ComponentClient
component hub WeChat.Storage.ComponentHub

Notice:

  • The above "client" means the business logic which rely on the access_token maintained by the centralization nodes;

  • The above "hub" means the implements in the centralization nodes.

How to use

Install

def deps do
  [
   {:elixir_wechat, "~> 0.4"}
  ]
end

Http Client

Currently, this library uses Tesla.Adapter.Finch to process http request/response, you can optionally define Finch's default pool setting like this:

config :elixir_wechat,
  pool_size: 100,
  pool_count: 1
  • pool_size, optional, number of connections to maintain in each pool, see Finch.request/6 for details, default to 100.
  • pool_count, optional, number of pools to start, see Finch.request/6 for details, default to 1.

Usage

First of all, let's add the built-in plug into the router of your server:

plug WeChat.Plug.Pipeline,
  adapter_storage: [
    component: WeChat.Storage.ComponentLocal,
    common: WeChat.Storage.Local
  ]

The adapter_storage option is required, according to your use case, you need to implement your common or component storage refer the corresponding behaviour, if your server need to cover both of them, just add them as the same time.

After the above setup, there will add the following URLs into your server for internal interactive, both of them are used to read/write cacheable data from the centralization nodes.

POST "/refresh/access_token"
GET "/client/access_token"
GET "/client/component_access_token"
GET "/client/ticket"

For example, assume that the above setup server is running as "http://localhost:4000", now let's invoke the get material list API as an example from the client side.

POST /cgi-bin/material/batchget_material?access_token=ACCESS_TOKEN
Host: api.weixin.qq.com
Scheme: https

Body: {
  "type": "image",
  "offset": 0,
  "count": 10
}

As a common client application

defmodule MyClient do
  use WeChat,
    adapter_storage: {:default, "http://localhost:4000"},
    appid: "MyAppID"
end

MyClient.request(
  :post,
  url: "/cgi-bin/material/batchget_material",
  body: %{type: "image", offset: 0, count: 10}
)

Or use WeChat.request/2 directly

WeChat.request(
  :post,
  appid: "MyAppID",
  adapter_storage: {:default, "http://localhost:4000"},
  url: "/cgi-bin/material/batchget_material",
  body: %{type: "image", offset: 0, count: 10}
)

As a component client application

defmodule MyComponentClient do
  use WeChat.Component,
    adapter_storage: {:default, "http://localhost:4000"},
    appid: "MyComponentAppID",
    authorizer_appid: "MyAuthorizerAppID"
end

MyComponentClient.request(
  :post,
  url: "/cgi-bin/material/batchget_material",
  body: %{type: "image", offset: 0, count: 10}
)

Or use WeChat.request/2 directly

WeChat.request(
  :post,
  appid: "MyComponentAppID",
  authorizer_appid: "MyAuthorizerAppID",
  adapter_storage: {:default, "http://localhost:4000"},
  url: "/cgi-bin/material/batchget_material",
  body: %{type: "image", offset: 0, count: 10}
)

Please notice the access_token parameter will be automatically appended by this library, if access_token is expired when calling, there will retry refresh access_token from self-host centralization nodes, and then self-host centralization nodes will maintain the life cycle of a fresh access_token.

The default adapter storage {:default, "http://localhost:4000"} is implemented as a client connects to the self-host hub servers via some predefined HTTP API functions:

  • The WeChat.Storage.Adapter.DefaultClient is used for common application.
  • The WeChat.Storage.Adapter.DefaultComponentClient is used for component application.

In general use, you need to define your adapter storage implemented the corresponding behaviour, the aim of this design to adapt as much as you want.

Document

$ mix docs

Test

First you need to add the following environment variables in the config/test.exs, and then run mix test in the root of this repo.

System.put_env("TEST_COMMON_APPID", "...")
System.put_env("TEST_COMPONENT_APPID", "...")
System.put_env("TEST_HUB_URL", "...")
System.put_env("TEST_OPENID", "...")

License

MIT

elixir_wechat's People

Contributors

xinz avatar feng19 avatar kianmeng avatar

Stargazers

 avatar shynome avatar Yos avatar Warren.yu avatar wp1027322856 avatar xcplus avatar xuming avatar Frampt avatar AICells avatar Chris avatar Naupio avatar Ian avatar

Watchers

Jandy avatar James Cloos avatar  avatar xcplus avatar  avatar

elixir_wechat's Issues

Hub场景下,指定appid,调用token/1接口报错

Hub场景下,指定appid,调用token/1接口报错,
配置如下:

use WeChat,
    appid: "wx1111111111111111",
    scenario: :hub,
    adapter_storage: Wx.Adapter.Storage.WeChat

调用Wx.token :get
报错:

iex(1)> Wx.token :get

17:40:21.531 [info]  get access_token, configs: %{http_verbs: ["get"], scenario: "hub", uri_prefix: "cgi-bin/token", use_for_component: false}, module: Wx

17:40:21.914 [info]  GET https://api.weixin.qq.com/cgi-bin/token -> 200 (351.320 ms)

17:40:21.914 [debug]
>>> REQUEST >>>
Query: grant_type: client_credential
Query: appid: wx1111111111111111
Query: secret: 111111111111111111111111111111111111

(no headers)
(no body)

<<< RESPONSE <<<
connection: keep-alive
date: Sat, 12 Oct 2019 09:40:21 GMT
content-length: 194
content-type: application/json; encoding=utf-8

{"access_token":"access_token1111111111111111111111","expires_in":7200}

17:40:21.923 [error] >>>> occur error in common middleware: %UndefinedFunctionError{arity: 3, function: :set_access_token, message: nil, module: Wx, reason: nil} <<<<
{:error,
 %UndefinedFunctionError{
   arity: 3,
   function: :set_access_token,
   message: nil,
   module: Wx,
   reason: nil
 }}

抛出错误的地方WeChat.Http.Middleware.Common.reserve_access_token/3

defp reserve_access_token(%URI{path: "/cgi-bin/token"}, response_body, options) do
    wechat_module = Keyword.get(options, :module)
    appid = Http.grep_appid(options)
    apply(wechat_module, :set_access_token, [appid, response_body, options])
  end

Wx模块只有生成set_access_token/2函数,此处应该是确实case没有appid参数的情况。

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.