最近一个朋友找我开发微信公众号发送红包的功能。
首先我以前没做过微信接口方面的开发,但做过别的第三方开发啊。通过查看api文档,终于成功完成。在此说下完成的思路,并公布部分代码。
首先打开链接时候,要得到用户的唯一标识(open_id)。先授权,点击授权,进入到微信支付后台填写的回调页面,取出code,通过code可以得到openid,有了openid可以得到昵称,头像等等。
根据得到的openid让微信公众号给该openid的用户发红包。
为了避免重复发红包,把openid存到数据库中,每次都检查是否已经发过红包。
下面公布部分代码
//跳转到授权页面
$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->app_id}&redirect_uri={$redirect_uri}&response_type=code&scope=snsapi_userinfo&state={$state}#wechat_redirect";
header("Location:".$url);
//得到code
$code = $_GET['code'];
//得到用户详细信息
if (empty($code)) $this->error('授权失败');
$token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$appsecret.'&code='.$code.'&grant_type=authorization_code';
$token = json_decode(file_get_contents($token_url));
if (isset($token->errcode)) {
echo '<h1>错误:</h1>'.$token->errcode;
echo '<br/><h2>错误信息:</h2>'.$token->errmsg;
exit;
}
$access_token_url = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid='.$appid.'&grant_type=refresh_token&refresh_token='.$token->refresh_token;
//转成对象
$access_token = json_decode(file_get_contents($access_token_url));
if (isset($access_token->errcode)) {
echo '<h1>错误:</h1>'.$access_token->errcode;
echo '<br/><h2>错误信息:</h2>'.$access_token->errmsg;
exit;
}
$user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token->access_token.'&openid='.$access_token->openid.'&lang=zh_CN';
//转成对象
$user_info = json_decode(file_get_contents($user_info_url));
if (isset($user_info->errcode)) {
echo '<h1>错误:</h1>'.$user_info->errcode;
echo '<br/><h2>错误信息:</h2>'.$user_info->errmsg;
exit;
}
$openid = $user_info->openid;
print_r($user_info);
然后判断$openid在数据库中是否已经存在,存在则不调发红包的接口,若不存在则存入数据库,并调用发红包的接口。
希望大家多多交流。qq:274501366
qq群:461195643