lib/blsm-mp-wx.rb in blsm-mp-wx-0.3.2 vs lib/blsm-mp-wx.rb in blsm-mp-wx-0.3.3
- old
+ new
@@ -9,10 +9,11 @@
require 'active_support'
require 'blsm-mp-wx/version'
require 'blsm-mp-wx/model/active_record'
require 'blsm-mp-wx/model/vd_mp_wx'
require 'blsm-mp-wx/model/vd_mp_msg'
+require 'blsm-mp-wx/model/vd_wx_user'
require 'json'
require 'faraday'
module BlsmMpWx
ERROR_CODES = {
@@ -346,9 +347,60 @@
end
rescue Exception => e
puts e
end
returned_openids
+ end
+
+ #sns登录获取用户信息
+ def sns_login_userinfo(code)
+ app_id = 'wx143306afc47c63a6'
+ app = VdMpWx.where(app_id: app_id).first
+
+ conn = Faraday.new(:url => 'https://api.weixin.qq.com')
+ response = conn.post do |req|
+ req.url '/sns/oauth2/access_token'
+ req.headers['Content-Type'] = 'application/xml'
+ req.params[:appid] = app_id
+ req.params[:secret] =app.app_secret
+ req.params[:code] = code
+ req.params[:grant_type] = 'authorization_code'
+ end
+
+ if response.body.encoding != 'UTF-8'
+ response_body = response.body.force_encoding('UTF-8')
+ else
+ response_body = response.body
+ end
+
+ res = parse_json(response_body)
+
+
+ conn = Faraday.new(:url => 'https://api.weixin.qq.com')
+ response = conn.post do |req|
+ req.url '/sns/userinfo'
+ req.headers['Content-Type'] = 'application/xml'
+ req.params[:access_token] = res['access_token']
+ req.params[:openid] = res['openid']
+ end
+ if response.body.encoding != 'UTF-8'
+ response_body = response.body.force_encoding('UTF-8')
+ else
+ response_body = response.body
+ end
+
+ res = parse_json(response_body)
+ VdWxUser.find_or_create_by({app_id: app_id, openid: res['openid']}) do |u|
+ u.update_attributes({nickname: res['nickname'],
+ sex: res['sex'],
+ unionid: res['unionid'],
+ language: res['language'],
+ city: res['city'],
+ province: res['province'],
+ country: res['country'],
+ headimgurl: res['headimgurl'],
+ })
+ end
end
private
#解析json类型的数据,并将最后的数据转为hash或array
# +json_data_str+ 要转换的json数据