获取 access token
        详情请参考 http://mp.weixin.qq.com/wiki/index.php?title=通用接口文档

        :return: 返回的 JSON 数据包
553752
def fetch_access_token(self):
        
        return self._fetch_access_token(
            url='https://api.weixin.qq.com/cgi-bin/token',
            params={
                'grant_type': 'client_credential',
                'appid': self.appid,
                'secret': self.secret
            }
        )
448609
def get_content_item(access_token, content_item_id):
	'''
	
	'''

	headers = {'Authorization': 'Bearer ' + str(access_token)}
	content_item_url =\
		construct_content_item_url(enrichment_url, content_item_id)

	request = requests.get(content_item_url, headers=headers)
	if request.status_code == 200:

		content_item = request.json()
		return content_item

	return {'status': request.status_code, "message": request.text}
98399
def retrieve_token(self):
        

        if self.authorization_code:
            request_param = {
                "client_id": self.client_id,
                "client_secret": self.client_secret,
                "redirect_uri": self.redirect_uri,
                "code": self.authorization_code
                }

            if self._extra_token_params:
                request_param.update(self._extra_token_params)

            content_length = len(urlencode(request_param))
            headers = {
                'Content-Length': str(content_length),
                'Content-Type': 'application/x-www-form-urlencoded'
                }
        
            r = requests.post(self.token_uri, data=request_param,
                              headers=headers)
            jsondata = json.loads(r.text)
            self.access_token = jsondata
            return self.access_token

        else:
            print("authorization code is required before getting accesss token")
            print("Please call retrieve_authorization_code() beforehand")
1124519
def request_access_token(self, params):
        
        return self.request(self.access_token_url, method="GET", params=params)
1168347
public function getOauthAuth($access_token, $openid)
    {
        $result = Tools::httpGet(self::API_BASE_URL_PREFIX . self::OAUTH_AUTH_URL . "access_token={$access_token}&openid={$openid}");
        if ($result) {
            $json = json_decode($result, true);
            if (empty($json) || !empty($json['errcode'])) {
                $this->errCode = isset($json['errcode']) ? $json['errcode'] : '505';
                $this->errMsg = isset($json['errmsg']) ? $json['errmsg'] : '无法解析接口返回内容！';
                Tools::log("WechatOauth::getOauthAuth Fail.{$this->errMsg} [{$this->errCode}]", "ERR - {$this->appid}");
                return false;
            } elseif (intval($json['errcode']) === 0) {
                return true;
            }
        }
        return false;
    }
436143
protected function curl_access_token($url, $postFields = NULL)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_TIMEOUT, 3);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_FAILONERROR, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        //https 请求
        if (strlen($url) > 5 && strtolower(substr($url, 0, 5)) == 'https') {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        }

        if (is_array($postFields) && 0 < count($postFields)) {
            $postBodyString = '';
            $postMultipart = FALSE;
            foreach ($postFields as $k => $v) {
                if ('@' != substr($v, 0, 1)) //判断是不是文件上传
                {
                    $postBodyString .= "$k=" . urlencode($v) . "&";
                } else {
                    //文件上传用multipart/form-data，否则用www-form-urlencoded
                    $postMultipart = TRUE;
                }
            }
            $postFields = trim($postBodyString, '&');
            unset($k, $v);
            curl_setopt($ch, CURLOPT_POST, TRUE);
            if ($postMultipart) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
            } else {
                curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
            }
        }

        $reponse = curl_exec($ch);
        curl_close($ch);
        return $reponse;
    }
584802
def get_token(url_base, tenant_id, user, password):
    
    url = 'http://' + url_base + '/v2.0/tokens'
    headers = {'Content-Type': 'application/json'}
    payload = '{"auth":{"tenantId":"' + tenant_id +\
              '","passwordCredentials":{"username":"'\
              + user + '","password":"' + password + '"}}}'
    response = requests.post(url, headers=headers, data=payload)
    if response.status_code != 200:
        print 'error to obtain the token ' + str(response.status_code)
        exit(1)
    response_json = response.json()
    token = response_json['access']['token']['id']
    return token
