<commit_before>/*!
 * wechat-platform
 *    OAuth 平台授权
 *
 * Copyright (c) 2015 MicLee
 * MIT Licensed
 */

/**
 * V8引擎只在严格模式之下，支持let、const、class
 */
"use strict";

/**
 * Module dependencies.
 */
var urllib = require('urllib');
var extend = require('util')._extend;

/**
* OAuth 平台授权类
*/
var OAuth = function(config) {
 if (!(this instanceof OAuth)) {
    return new OAuth(config);
 }

 if (config.appid && config.appsecret) {
   this.appid = config.appid;
   this.appsecret = config.appsecret;
 } else {
   throw new Error('please check your config');
 }

 this.defaults = {
   headers: {
     'Content-Type': 'application/json'
   }
 };
}

/**
 * urllib的封装
 *
 * @param {String} url 路径
 * @param {Object} opts urllib选项
 *
 * @private
 */
var _request = function *(url, opts) {
 var options = {};
 extend(options, this.defaults);

 for (let key in opts) {
   if (key !== 'headers') {
     options[key] = opts[key];
   } else {
     if (opts.headers) {
       options.headers = options.headers || {};
       extend(options.headers, opts.headers);
     }
   }
 }

 return _resWrapper(yield urllib.requestThunk(url, options));
}

/**
 * 处理返回结果
 */
var _resWrapper = function (response) {
  var data = response.data;
  if (data.errcode) {
    var err = new Error(data.errmsg);
    err.name = 'WechatAPIError';
    err.code = data.errcode;
    throw err;
  }
  return data;
}

/**
 * 用于设置urllib的默认options
 *
 * Examples:
 * ```
 * oauth.setOpts({timeout: 15000});
 * ```
 * @param {Object} opts 默认选项
 */
OAuth.prototype.setOptions = function (options) {
  this.defaults = options;
}

/* ---------------------------- 业务 API ---------------------------- */

/**
 * 获取第三方平台令牌（component_access_token）
 * http请求方式: POST（请使用https协议）
 * https://api.weixin.qq.com/cgi-bin/component/api_component_token
 *
 * 返回结果示例：
 * {
 *  "component_access_token":"<KEY>",
 *  "expires_in":7200
 * }
 *
 * @param {String} ticket 微信后台推送的ticket 十分钟推送一次
 */
OAuth.prototype.getComponentToken = function *(ticket) {
  var url = 'https://api.weixin.qq.com/cgi-bin/component/api_component_token';
  var info = {
    component_appid: this.appid,
    component_appsecret: this.appsecret,
    component_verify_ticket: ticket
  };
  var args = {
    data: info,
    dataType: 'json',
    method: 'POST'
  };

  return yield _request.call(this, url, args);
}

/**
 * 请求跳转授权页面，生成预授权码
 * http请求方式: POST（请使用https协议）
 * https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token=xxx
 *
 * 回调返回结果示例：
 * {
 *  "pre_auth_code":"<KEY>",
 *  "expires_in":600
 * }
 *
 * @param {String} token 第三方平台component_access_token
 */
OAuth.prototype.createPreAuthCode = function *(token) {
  var url = 'https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token=' + token;
  var info = {
    component_appid: this.appid
  };
  var args = {
    data: info,
    dataType: 'json',
    method: 'POST'
  };

  return yield _request.call(this, url, args);
}

/**
 * 获取跳转微信授权页面URL
 *
 * @param {String} preCode 预授权码
 * @param {String} callbackUrl 用户在第三方平台授权页中完成授权流程后，在回调URI中通过URL参数提供给第三方平台方code
 */
OAuth.prototype.getOAuthURL = function *(preCode, callBackUrl) {
  var url = 'https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=' + this.appid
          + '&pre_auth_code=' + preCode
          + '&redirect_uri=' + callBackUrl;

  return url;
}

/**
 * 获取公众号的授权信息
 * http请求方式: POST（请使用https协议）
 * https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token=xxx
 *
 * 返回结果示例：
 * ```
 * {
 *  "authorization_info": {
 *      "authorizer_appid": "wxf8b4f85f3a794e77",
 *      "authorizer_access_token": "<KEY>",
 *      "expires_in": 7200,<commit_msg>response json<commit_after>/*!
 * wechat-platform
 *    OAuth 平台授权
 *
 * Copyright (c) 2015 MicLee
 * MIT Licensed
 */

/**
 * V8引擎只在严格模式之下，支持let、const、class
 */
"use strict";

/**
 * Module dependencies.
 */
