微信小程序获取手机号ruby解密

微信文档:
https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/getPhoneNumber.html

module WeMinigram
  class MinigramApi
    def initialize(session_key: "")
      @appid = Setting.weixin.minigram.appid
      @appsecret = Setting.weixin.minigram.appsecret
      @code = ""
      @session_key = session_key || ""
      @unionid = ""
      @openid = ""
    end

    def decrypt(_encryptedData, _iv)
      session_key = Base64.decode64(@session_key)
      encryptedData = Base64.decode64(_encryptedData)
      iv = Base64.decode64(_iv)

      decipher = OpenSSL::Cipher::AES128.new(:CBC)
      decipher.decrypt
      decipher.key = session_key
      decipher.iv = iv
      result = decipher.update(encryptedData) + decipher.final

      return JSON.parse(result)
      # 获取得到的开放数据为以下 json 结构:
      # {
      #     "phoneNumber": "13580006666",
      #     "purePhoneNumber": "13580006666",
      #     "countryCode": "86",
      #     "watermark":
      #     {
      #         "appid":"APPID",
      #         "timestamp": TIMESTAMP
      #     }
      # }
    end

    def get_access_token(mini_code)
      @code = mini_code
      url = "https://api.weixin.qq.com/sns/jscode2session?appid=#{@appid}&secret=#{@appsecret}&js_code=#{@code}&grant_type=authorization_code"
      res = rest_client_get(url)
      data = res[:data]

      if data && data['errcode'].blank? # 成功
        @session_key = data[:session_key]
        @openid = data[:openid]
        return res[:data].merge(result: 1)
      else # 错误
        return res[:data].to_h.merge(result: 0)
      end

    private

    def rest_client_get(url, query = {})
      begin
        response = RestClient.get(url)

        {
            code: response.code,
            data: JSON(response.body)
        }
      rescue RestClient::ExceptionWithResponse => err
        puts "rest_client_get error #{err.response.code} #{err.response} [#{url}]"
        Rails.logger.info "rest_client_get error #{err.response.code} #{err.response} [#{url}]"
        response = err.response

        {
            code: err.response.code,
            data: JSON(response.body)

        }
      rescue Exception => e
        puts "rest_client_get error -1 #{e} [#{url}]"
        Rails.logger.info "rest_client_get error -1 #{e} [#{url}]"

        {
            code: -1,
            message: "#{e}"

        }
      end
    end

  end
end

你可能感兴趣的:(微信小程序获取手机号ruby解密)