module WechatGate::SendMessage

Public Instance Methods

mass_send(open_ids, msg_options = {}) click to toggle source

mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140549&token=&lang=zh_CN 这个接口有发送限制,服务号每月只能发送4次,订阅号每天一次

# File lib/wechat_gate/send_message.rb, line 11
def mass_send open_ids, msg_options = {}
  payload = {
     "touser": [open_ids].flatten,
      "msgtype": "text",
      "text": { "content": "hello from boxer."}
  }.merge(msg_options)

  WechatGate::Request.send(
    "https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token=#{self.access_token}",
    :post,
    payload.to_json
  )
end
single_send(open_id, content) click to toggle source
# File lib/wechat_gate/send_message.rb, line 67
def single_send open_id, content
  single_send_if_need_refresh_cookie

  opts = {
    method: :post,
    url: "https://mp.weixin.qq.com/cgi-bin/singlesend?t=ajax-response&f=json&token=#{self.single_send_token}&lang=zh_CN",
    verify_ssl: false,
    payload: {
      token: self.single_send_token,
      lang: "zh_CN",
      f: "json",
      ajax: 1,
      random: Random.rand,
      type: 1, # 文本消息
      content: content,
      tofakeid: open_id,
      imgcode: ""
    }.to_query,
    headers: {
      'User-Agent': self.single_send_ua,
      'Cookie': self.single_send_cookies,
      'Referer': "https://mp.weixin.qq.com/cgi-bin/singlesendpage?t=message/send&action=index&tofakeid=#{open_id}&token=#{self.single_send_token}&lang=zh_CN"
    }
  }

  response = RestClient::Request.execute(opts)
  data = JSON.parse(response)
  raise response.to_s if data['errmsg'] and data['errmsg'] != 'ok'
  data
end

Private Instance Methods

single_send_login_and_refresh_cookies_w_token() click to toggle source

登录公众号,缓存登录后的cookie和token

# File lib/wechat_gate/send_message.rb, line 109
def single_send_login_and_refresh_cookies_w_token
  opts = {
    method: :post,
    url: "https://mp.weixin.qq.com/cgi-bin/login?lang=zh_CN",
    verify_ssl: false,
    payload: {
      username: self.config['wechat_login_username'],
      pwd: Digest::MD5.hexdigest(self.config['wechat_login_password']),
      imgcode: "",
      f: "json"
    }.to_query,
    headers: {
      'User-Agent': self.single_send_ua,
      'Referer': 'https://mp.weixin.qq.com/'
    }
  }

  response = RestClient::Request.execute(opts)
  data = JSON.parse(response)
  raise response.to_s if data['errmsg'] and data['errmsg'] != 'ok'

  self.single_send_cookies = response.cookies.map {|k, v| k + "=" + v}.join("; ")
  data["redirect_url"].gsub(/token=(\d+)/) { |x| self.single_send_token = $1 }
  self.single_send_cookies_refreshed_at = Time.now.to_i
end