var urllib = require('urllib');
var extend = require('util')._extend;

/**
* OAuth 平台授权类
*/
var OAuth = function(config) {
 if (!(this instanceof OAuth)) {
    return new OAuth(config);
 }

 if (config.appid && config.appsecret) {
   this.appid = config.appid;
   this.appsecret = config.appsecret;
 } else {
   throw new Error('please check your config');
 }

 this.defaults = {
   headers: {
     'Content-Type': 'application/json'
   }
 };
}

/**
 * urllib的封装
 *
 * @param {String} url 路径
 * @param {Object} opts urllib选项
 *
 * @private
 */
var _request = function *(url, opts) {
 var options = {};
 extend(options, this.defaults);

 for (let key in opts) {
   if (key !== 'headers') {
     options[key] = opts[key];
   } else {
     if (opts.headers) {
       options.headers = options.headers || {};
       extend(options.headers, opts.headers);
     }
   }
 }

 return _resWrapper(yield urllib.requestThunk(url, options));
}

/**
 * 处理返回结果
 */
var _resWrapper = function (response) {
  var data = response.data;
  if (data.errcode) {
    var err = new Error(data.errmsg);
    err.name = 'WechatAPIError';
    err.code = data.errcode;
    throw err;
  }
  return data;
}

/**
 * 用于设置urllib的默认options
 *
 * Examples:
 * ```
 * oauth.setOpts({timeout: 15000});
 * ```
 * @param {Object} opts 默认选项
 */
OAuth.prototype.setOptions = function (options) {
  this.defaults = options;
}

/* ---------------------------- 业务 API ---------------------------- */

/**
 * 获取第三方平台令牌（component_access_token）
 * http请求方式: POST（请使用https协议）
 * https://api.weixin.qq.com/cgi-bin/component/api_component_token
 *
 * 返回结果示例：
 * {
 *  "component_access_token":"<KEY>",
 *  "expires_in":7200
 * }
 *
 * @param {String} ticket 微信后台推送的ticket 十分钟推送一次
 */
OAuth.prototype.getComponentToken = function *(ticket) {
  var url = 'https://api.weixin.qq.com/cgi-bin/component/api_component_token';
  var info = {
    component_appid: this.appid,
    component_appsecret: this.appsecret,
    component_verify_ticket: ticket
  };
  var args = {
    data: info,
    dataType: 'json',
    method: 'POST'
  };

  return yield _request.call(this, url, args);
}

/**
 * 请求跳转授权页面，生成预授权码
 * http请求方式: POST（请使用https协议）
 * https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token=xxx
 *
 * 回调返回结果示例：
 * {
 *  "pre_auth_code":"Cx_Dk6qiBE0Dmx4EmlT3oRfArPvwSQ-oa3NL_fwHM7VI08r52wazoZX2Rhpz1dEw",
 *  "expires_in":600
 * }
 *
 * @param {String} token 第三方平台component_access_token
 */
OAuth.prototype.createPreAuthCode = function *(token) {
  var url = 'https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token=' + token;
  var info = {
    component_appid: this.appid
  };
  var args = {
    data: info,
    dataType: 'json',
    method: 'POST'
  };

  return yield _request.call(this, url, args);
}

/**
 * 获取跳转微信授权页面URL
 *
 * @param {String} preCode 预授权码
 * @param {String} callbackUrl 用户在第三方平台授权页中完成授权流程后，在回调URI中通过URL参数提供给第三方平台方code
 */
OAuth.prototype.getOAuthURL = function *(preCode, callBackUrl) {
  var strUrl = 'https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=' + this.appid
          + '&pre_auth_code=' + preCode
          + '&redirect_uri=' + callBackUrl;

  var result = {
    url: strUrl
  }
  return result;
}

/**
 * 获取公众号的授权信息
 * http请求方式: POST（请使用https协议）
 * https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token=xxx
 *
 * 返回结果示例：
 * ```
 * {
 *  "authorization_info": {
 *      "authorizer_appid": "wxf8b4f85f3a794e77",
 *      "authorizer_access_token": "<KEY>",
 *      "expires_in": 7200,
{'fraction_non_alphanumeric': 0.16952100615466953, 'fraction_numerical': 0.009900990099009901, 'mean_word_length': 3.2183972911963883, 'pattern_counts': {'":': 16, '<': 8, '<?xml version=': 0, '>': 8, 'https://': 12, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5578411', 'n_tokens_mistral': 3038, 'n_tokens_neox': 3091, 'n_words': 478}