Module: Ocean::Wechat

Extended by:
Wechat
Included in:
Wechat
Defined in:
lib/ocean/wechat.rb,
lib/ocean/wechat/version.rb

Constant Summary collapse

BASE_URL =
'https://api.weixin.qq.com/cgi-bin'
ACCESS_TOKEN_FILE =
'tmp/access_token.txt'
NOTIFY_RECIPIENT_FILE =
'config/wechat_notify.yml'
SUCCESS_CODE =
0
ACCESS_TOKEN_EXPIRED_CODE =
420_01
ACCESS_TOKEN_INVALID_CODE =
400_01
NOTIFY_DEFAULT_COLOR =
'#173177'
MAX_RETRY_NUM =
5
VERSION =
"0.1.3"

Instance Method Summary collapse

Instance Method Details

#access_tokenObject



20
21
22
# File 'lib/ocean/wechat.rb', line 20

def access_token
  read_access_token || refresh_access_token
end

#add_tag_for_users(users, tag_id) ⇒ Object



91
92
93
94
95
96
97
98
# File 'lib/ocean/wechat.rb', line 91

def add_tag_for_users(users, tag_id)
  params = {
    open_list: users,
    tagid: tag_id
  }

  request("#{BASE_URL}/tags/members/batchtagging",  params, :post)
end

#create_user_tag(name) ⇒ Object



60
61
62
63
64
65
66
67
68
# File 'lib/ocean/wechat.rb', line 60

def create_user_tag(name)
  params = {
    tag: {
      name: name
    }
  }

  request("#{BASE_URL}/tags/create", params, :post)
end

#find_tag_id_by_name(name) ⇒ Object



87
88
89
# File 'lib/ocean/wechat.rb', line 87

def find_tag_id_by_name(name)
  user_tags[:tags].detect { |item| item['name'] == name }['id']
end

#find_users_by_tag(name) ⇒ Object



75
76
77
78
79
80
81
82
83
84
85
# File 'lib/ocean/wechat.rb', line 75

def find_users_by_tag(name)
  res = request(
    "#{BASE_URL}/user/tag/get",
    {
      tagid: find_tag_id_by_name(name)
    },
    :post
  )

  res['count'] == 0 ? [] : res['data']['openid']
end

#notify(**args) ⇒ Object

Use wechat template to send message



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/ocean/wechat.rb', line 25

def notify(**args)
  notify_block = lambda do |open_id|
    url = "#{BASE_URL}/message/template/send"
    params = {
      touser: open_id,
      template_id: wechat_notify(args[:event], 'template'),
      url: args[:redirect_url],
      data: {}
    }

    args.each { |k, v| params[:data][k] = { value: v, color: NOTIFY_DEFAULT_COLOR } }

    request(url, params, :post)
  end

  [].tap do |item|
    wechat_notify(args[:event], 'users').split(',').each do |open_id|
      item << {
        open_id: open_id,
        success: notify_block.call(open_id)[:errcode] == SUCCESS_CODE
      }
    end
  end
end

#notify_templatesObject

Get all notify template



51
52
53
# File 'lib/ocean/wechat.rb', line 51

def notify_templates
  request("#{BASE_URL}/template/get_all_private_template")
end

#user_tagsObject

Get all user tag



71
72
73
# File 'lib/ocean/wechat.rb', line 71

def user_tags
  request("#{BASE_URL}/tags/get")
end

#usersObject

Get all followers



56
57
58
# File 'lib/ocean/wechat.rb', line 56

def users
  request("#{BASE_URL}/user/get")
end