911857
function callBack($from,$to,$customerSerNum,$fromSerNum,$promptTone)
	  {
        //子帐号鉴权信息验证，对必选参数进行判空。
        $auth=$this->subAuth();
        if($auth!=""){
            return $auth;
        }
        // 拼接请求包体
        if($this->BodyType=="json"){
           $body= "{'from':'$from','to':'$to','customerSerNum':'$customerSerNum','fromSerNum':'$fromSerNum','promptTone':'$promptTone'}";
        }else{
           $body= "<CallBack>
                     <from>$from</from>
                     <to>$to</to>
                     <customerSerNum>$customerSerNum</customerSerNum>
                     <fromSerNum>$fromSerNum</fromSerNum>
                     <promptTone>$promptTone</promptTone>
                   </CallBack>";
        }
        $this->showlog("request body = ".$body);
        // 大写的sig参数
        $sig =  strtoupper(md5($this->SubAccountSid . $this->SubAccountToken . $this->Batch));
        // 生成请求URL
        $url="https://$this->ServerIP:$this->ServerPort/$this->SoftVersion/SubAccounts/$this->SubAccountSid/Calls/Callback?sig=$sig";
        $this->showlog("request url = ".$url);
        // 生成授权：子帐号Id + 英文冒号 + 时间戳
        $authen=base64_encode($this->SubAccountSid . ":" . $this->Batch);
        // 生成包头
        $header = array("Accept:application/$this->BodyType","Content-Type:application/$this->BodyType;charset=utf-8","Authorization:$authen");
        // 发请求
        $result = $this->curl_post($url,$body,$header);
        $this->showlog("response body = ".$result);
        if($this->BodyType=="json"){//JSON格式
           $datas=json_decode($result);
        }else{ //xml格式
           $datas = simplexml_load_string(trim($result," \t\n\r"));
        }
      //  if($datas == FALSE){
//            $datas = new stdClass();
//            $datas->statusCode = '172003';
//            $datas->statusMsg = '返回包体错误'; 
//        }
        return $datas;
	}
46127
public function getAccessToken()
    {
        $param = [
            'grant_type' => 'client_credentials',
            'client_id' => $this->apiKey,
            'client_secret' => $this->secretKey
        ];
        $result = $this->client->post($this->accessTokenUrl(), $param);

        if (!is_array($result)) {
            throw new Exception('请求access token失败');
        }

        $content = json_decode($result['content'], true);
        $this->accessToken = $content['access_token'];
    }
602756
def auth(self, code):
        
        request_data = self.get_access_token_params(code)

        res = self._session.post(**request_data)
        if res.status_code != 200:
            raise APIException(
                request_data['url'],
                res.status_code,
                response=res.content,
                request_param=request_data,
                response_header=res.headers
            )

        json_res = res.json()
        self.update_token(json_res)
        return json_res
1153433
def queryUser(self, groupId):
        

        desc = {
            "name": "GroupUserQueryReslut",
            "desc": "groupUserQuery返回结果",
            "fields": [{
                "name": "code",
                "type": "Integer",
                "desc": "返回码，200 为正常。"
            }, {
                "name": "id",
                "type": "String",
                "desc": "群成员用户Id。"
            }, {
                "name": "users",
                "type": "List<GroupUser>",
                "desc": "群成员列表。"
            }]
        }
        r = self.call_api(
            method=('API', 'POST', 'application/x-www-form-urlencoded'),
            action='/group/user/query.json',
            params={"groupId": groupId})
        return Response(r, desc)
1293310
def get_text(self, title):
        
        r = requests.get(self.api,
                         params={'action': 'parse', 'page': title, 'format': 'json'},
                         headers=self.header)
        jsd = r.json()
        return jsd['parse']['text']['*']
952920
public function get_access_token()
    {
        $token = false;
        if ($this->get_access_token_diy !== false) {
            // 调用用户自定义获取AccessToken方法
            $token = call_user_func($this->get_access_token_diy);
            if ($token) {
                $token = json_decode($token);
            }
        } else {
            // 异常处理: 获取access_token方法未定义
            @error_log('Not set get_tokenDiy method, AccessToken will be refreshed each time.', 0);
        }
        // 验证AccessToken是否有效        
        if (!$this->valid_access_token($token)) {

            // 生成新的AccessToken
            $token = $this->new_access_token();
            if ($token === false) {
                return false;
            }

            // 保存新生成的AccessToken
            if ($this->save_access_token_diy !== false) {
                // 用户自定义保存AccessToken方法    
                call_user_func($this->save_access_token_diy, json_encode($token));
            } else {
                // 异常处理: 保存access_token方法未定义
                @error_log('Not set saveTokenDiy method, AccessToken will be refreshed each time.', 0);
            }
        }
        return $token->access_token;
    }
