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.1"

Instance Method Summary collapse

Instance Method Details

#access_tokenObject



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

def access_token
  read_access_token || refresh_access_token
end

#add_tag_for_users(users, tag_id) ⇒ Object



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

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



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

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

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

#find_tag_id_by_name(name) ⇒ Object



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

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

#find_users_by_tag(name) ⇒ Object



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

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



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

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').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



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

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

#user_tagsObject

Get all user tag



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

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

#usersObject

Get all followers



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

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