1、
//获取token值存入文件
$appid = '写入自己的公众号的appid'; $app_secret = '写入自己的公众号的appsecret'; $menu_url=__DIR__.'/menu.txt'; if(!file_exists($menu_url) || time() - filemtime( $menu_url ) > 7100){ //获取token值 $token_url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$app_secret; $token_json=file_get_contents( $token_url ); $token_data=json_decode($token_json,true); if(!empty($token_data['access_token'])){ $a=file_put_contents($menu_url ,$token_data['access_token']); } $token = $token_data['access_token']; }else{ $token = file_get_contents($menu_url); }
2、
定义json串例如
$param_str='{ "button":[ { "type":"click", "name":"今日歌曲", "key":"V1001_TODAY_MUSIC" }, { "name":"乐柠教育", "sub_button":[ { "type":"view", "name":"百度一下,你就知道", "url":"http://www.baidu.com/" }, { "type":"view", "name":"赞一下我们", "url":"http://132.232.17.237/" }] }] }';
3、用一个函数来对微信服务器进行请求
function CurlPost($url, $param = [], $is_post = 1, $timeout = 5 ) { //初始化curl $curl = curl_init(); // 设置请求的路径 curl_setopt($curl, CURLOPT_URL, $url); if( $is_post == 1 ){ //设置POST提交 curl_setopt($curl, CURLOPT_POST, 0 ); } //显示输出结果 1代表 把接口返回的结果当作一个字符串处理 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 设置请求超时时间 curl_setopt($curl, CURLOPT_TIMEOUT, $timeout); curl_setopt( $curl ,CURLOPT_SSL_VERIFYHOST , false ); curl_setopt( $curl ,CURLOPT_SSL_VERIFYPEER , false ); if( $is_post == 1 ){ //提交数据 -- 设置post提交的数据 if (is_array($param)) { //http_build_query curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($param)); } else { curl_setopt($curl, CURLOPT_POSTFIELDS, $param); } } //执行请求 $data = $data_str = curl_exec($curl); //处理错误 if ($error = curl_error($curl)) { $log_data = array( 'url' => $url, 'param' => $param, 'error' => '<span style="color:red;font-weight: bold">' . $error . '</span>', ); var_dump($log_data); exit; } # 关闭CURL curl_close($curl); //json数据转换为数组 $data = json_decode($data, true); if (!is_array($data)) { $data = $data_str; } #调用玩接口之后写一个日志 $log = [ 'url' => $url , 'param' => $param , 'response' => $data_str ]; file_put_contents( __DIR__.'/wechat.log' , print_r( $log , true ) , 8 ); return $data;
}
4、调用的时候可能报错因为json串的原因
$param_str = rtrim($param_str);去掉最右边的多余部分就行了