微信小程序云开发开放了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如下:
<?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;
}
?>