php访问微信云数据库,第三方服务器php获取微信小程序云开发access_token和云数据库...
微信小程序云開發開放了http api,可以從第三方訪問云服務了。方便很多。云服務的后臺,可以用PC端寫了。
流程大概就是通過appid,appkey獲得access_token,這個access_token一定要在有效期內自己備份,不要每次使用都去申請,因為企鵝那邊永遠是是你的appid申請的最后一次的access_token有效。多此申請可能造成前面業務失敗。我這里用redis存儲申請到的access_token,正好還可以設置超時時間。
獲取access_token的鏈接如下:
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".APPID."&secret=".APPKEY;
獲取access_token后,可以用云環境ID訪問自己小程序中的云資源了。比如查詢云數據庫:
$url = "https://api.weixin.qq.com/tcb/databasequery?access_token=".$at;
$data = array ('env' => APPCLOUDID,'query'=>'db.collection("member").where({"comp.review":1}).get()');
$data = json_encode($data);
$opts = array (
'http' => array (
'method' => 'POST',
'header'=> "Content-type: application/jsonrn",
"Content-Length: " . strlen($data) . "rn",
'content' => $data
)
);
$context = stream_context_create($opts);
$html = file_get_contents($url, false, $context);
//var_dump($html);
$arr["data"] = $html;
下面是完整的php代碼。
minip.php如下:
require_once(dirname(__FILE__).'/../../config.php');
$minip_actions = array(
'comp-review-get' => function($param,&$arr,$token,$at){
$arr["status"] = 0;
$arr["msg"] = "callminip";
compreviewget($param,$arr,$token,$at);
},
);
function compreviewget ($param,&$arr,$token,$at){
$url = "https://api.weixin.qq.com/tcb/databasequery?access_token=".$at;
$data = array ('env' => APPCLOUDID,'query'=>'db.collection("member").where({"comp.review":1}).get()');
$data = json_encode($data);
$opts = array (
'http' => array (
'method' => 'POST',
'header'=> "Content-type: application/jsonrn",
"Content-Length: " . strlen($data) . "rn",
'content' => $data
)
);
$context = stream_context_create($opts);
$html = file_get_contents($url, false, $context);
//var_dump($html);
$arr["data"] = $html;
}
function callMiniP($param,&$arr,$token){
global $minip_actions;
$redis = new Redis();
$redis->connect(DB_REDIS_IP, 6379);
$redis->auth(DB_REDIS_PWD);
$key = '6Xdd55klotnbpo98_minip_access_token';
$ui = $redis->get($key);
$from = '';
if($ui==False){/// access_token已經失效。需要重新申請。
do{
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".APPID."&secret=".APPKEY;
$j =json_decode( file_get_contents($url),false);//true,轉化成數組
if(property_exists($j, 'errcode')){
if($j->errcode == -1){
continue;
}else if($j->errcode > 0){
break;
}
}
$redis->select(0);
$count = 0;
$redis->set($key, serialize($j), ['nx', 'ex'=>$j->expires_in]);
$ui0 = $j;
$from = "QQ";
break;
}while(true);
}else{
$ui0 = unserialize($ui);
$from = "local";
}
if(!property_exists($ui0, 'access_token')){
return;
}
$action = $param["action"];
$arr["msg"] = "1未知action: ".$action;
if(!array_key_exists($action,$minip_actions)){
return;
}
$func = $minip_actions[$action];
$func($param,$arr,$token,$ui0->access_token);
return;
}
?>
總結
以上是生活随笔為你收集整理的php访问微信云数据库,第三方服务器php获取微信小程序云开发access_token和云数据库...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ORACLE对表批处理操作
- 下一篇: 海底捞和饿了么合作了,你会来一份“火锅外