function getNumAudience($code, $gender, $accessToken) { global $aux_num_intentos, $num_intentos, $data_acount_facebook, $data_acount_facebook_index; $numAudience = ""; $ban = 0; while ($ban == 0) { try { $datos = file_get_contents('https://graph.facebook.com/act_' . $data_acount_facebook[$data_acount_facebook_index]['accountId'] . '/reachestimate?endpoint=/act_' . $data_acount_facebook[$data_acount_facebook_index]['accountId'] . '/reachestimate&accountId=' . $data_acount_facebook[$data_acount_facebook_index]['accountId'] . '&locale=es_LA&targeting_spec={"genders":[' . $gender . '],"age_max":65,"age_min":13,"broad_age":true,"regions":[],"countries":["' . $code . '"],"cities":[],"zips":[],"radius":0,"keywords":[],"connections":[],"excluded_connections":[],"friends_of_connections":[],"relationship_statuses":null,"interested_in":[],"college_networks":[],"college_majors":[],"college_years":[],"education_statuses":[0],"locales":[],"work_networks":[],"user_adclusters":[]}&method=get&access_token=' . $accessToken); $datosarray2 = json_decode($datos, true); $numAudience = $datosarray2['users']; if ($numAudience != "" && is_numeric($numAudience)) { $ban = 1; } else { sleep(3); //Espera 3 minutos $accessToken = getAccessToken(); //Trata de obtener un nuevo access_token } } catch (Exception $e) { if ($aux_num_intentos++ > $num_intentos) { informarError(); } sleep(3); //Espera 3 minutos $accessToken = getAccessToken(); //Trata de obtener un nuevo access_token } } return $numAudience; }
function getWxUserByOpenid($openid) { $access_token = getAccessToken(); $param = array('access_token' => $access_token, 'openid' => $openid, 'lang' => 'zh_CN'); $url = "https://api.weixin.qq.com/cgi-bin/user/info"; //获取userinfo" $resp = SimpleHttpClient::get($url, $param); $resp = parseResponse($resp); return $resp; }
/** * 构造函数 * * */ public function __construct() { parent::__construct(); $this->wxWechatModel = D('WxWechat'); $this->wxUserModel = D('WxUser'); $this->wxGoodsModel = D('WxGoods'); $this->wxGoodsCategoryModel = D('WxGoodsCategory'); /* 微信入口进来,从微信获取用户信息 */ if (isset($_GET['code'])) { $AccessToken = getAccessToken(); $appid = C('APPID'); $secret = C('APPSECRET'); $msg = file_get_contents('https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appid . '&secret=' . $secret . '&code=' . $code . '&grant_type=authorization_code'); $merchantOpenid = json_decode($msg, true); /* 通过openid从数据库获取用户的微信信息 */ $merchantWechat = $this->wxWechatModel->getWechat($merchantOpenid['openid']); if (!$merchantWechat) { /* 如果本地数据库中不存在,则从微信服务器获取 */ $requestUrl = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $accessToken . '&openid=' . $merchantOpenid . '&lang=zh_CN'; $getMerchantWechat = file_get_contents($requestUrl); $merchantWechat = json_decode($getMerchantWechat, true); } /* 如果数据库中获取失败,同时也不能从微信服务器获取用户信息,提示失败 */ if (!$merchantWechat) { die('Param fail'); } /* 把商户微信个人资料存入session */ session('merchantWechat', $merchantWechat); } /* 测试数据start:模拟登陆 */ $testStr = '{ "subscribe": 1, "openid": "oaQ8auGYY-uQTtIUAFFxqnQJpjWQ", "nickname": "Jahng", "sex": 1, "language": "zh_CN", "city": "广州", "province": "广东", "country": "中国", "headimgurl": "http://wx.qlogo.cn/mmopen/w9h84ibs6ic2cwVYeJTqmRtNpkhXTqYMrAGA5mAW6d5rPQ4qHvDuSkaTlrWEEf1v8icFFOrITC8MRvBrKz3Es35PzqpO7zic10CD/0", "subscribe_time": 1426411696, "remark": "" }'; $merchantWechat = json_decode($testStr, true); session('merchantWechat', $merchantWechat); /* 测试数据end */ /* 如果没有商户微信信息,访问失败 */ if (!session('merchantWechat')) { die('Param fail'); } /* 获取用户的微信个人信息 */ $this->merchantWechat = session('merchantWechat'); /* 获取用户微销平台个人信息 */ $this->merchantUser = $this->wxUserModel->getUser(array('openid' => $this->merchantWechat['openid'])); }
function getFilter($currPage, $keyword, $availability, $industry) { $consumer_key = KEY; $consumer_secret = SECRET; $req_url = 'https://public-api.expertfile.com/v1/organization/' . ID . '/getfilters'; $oauth = getAccessToken($consumer_key, $consumer_secret, $req_url); $req_url = $req_url; $params = http_build_query($oauth); $ch = curl_init($req_url . '?' . $params); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $responsefromwcf = curl_exec($ch); curl_close($ch); $responseData = json_decode(urldecode($responsefromwcf)); return $responseData; }
function getResults() { $consumer_key = KEY; $consumer_secret = SECRET; $req_url = 'https://public-api.expertfile.com/v1/organization/' . ID . '/search'; $oauth = getAccessToken($consumer_key, $consumer_secret, $req_url); $parameters = array('fields' => urlencode('user:firstname,user:lastname,user:job_title,tagline,user:location:city,user:location:state,user:location:country'), 'keywords' => urlencode(''), 'location' => urlencode(''), 'industry' => urlencode(''), 'portfolio' => urlencode(''), 'availability' => urlencode(''), 'fee_min' => urlencode(''), 'fee_max' => urlencode(''), 'page_number' => urlencode(1), 'page_size' => 99999, 'keyword' => urlencode('')); $req_url = $req_url; $params = http_build_query($oauth) . '&' . http_build_query($parameters); $ch = curl_init($req_url . '?' . $params); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $responsefromwcf = curl_exec($ch); curl_close($ch); $responseData = json_decode($responsefromwcf); return $responseData; }
function lzmatch_request() { $ak = getAccessToken(); if ($ak) { $matchKey = $_REQUEST['key']; $matchData = getMatch($ak, $matchKey, 'full_card'); wp_send_json(array('data' => $matchData)); exit; } else { setAccessToken(); $ak = getAccessToken(); if ($ak) { lzmatch_request(); } else { die('Error'); } } }
function nextAccessToken() { global $accessToken_data, $accessToken_data_index, $accessToken, $accountId, $nun_intentos, $max_nun_intentos; $accessToken_data_index++; if ($accessToken_data_index < count($accessToken_data)) { $accessToken = $accessToken_data[$accessToken_data_index]['access_token']; $accountId = $accessToken_data[$accessToken_data_index]['accountId']; } else { $nun_intentos++; if ($nun_intentos < $max_nun_intentos) { setAccessToken(); $accessToken_data = getAccessToken(); $accessToken_data_index = -1; nextAccessToken(); } else { informarErrorActividades(); } } }
function nextAccessToken() { global $accessToken_data, $accessToken_data_index, $accessToken, $accountId, $pageId, $pageName, $nun_intentos, $max_nun_intentos; $accessToken_data_index++; if ($accessToken_data_index < count($accessToken_data)) { $accessToken = $accessToken_data[$accessToken_data_index]['access_token']; $accountId = $accessToken_data[$accessToken_data_index]['accountId']; $pageId = $accessToken_data[$accessToken_data_index]['pageId']; $pageName = $accessToken_data[$accessToken_data_index]['pageName']; } else { $nun_intentos++; if ($nun_intentos < $max_nun_intentos) { setAccessToken(); $accessToken_data = getAccessToken(); $accessToken_data_index = -1; nextAccessToken(); } else { send_email('country_language_3_1', 'Owloo ERROR - Pais LANGUAGE 3.1', 'ERROR en la captura de datos.', true, 'Access Token - Pais LANGUAGE - ID = ' . $_SERVER['argv'][1]); } } }
function getJsApiTicket($appId, $appSecret) { // jsapi_ticket 应该全局存储与更新,以下代码以写入到文件中做示例 $ticket = _ROOT_ . "/jsapi_ticket.json"; //$data = json_decode(file_get_contents("jsapi_ticket.json")); $data = json_decode(file_get_contents($ticket)); if ($data->expire_time < time()) { $accessToken = getAccessToken($appId, $appSecret); $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token={$accessToken}"; $res = json_decode(httpGet($url)); $ticket = $res->ticket; if ($ticket) { $data->expire_time = time() + 7000; $data->jsapi_ticket = $ticket; $fp = fopen($ticket, "w"); fwrite($fp, json_encode($data)); fclose($fp); } } else { $ticket = $data->jsapi_ticket; } return $ticket; }
function getYearlyDashboardMetrics() { global $coll; $query = $coll->findOne(array('username' => $_SESSION["username"])); $refresh_token = $query['ga_refresh_token']; $property = $query['ga_web_property']['ga_property_id']; $access_token = getAccessToken($refresh_token); $endDate = date('Y-m-d'); $startDate = date('Y-m-d', strtotime('-365 day')); if (isset($property)) { //Get daily visits and new visits for the last month $url = 'https://www.googleapis.com/analytics/v3/data/ga?ids=ga:' . $property . '&start-date=' . $startDate . '&end-date=' . $endDate . '&metrics=ga:visitors,ga:newVisits&dimensions=ga:year,ga:month'; $ch = curl_init(); $timeout = 5; curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . $access_token)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); $data = curl_exec($ch); curl_close($ch); return json_decode($data, true); } }
define('API_SECRET', 'a1580d3de5b915007796abfd3b72466e'); define('REDIRECT_URI', 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['SCRIPT_NAME']); define('SCOPE', 'read_stream'); // You'll probably use a database session_name('facebook'); session_start(); // OAuth 2 Control Flow if (isset($_GET['error'])) { // LinkedIn returned an error print $_GET['error'] . ': ' . $_GET['error_description']; exit; } elseif (isset($_GET['code'])) { // User authorized your application if ($_SESSION['state'] == $_GET['state']) { // Get token so you can make API calls getAccessToken(); } else { // CSRF attack? Or did you mix up your states? exit; } } else { if (empty($_SESSION['expires_at']) || time() > $_SESSION['expires_at']) { // Token has expired, clear the state $_SESSION = array(); } if (empty($_SESSION['access_token'])) { // Start authorization process getAuthorizationCode(); } } // Congratulations! You have a valid token. Now fetch your profile
<?php include_once 'modules/config.php'; if (!loggedIn()) { echo '<script> window.location="login.php"; </script> '; } else { $query = $coll->findOne(array('username' => $_SESSION["username"])); $refresh_token = $query['ga_refresh_token']; if (!isset($query['ga_refresh_token'])) { echo '<script> window.location="' . $get_ga_code_url . '"; </script> '; } else { $access_token = getAccessToken($refresh_token); //Get web properties for account if (isset($access_token)) { $result_properties = getWebProperties($access_token); foreach ($result_properties['items'] as $obj_add) { $dropdown_add .= "<option value='" . $obj_add['id'] . "*" . $obj_add['name'] . "'>" . $obj_add['name'] . "</option>"; } foreach ($query['ga_web_property'] as $obj_delete) { $dropdown_delete .= "<option value='" . $obj_delete['ga_property_id'] . "'>" . $obj_delete['ga_property_name'] . "</option>"; } } } if (isset($_POST['property_add'])) { $try = explode('*', $_POST['property_add']); $ga_property_id = $try[0]; $ga_property_name = $try[1]; setWebProperty($query['username'], $ga_property_id, $ga_property_name); echo '<script>parent.window.location.reload(true);</script>'; } if (isset($_POST['property_delete'])) {
<?php /* * 菜单管理页面 * */ global $token; $token = getAccessToken(); function requestMenu() { global $token; $url = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token=" . $token; $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_BINARYTRANSFER, true); $res = curl_exec($ch); curl_close($ch); return $res; } if (isset($_POST['sectionCount'])) { $sectionCount = $_POST['sectionCount']; $menu = []; for ($idx = 0; $idx < $sectionCount; $idx++) { $subMenu = []; for ($idy = 0; $idy < 5; $idy++) { if (!empty($_POST[$idx . '_subName_' . $idy]) && $_POST[$idx . '_subName_' . $idy] != 'none') { $subMenu[$idy] = getCorrectSubmenu($idx, $idy); } } if (!empty($_POST[$idx . '_menu'])) { $menu[$idx] = getCorrectMainMenu($idx, $subMenu);
public function home_select_booktype_unique_mobile() { $ret->status = 0; $ret->msg = 'No Data'; if ($_REQUEST['code']) { //just authenticated the application $params->app_id = $this->config->item('fb_appkey'); //$params->redirect_url = $this->config->item('fb_canvaspage') . '/main/home_select_booktype/'; $params->redirect_url = $this->config->item('fb_canvaspage') . '/main/filter_page/'; $params->app_secret = $this->config->item('fb_appsecret'); $params->code = trim($_REQUEST['code']); $token_info = getAccessToken($params); $user = getFacebookUserDetails($params); //setcookie("hardcover_fbid", $user->id, 0,'/'); //setcookie("hardcover_token", $token_info->access_token,0,'/'); //expires in 2hrs $this->retrieve_fbdata($user->id, $token_info->access_token); $this->start_create_book(); } else { //this is creating another book $ret->status = 1; $ret->msg = ''; //$this->start_create_book(); //$this->start_create_book(); } $param = new stdClass(); $param->book_info_id = $_COOKIE['hardcover_book_info_id']; $param->facebook_id = $_COOKIE['hardcover_fbid']; $data['token'] = $_COOKIE['hardcover_token']; $data['book_filter'] = $this->filter_model->get_filter($param); $data['user_albums'] = $this->filter_model->get_user_albums($param); $data['user_albums_data'] = array(); $p_data = ''; foreach ($data['user_albums'] as $k1 => $v1) { $p_data = ''; $param->album_id = $v1->album_id; $photo_data = $this->filter_model->get_album_photos($param); if (count($photo_data) > 0) { $p_data .= '<ul style="display:none;" class="alb_photo hide albb_' . $v1->album_id . '" id="photos_from_album" >'; foreach ($photo_data as $k => $v) { $p_data .= '<li><img src="' . $v->small . '"/><br/><center><input type="checkbox" name="photo[' . $v1->album_id . '][' . $v->fb_dataid . ']" id="photo_' . $v->fb_dataid . '" value="' . $v->fb_dataid . '" /></center></li>'; } $p_data .= '</ul>'; } $data['user_albums_data'][$v1->album_id] = $p_data; } // print_r($data); exit; $ret->data = $this->load->view('filter_page_new_unique_mobile', $data, TRUE); echo json_encode($ret); }
<?php define('ROOT_PATH', realpath(dirname(__FILE__)) . '/'); require_once 'vendor/autoload.php'; require_once 'src/config.php'; require_once 'src/google.php'; require_once 'src/spreadsheet.php'; require_once 'src/insert.php'; //----------------------------------------------------------------------------- $entries = readFromFile(ROOT_PATH . $iniSettings['bug_file']); if (count($entries) == 0) { echo "No Entries"; exit; } //----------------------------------------------------------------------------- $accessToken = getAccessToken($client); $spreadsheet = getSpreadsheet($accessToken, $iniSettings['sheet_title']); $worksheetFeed = $spreadsheet->getWorksheets(); $worksheet = $worksheetFeed->getByTitle('Reported Typos'); //----------------------------------------------------------------------------- $results = insertLine($worksheet, $entries); echo json_encode($results);
<?php require 'ConfigFactory.php'; require 'OAuthRequest.php'; $c = new Creds(); $creds = $c->creds(); $links = $c->links(); $accessTokenData = getAccessToken($links, $creds); $paymentId = ""; $payment = new OAuthRequest($endpoint['getPaymentById'], $accessTokenData, null, $paymentId); $payment->createHeader(); echo $payment->sendRequest();
<?php header("Content-Type: text/html; charset=utf-8"); require_once "./oauth/getAccessToken.php"; require_once "./oauth/getSessionKey.php"; require_once "./common/http_post_contents.php"; require_once "./common/config.inc.php"; require_once "./api/users.getProfileInfo.php"; require_once "./api/users.getInfo.php"; session_destroy(); if (isset($_GET['code'])) { $code = $_GET['code']; $accessToken = getAccessToken($code); $result = json_decode($accessToken); //print_r($result) ; /* Format stdClass Object ( [scope] => operate_like publish_share publish_feed send_invitation [expires_in] => xxx [refresh_token] => xxx [user] => stdClass Object ( [id] => xxx [name] => xxx [avatar] => Array ( [0] => stdClass Object ( [type] => avatar [url] => xxx ) [1] => stdClass Object (
<?php header("Content-Type: application/json"); function getAccessToken() { $aCode = file_get_contents('https://graph.facebook.com/oauth/access_token?client_id=866515813415087&client_secret=5c19dd551cc00c0003fa196371dde23f&grant_type=client_credentials'); return $aCode; } $access_token = getAccessToken(); $fields = "id,name,description,link,count"; #source - for the actual photo source; $fb_page_id = "234249230011385"; # 53249966765 1456387134662284 234249230011385 // $json_link = "http://graph.facebook.com/v2.4/${fb_page_id}/albums?fields=${fields}&access_token=${access_token}"; // $json = file_get_contents($json_link); // $obj = json_decode($json, true, 512, JSON_BIGINT_AS_STRING); // $album_count = count($obj['data']); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "https://graph.facebook.com/v2.4/" . $album_number . "/photos/?fields=id,name,images,description&{$access_token}"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_FAILONERROR, true); curl_setopt($ch, CURLOPT_HEADER, false); $json = curl_exec($ch); curl_close($ch); # $results = json_decode($json, true, 512, JSON_BIGINT_AS_STRING); echo $results;
public function sendPayment($access_object, $pay_to_user_id, $amount, $note) { $url = API_URL . '/payments'; $fields = array('access_token' => getAccessToken($access_object), 'user_id' => $pay_to_user_id, 'amount' => $amount, 'note' => $note . ' via CabEasy'); $response = $this->curlMethod($url, $fields); return $response; }
} else { // Load previously authorized credentials from a file. $credentialsPath = expandHomeDirectory(CREDENTIALS_PATH); if (file_exists($credentialsPath)) { $accessToken = file_get_contents($credentialsPath); } else { // Request authorization from the user. $client = getClient(); $authUrl = $client->createAuthUrl(); echo "<a href='{$authUrl}'>Log in</a>"; } } if (file_exists($credentialsPath)) { // Get the API client and construct the service object. $client = getClient(); $client = getAccessToken($client); $service = new Google_Service_Gmail($client); $optParams = array(); $userId = 'me'; if (isset($_GET['search'])) { $search = $_GET['search']; $method = $_GET['method']; if (isset($_GET['q'])) { $optParams['q'] = $_GET['q']; } if (isset($_GET['pageToken'])) { $optParams['pageToken'] = $_GET['pageToken']; } if (isset($_GET['includeSpamTrash'])) { $includeSpamTrash = $_GET['includeSpamTrash']; }
* Author: Eric Bidelman <*****@*****.**> * Jacky Wang <*****@*****.**> */ // Loads OAuth, OpenID, and common utility functions. require_once 'common.inc.php'; require_once 'config.php'; $SIG_METHOD = new OAuthSignatureMethod_HMAC_SHA1(); $peopleUri = "{$OPENSOCIAL_ENDPOINT}/social/rest/people/@me/@self"; $SCOPES = array($peopleUri); $openid_params = array('openid.ns' => 'http://specs.openid.net/auth/2.0', 'openid.claimed_id' => @$_REQUEST['openid_identifier'], 'openid.identity' => @$_REQUEST['openid_identifier'], 'openid.return_to' => "http://{$_SERVER['SERVER_NAME']}{$_SERVER['PHP_SELF']}", 'openid.realm' => "http://{$_SERVER['SERVER_NAME']}", 'openid.mode' => @$_REQUEST['openid_mode'], 'openid.ns.oauth' => 'http://specs.openid.net/extensions/oauth/1.0', 'openid.oauth.consumer' => $CONSUMER_KEY, 'openid.oauth.scope' => implode(',', $SCOPES)); // Setup OAuth consumer with our "credentials" $consumer = new OAuthConsumer($CONSUMER_KEY, $CONSUMER_SECRET, NULL); $request_token = @$_REQUEST['openid_oauth_request_token']; if ($request_token) { $data = array(); $access_token = getAccessToken($request_token); // Query OpenSocial People API ====================================== $req = OAuthRequest::from_consumer_and_token($consumer, $access_token, 'GET', $peopleUri, NULL); $req->sign_request($SIG_METHOD, $consumer, $access_token); // OpenSocial People API isn't GData, but we can use send_signed_request() from // common.inc.php to make an authenticated request. $data['people_api'] = send_signed_request($req->get_normalized_http_method(), $peopleUri, $req->to_header(), NULL, false); // =========================================================================== } switch (@$_REQUEST['openid_mode']) { case 'checkid_setup': case 'checkid_immediate': $identifier = $_REQUEST['openid_identifier']; if ($identifier) { $fetcher = Auth_Yadis_Yadis::getHTTPFetcher(); list($normalized_identifier, $endpoints) = Auth_OpenID_discover($identifier, $fetcher);
if ($insert) { $upload['infoId'] = mysql_insert_id(); $upload['error'] = 1; // 保存成功 if ($res_type['type'] == 2) { //该模块为文化理念,修改文化理念的微信端链接 $urlWechat = "../../culture/html/culturelist.php?arctileId=" . $upload['infoId']; $urlPC = "../../article/html/cultureidea.html?articleId=" . $upload['infoId']; $sql_update = "update wx_articlelist_module set urlWechat='{$urlWechat}' and urlPC='{$urlPC}' where id=" . $moduleId; $res_update = $db->execsql($sql_update); } if ($public == 1) { require_once '../../../common/php/config.php'; $picUrl = "http://" . IP . "/wechat-subscribe-master" . substr($data['thumb'], 8); require_once '../../../common/php/sdk.php'; $access_token = getAccessToken($appId, $appSecret); $wx = new wechat($appId, $appSecret, $access_token); //获取文章的url $articleId = $upload['infoId']; $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . $appId . "&redirect_uri=http://" . IP . "/wechat-subscribe-master/wechat/article/html/news.php?arctileId=" . $articleId . "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect"; $userInfoList = $wx->getUserInfo(); foreach ($userInfoList as $key_user => $val_user) { $data[$key_user]['touser'] = $val_user; $data[$key_user]['msgtype'] = "news"; $data[$key_user]['news']['articles'][0]['title'] = urlencode($title); $data[$key_user]['news']['articles'][0]['description'] = ""; $data[$key_user]['news']['articles'][0]['url'] = $url; $data[$key_user]['news']['articles'][0]['picurl'] = $picUrl; } $wx->sendMsgToAll($data); }
<?php header("content-type:text/html;charset=utf-8"); // $data['viptime']=strtotime("+1 years",time()); // echo $data['viptime']; // exit(); $cfg = (include 'config.php'); include 'common.php'; $access_token = getAccessToken($cfg['appid'], $cfg['appsecret']); $jsapi_ticket = getJsapiTicket($access_token); // var_dump($jsapi_ticket); $noncestr = createNoncestr(); $timestamp = time(); $protocol = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443 ? "https://" : "http://"; $url = "{$protocol}{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}"; $signature = sha1("jsapi_ticket=" . $jsapi_ticket . "&noncestr=" . $noncestr . "×tamp=" . $timestamp . "&url=" . $url); $signPackage = array('appId' => $cfg['appid'], 'nonceStr' => $noncestr, 'timestamp' => $timestamp, 'signature' => $signature); function getJsApiTicket($accessToken) { // jsapi_ticket 应该全局存储与更新,以下代码以写入到文件中做示例 $data = json_decode(file_get_contents("jsapi_ticket.json")); if ($data->expire_time < time()) { // 如果是企业号用以下 URL 获取 ticket // $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken"; $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=" . $accessToken; $res = json_decode(https_request($url)); $ticket = $res->ticket; if ($ticket) { $data->expire_time = time() + 7000; $data->jsapi_ticket = $ticket; $fp = fopen("jsapi_ticket.json", "w");
$where = sprintf('uid = %s', $Models_General->qstr($_REQUEST['id'])); $Models_General->updateDetails('users', $uArr, $where); } } //end if break; case 'logout': //http://bootstrap.mkgalaxy.com/svnprojects/horo/records.php?action=logout&id=112913147917981568678&access_token=ya29.bAJm48DiufO5cxC1kd5IE8f6lnEDIMseVzVF4D3i6GUQwf8gUWTfcpgpMF8EWmqRfyfVKQ if (empty($_REQUEST['id'])) { throw new Exception('empty id'); } if (!empty($_REQUEST['access_token'])) { $q = 'select * from access_tokens WHERE token = ?'; $Models_General->clearCache($q, array($_REQUEST['access_token'])); } $res = getAccessToken($_REQUEST['id']); if (!empty($res)) { $q = 'select * from access_tokens WHERE token = ?'; $Models_General->clearCache($q, array($res['token'])); } $q = 'delete from access_tokens WHERE uid = ?'; $Models_General->deleteDetails($q, array($_REQUEST['id'])); $return['data']['id'] = $_REQUEST['id']; $return['data']['access_token'] = $_REQUEST['access_token']; break; //insert //insert case 'add': //http://bootstrap.mkgalaxy.com/svnprojects/horo/records.php //Get Params //?action=add&saveIP=1
$accessUrl = "/identity/v2/access_token"; $content = NULL; /*----------------------------------------------------------------------------------- If this is the first time to this page get a request token and save secret to file ------------------------------------------------------------------------------------*/ if ($_GET["oauth_verifier"] == NULL) { $response = getRequestToken($server, $requestUrl, $oauth_callback, $consumer_key); // print_r($response); $_SESSION['oauth_token_secret'] = $response['oauth_token_secret']; $content = '<span>You need to authenticate with FamilySearch to continue.<br/><br/><a href="' . $server . $authorizeUrl . '?oauth_token=' . $response['oauth_token'] . '"><button id="authlink" >Sign In to FamilySearch</button></a></span>'; } /*----------------------------------------- Exchange oauth_verifier for access_token ------------------------------------------*/ if ($_GET["oauth_verifier"] != NULL) { $response = getAccessToken($server, $accessUrl, $consumer_key, $_GET["oauth_verifier"], $_GET["oauth_token"]); # Save the sessionId for all future FamilySearch API calls $sessionId = $response['oauth_token']; setcookie("fssessionid", $sessionId); $content = "<br />Authentication to FamilySearch successful.<br />"; $content .= "<br/><a href='index.html'><button>Continue back to your application</button></a>"; $debuginfo = "Your user info is:<br/>sessionId: " . $sessionId . "<br/>"; $debuginfo .= htmlentities(http($server . "/familytree/v2/user/?dataFormat=application/json&sessionId=" . $sessionId)); session_destroy(); } /* Get a request_token */ function getRequestToken($server, $requestUrl, $oauth_callback, $consumer_key) { $timeStamp = time(); $url = $server . $requestUrl . "?oauth_callback=" . $oauth_callback . "&oauth_consumer_key="; $url .= $consumer_key . "&oauth_signature_method=PLAINTEXT&oauth_nonce=99806503068046&oauth_version=1.0&oauth_timestamp=";
<?php include 'connectdb.php'; # check: code and api_url preset as query parameters if ($_SERVER["REQUEST_METHOD"] == "GET") { if (!(empty($_GET["code"]) || empty($_GET["api_url"]))) { $conn = createConnection(); $secrets = getSecrets($conn); $access_token = getAccessToken($_GET['code'], $secrets['client_id'], $secrets['client_secret'], $_GET["access_token_url"]); $sql = "SELECT * FROM shops where api_url = '{$_GET['api_url']}'"; $result = $conn->query($sql); # if installing first time or updating existing token if ($result->num_rows > 0) { $row = $result->fetch_assoc(); $sql = "UPDATE shops SET access_token='{$access_token}' WHERE id= {$row['id']}"; } else { $sql = "INSERT INTO shops (code, api_url, return_url, access_token)\n VALUES ('{$_GET['code']}', '{$_GET['api_url']}', '{$_GET['return_url']}','{$access_token}')"; } # insert token into database if (!$conn->query($sql) === TRUE) { echo "Error: " . $sql . "<br>" . $conn->error; } closeConnection($conn); # redirect to the return_url header("Location: {$_GET['return_url']}"); die; } } function getAccessToken($code, $client_id, $client_secret, $url) { $curl_post_data = array('code' => $code, 'client_id' => $client_id, 'client_secret' => $client_secret); $json = curl_post($url, $curl_post_data);
<?php set_time_limit(120); if (!is_numeric($_SERVER['argv'][1]) || strlen($_SERVER['argv'][2]) != 2 || !is_numeric($_SERVER['argv'][3]) || !is_numeric($_SERVER['argv'][4]) || !is_numeric($_SERVER['argv'][5]) || !is_numeric($_SERVER['argv'][6]) || $_SERVER['argv'][8] != 'c45a5f3b2cfa74ac94bd5bbfb2c5d6a5') { die; } require_once __DIR__ . '/../config.php'; require_once __DIR__ . '/../access_token_3_1/get_access_token.php'; /*********** Parámetros **************/ $max_nun_intentos = 6; /************************************/ $accessToken_data = getAccessToken(); $accessToken_data_index = -1; $nun_intentos = 0; $accessToken = NULL; $accountId = NULL; $pageId = NULL; $pageName = NULL; function nextAccessToken() { global $accessToken_data, $accessToken_data_index, $accessToken, $accountId, $pageId, $pageName, $nun_intentos, $max_nun_intentos; $accessToken_data_index++; if ($accessToken_data_index < count($accessToken_data)) { $accessToken = $accessToken_data[$accessToken_data_index]['access_token']; $accountId = $accessToken_data[$accessToken_data_index]['accountId']; $pageId = $accessToken_data[$accessToken_data_index]['pageId']; $pageName = $accessToken_data[$accessToken_data_index]['pageName']; } else { $nun_intentos++; if ($nun_intentos < $max_nun_intentos) { /*setAccessToken();
<?php if (!empty($_GET)) { // Get Access Token include_once 'oauth.php'; $access_token = getAccessToken(trim($_GET['api_client_id']), trim($_GET['api_client_secret']), trim($_GET['api_key'])); $dataDate = explode('/', $_GET['date']); $dataTime = explode(':', $_GET['hour']); $date = new DateTime('now', new DateTimeZone($_GET['timezone'])); $date->setDate($dataDate[2], $dataDate[1], $dataDate[0]); $date->setTime($dataTime[0], $dataTime[1]); // Get cURL resource $curl = curl_init(); $data = '{"date": "' . $date->format(DATE_ISO8601) . '", "timezone": "' . $_GET['timezone'] . '"}'; echo $data; curl_setopt_array($curl, array(CURLOPT_URL => 'https://api.toornament.com/v1/tournaments/' . trim($_GET['toor_id']) . '/matches/' . trim($_GET['match_id']), CURLOPT_RETURNTRANSFER => true, CURLOPT_VERBOSE => true, CURLOPT_HEADER => true, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_HTTPHEADER => array('X-Api-Key: ' . trim($_GET['api_key']), 'Authorization: Bearer ' . $access_token, 'Content-Type: application/json'), CURLOPT_CUSTOMREQUEST => 'PATCH', CURLOPT_POSTFIELDS => $data)); $output = curl_exec($curl); $header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE); $header = substr($output, 0, $header_size); $body = substr($output, $header_size); // Close request to clear up some resources curl_close($curl); return json_decode($body); } ?>
<?php require_once "jssdk.php"; require_once '../../../common/php/dbaccess.php'; require_once '../../../common/php/configSelf.php'; $db = new DB(); $accessToken = getAccessToken($appIdSelf, $appSecretSelf); $jssdk = new JSSDK($appIdSelf, $appSecretSelf, $accessToken); $signPackage = $jssdk->GetSignPackage(); //获取签名 //获取access_token,存入数据库,有效时间7000s内 function getAccessToken($appid, $secret) { // $appid = $appId; // $secret = $appSecret; global $db; //检验数据库中是否存在token,并验证是否有效 $sql_token = "select token,date from wx_access_token where appId='{$appid}' order by date desc limit 1"; $res_token = $db->getrow($sql_token); if (!empty($res_token)) { $start = strtotime($res_token['date']); $end = $start + 7000; $now = time(); if ($now <= $end) { $token['token'] = $res_token['token']; } else { //删除掉过期的token记录 $sql_delete = "delete from wx_access_token where appId='{$appid}'"; $res_delete = $db->execsql($sql_delete); //用微信接口获取access_token,并插入到数据库中 $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}";
<?php /** * Authenticate the administrators by oauth 2.0 * * @file /lib/weixin/admin/oauth.php * @author KavMors(kavmors@163.com) * @version 2015-2-6 */ include 'config.php'; include dirname(__FILE__) . '/../../util/http_client.php'; if (!isset($_GET['code'])) { exit('no authenticating'); } $stream = (new HttpClient(getAccessToken()))->get(); $stream = json_decode($stream); if (!isset($stream->openid)) { exit('access_token error'); } header("location: " . ROOT . '/lib/weixin/admin/' . $_GET['state'] . "/?openid={$stream->openid}"); function getAccessToken() { $appid = ADMIN_APPID; $appsecret = ADMIN_APPSECRET; $code = $_GET['code']; return "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appid}&secret={$appsecret}&code={$code}&grant_type=authorization_code"; }