940082
public static String getPerpetualQR_senceId(String access_token, int senceId) {
		// 获取数据的地址（微信提供）
		String url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + access_token;
		JsonObject content = new JsonObject();
		content.addProperty("action_name", "QR_LIMIT_SCENE");
		JsonObject scene = new JsonObject();
		scene.addProperty("scene_id", senceId);
		JsonObject action_info = new JsonObject();
		action_info.add("scene", scene);
		content.add("action_info", action_info);
		// 发送给微信服务器的数据
		String jsonStr = content.toString();
		String qrurl = null;
		try {
			HttpUtil http = new HttpUtil();
			byte[] data = http.httpsPost(url, jsonStr.getBytes());
			JsonObject json = new JsonParser().parse(new String(data)).getAsJsonObject();
			qrurl = json.get("url").getAsString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return qrurl;
	}
12771
private function get_token(){

        if(self::$token==null){
            $config = $this->get_config();
            $file = $config['TOKEN_PATH'];
            if( Storage::disk()->exists($file) && TIMESTAMP - ( $createTime = Storage::disk()->lastModified($file) ) <= 7200 ){
                $token = Storage::disk()->get($file);
                self::$token = json_encode(array(
                    'token'=>$token,
                    'createtime'=>$createTime
                ));
                return $token;
            }
        }else{
            $token = json_decode(self::$token,true);
            if($token['createtime'] + 7200 > TIMESTAMP){
                return $token['token'];
            }
        }

        //返回远程token
        return $this->get_remote_token();
    }
1138223
public function api()
    {
        //处理消息
        $this->wechat->server->setMessageHandler(function ($m) {
            $this->m = $m;
            Log::info($m);

            if ($m->Event != 'unsubscribe' && $m->Event != 'LOCATION' && $m->Event != 'VIEW' && $m->Event != 'TEMPLATESENDJOBFINISH') {
                //存上行消息
                $msg = new Message();
                $msg->from_user_name = $m->FromUserName;
                $msg->to_user_name = $m->ToUserName;
                $msg->create_time = $m->CreateTime;
                $msg->msg_type = $m->MsgType;
//                $msg->msg_id = isset($m->MsgId) ? $m->MsgId : 0;
                $msg->content = isset($m->Content) ? $m->Content : '';
                $msg->pic_url = isset($m->PicUrl) ? $m->PicUrl : '';
//                $msg->location_x = isset($m->Location_X) ? $m->Location_X : '';
//                $msg->location_x = isset($m->Location_Y) ? $m->Location_Y : '';
//                $msg->scale = isset($m->Scale) ? $m->Scale : '';
                $msg->label = isset($m->Label) ? $m->Label : '';
                $msg->title = isset($m->Title) ? $m->Title : '';
                $msg->description = isset($m->Description) ? $m->Description : '';
                $msg->url = isset($m->Url) ? $m->Url : '';
                $msg->media_id = isset($m->MediaId) ? $m->MediaId : '';
                $msg->thumb_media_id = $m->ThumbMediaId;
                $msg->event = $m->Event;
                $msg->event_key = $m->EventKey;
                $msg->save();
            }

            //从上行消息中提取关键词
            $key = '';
            switch ($m->MsgType) {
                case 'text':
                    $key = $m->Content;

                    break;
                case 'event':
                    switch ($m->Event) {
                        case 'CLICK':
                            $key = $m->EventKey;
                            break;
                        case 'subscribe'://关注事件
                            UserSns::where('openid', $m->FromUserName)->update(['status' => 0]);
                            break;
                        case 'unsubscribe'://取消关注事件
                            UserSns::where('openid', $m->FromUserName)->update(['status' => 1]);
                            break;
                        case 'SCAN':
                    }
                    break;
            }
            $this->key = $key;
            Log::info($this->key);

//            //帮用户生成本站用户数据
//            if (!$this->reg()) {
//                return 'whops';
//            }

            //判断关注默认回复的关键词
            if ($m->Event == 'subscribe' && empty($m->EventKey)) {
                $this->key = $this->keyFollow;
            }

            //事件key会抽风夹带类似这种的 last_trade_no_4009012001201605306519754434
            if (strpos($m->EventKey, 'last_trade_no') === 0) {
                $this->key = $this->keyFollow;
            }

            //根据关键词处理回复
            $res = FALSE;
            if (!empty($this->key)) {
                $this->r = $this->returnReply();
            } else {
                $this->r = '';
            }

            //入库消息.取关和地理位置不记录

            return $this->r;

        });

        return $this->wechat->server->serve();

    }
793888
function getAccessToken(callback){

    console.log("Requesting access token from server...");

    var credentials = {
            scope: "messaging:push",
            grant_type: "client_credentials",
            client_id: CLIENT_ID,
            client_secret: CLIENT_SECRET
    }

    var post_data = querystring.stringify(credentials);

    var post_options = {
      host: "api.amazon.com",
      port: "443",
      path: "/auth/O2/token",
      method: "POST",
      headers: {
          "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
      }
    };

    var req = https.request(post_options, function(res) {

        var data = "";

        res.on("data", function (chunk) {
            data += chunk;
        });

        res.on("end", function() {
            console.log("\nAccess token response:", data);
            var accessToken = JSON.parse(data).access_token;
            callback(accessToken);
        });

    });

    req.on("error", function(e) {
      console.log("\nProblem with access token request: ", e.message);
    });

    req.write(post_data);
    req.end();

}