微信开发获取openID与发送客服消息

public function getOpenid($appid, $appsecret){

	$SERVER_NAME = $_SERVER['SERVER_NAME'];
	$REQUEST_URI = $_SERVER['REQUEST_URI'];
	$redirect_uri = urlencode('http://' . $SERVER_NAME . $REQUEST_URI);
	$code = $_GET['code'];
	if (! $code) {
		// 网页授权当scope=snsapi_userinfo时才会提示是否授权应用
		$autourl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=".$redirect_uri."&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";
		header("location:$autourl");
	} else {
		// 获取openid
		$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$appsecret."&code=$code&grant_type=authorization_code";
		$row = $this->posturl($url);
		return ($row['openid']);
	}
}

public function posturl($url){
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	$output = curl_exec($ch);
	curl_close($ch);
	$jsoninfo = json_decode($output, true);
	return $jsoninfo;
}    

public function https_postMessage($url,$data){
	$curl = curl_init();
	curl_setopt($curl, CURLOPT_URL, $url); 
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
	curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
	curl_setopt($curl, CURLOPT_POST, 1);
	curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
	$result = curl_exec($curl);
	if (curl_errno($curl)) {
	   return 'Errno'.curl_error($curl);
	}
	curl_close($curl);
	return $result;
}

//发送客服消息
public function send_message($info){

	$appid = "xxxxxx";
	$secret = "xxxxxxxxxxxx";
	$openid= $this->getOpenid($appid, $secret);

	$access_token = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret;
	$access_msg = json_decode(file_get_contents($access_token));
	$token = $access_msg->access_token;

	//判断是否关注
	// $subscribe_msg = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$token."&openid=".$openid;
	// $subscribe = json_decode(file_get_contents($subscribe_msg));
	// $gzxx = $subscribe->subscribe;

	$url            = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$token;

	$content 		='您好,'.$info['name'].'恭喜您报名成功!';
	$message        =  '{
		"touser":"'.$openid.'",
		"msgtype":"text",
		"text":
		{
			 "content":"'.$content.'"
		}
	}';

	$token_info  = $this->https_postMessage($url,$message);

	$final = json_decode($token_info);

	return $final;
	
}

你可能感兴趣的:(微信开发)