框架环境:tp5
access_token.php
jsapi_ticket.php
放到public
然后jsapi_ticket.php放到extend目录
/**
* 获取公众号信息
*/
public function wx_public_info() {
$yourAppID = Config::get("site.wx_public_AppID");
$yourAppSecret = Config::get("site.wx_public_AppSecret");
import('lib.wx_public.jssdk', EXTEND_PATH , '.php');
$jssdk = new \JSSDK($yourAppID, $yourAppSecret);
$signPackage = $jssdk->GetSignPackage();
$this->success("ok", $signPackage );
}
如果对象报错,修改jssdk.php
private function httpGet($url) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 500);
// 为保证第三方服务器与微信服务器之间数据传输的安全性,所有微信接口采用https方式调用,必须使用下面2行代码打开ssl安全校验。
// 如果在部署过程中代码在此处验证失败,请到 http://curl.haxx.se/ca/cacert.pem 下载新的证书判别文件。
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
// curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
// curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true);
curl_setopt($curl, CURLOPT_URL, $url);
$res = curl_exec($curl);
curl_close($curl);
return $res;
}
<?php
/**
* 获取微信用户信息
* 第一步:判断有没有code,有code去第三步,没有code去第二步
* 第二步:用户同意授权,获取code
* 第三步:通过code换取网页授权access_token
* 第四步:使用access_token获取用户信息
*/
namespace app\api\controller;
use app\common\controller\Api;
use think\Db;
use think\Config;
use app\common\library\Sms;
class Wexin extends Api
{
protected $noNeedLogin = ['*'];
protected $noNeedRight = ['*'];
public $appid = '';
public $appsecret = '';
public $api_url = '';
public $id = '';
public function _initialize() {
parent::_initialize();
$this->appid = Config::get('site.wx_public_AppID');
$this->appsecret = Config::get('site.wx_public_AppSecret');
}
/**
* 1、获取微信用户信息,判断有没有code,有使用code换取access_token,没有去获取code。
* @return array 微信用户信息数组
*/
public function get_user_all()
{
$code = $this->request->request("code",'');
$state = $this->request->request("state",'');
$callback = $this->request->request("url",'');
if (!$code) {//没有code,去微信接口获取code码
//微信服务器回调url,这里是本页url;注意::这里回调的url是http://www.xxxx.com/index.php。如果想要获取完整的路径用 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']
// $callback = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
$this->get_code( $callback , $state );
} else {
//获取code后跳转回来到这里了
$data = $this->get_access_token($code);//获取网页授权access_token和用户openid
$data_all = $this->get_user_info($data['access_token'], $data['openid']);//获取微信用户信息
$w = [];
$w['openid'] = array("eq",$data['openid']);
$user_info = Db::name("user")->field("id")->where( $w )->find();
// $this->success('ok', $data_all);
if( !$user_info ){
$this->success("ok",[
'type' => 1, // 未注册
'data' => $data_all
]);
}else{
$this->auth->public_login( $user_info['id'] ) ;
// echo '<pre>';print_r($data_all);die;
$this->success("ok",[
'type' => 2, // 已注册
'data' => $this->auth->getUserinfo()
]);
}
}
}
/**
* 2、用户授权并获取code
* @param string $callback 微信服务器回调链接url
*/
private function get_code( $callback , $state )
{
$appid = $this->appid;
$scope = 'snsapi_userinfo';
// $state = md5(uniqid(rand(), TRUE));//唯一ID标识符绝对不会重复
$url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $appid . '&redirect_uri=' . urlencode($callback) . '&response_type=code&scope=' . $scope . '&state=' . $state . '#wechat_redirect';
header("Location:$url");
}
/**
* 3、使用code换取access_token
* @param string 用于换取access_token的code,微信提供
* @return array access_token和用户openid数组
*/
private function get_access_token($code)
{
$appid = $this->appid;
$appsecret = $this->appsecret;
$url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appid . '&secret=' . $appsecret . '&code=' . $code . '&grant_type=authorization_code';
$user = json_decode(file_get_contents($url));
if (isset($user->errcode)) {
echo 'error:' . $user->errcode . '<hr>msg :' . $user->errmsg;
exit;
}
$data = json_decode(json_encode($user), true);//返回的json数组转换成array数组
return $data;
}
/**
* 4、使用access_token获取用户信息
* @param string access_token
* @param string 用户的openid
* @return array 用户信息数组
*/
private function get_user_info($access_token, $openid)
{
$url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $access_token . '&openid=' . $openid . '&lang=zh_CN';
$user = json_decode(file_get_contents($url));
if (isset($user->errcode)) {
echo 'error:' . $user->errcode . '<hr>msg :' . $user->errmsg;
exit;
}
$data = json_decode(json_encode($user), true);//返回的json数组转换成array数组
return $data;
}
/*
* 微信注册
*/
public function wx_register() {
$password = $this->request->request('password');
$mobile = $this->request->request('mobile');
$openid = $this->request->request('openid');
$reffer_code = $this->request->request('reffer_code');
$captcha = $this->request->request('captcha');
$pay_password = $this->request->request('pay_password');
$longitude = $this->request->request('longitude');
$latitude = $this->request->request('latitude');
// var_dump( $this->request->request() );die;
if ( strlen($password)>16 || strlen($password)<8 ) {
$this->error("请输入8-16位密码");
}
if( !$reffer_code ){
$this->error("请输入邀请码");
}
$check_pwd = controller("common")->check_transaction_code( $pay_password );
if( !$check_pwd ){
$this->error( "请输入六位数字" );
}
$encryption_pwd = controller("common")->encrypt_transaction_code( $pay_password );
$w = [];
$w['reffer_code'] = array("eq",$reffer_code);
$p_info = Db::name("user")->field("id,pid")->where( $w )->find();
if( !$p_info ){
$this->error("邀请码不存在");
}
if (!Sms::check($mobile, $captcha, 'register')) {
$this->error( "验证码不正确" );
}
$my_reffer_code = $this->create_reffer_code();
$extend['reffer_code'] = $my_reffer_code;
$extend['nickname'] = $mobile;
$extend['openid'] = $openid;
$extend['pay_pwd'] = $pay_password;
$extend['pid'] = $p_info['id'];
$extend['p_pid'] = $p_info['pid'];
$extend['pay_pwd'] = $encryption_pwd;
if( $latitude && $longitude ){
$address_ = [];
$baidu_key = Config::get('site.baidu_key');
$address_ = getCityName($baidu_key, $latitude, $longitude);
if( $address_ ){
$extend['province'] = $address_['province'];
$extend['city'] = $address_['city'];
$extend['area'] = $address_['district'];
}
}
$ret = $this->auth->wx_public_register($mobile, $password, $mobile, $extend);
if ($ret) {
$data = ['userinfo' => $this->auth->getUserinfo()];
$this->success("注册成功", $data);
} else {
$this->error($this->auth->getError());
}
}
/**
* 生成邀请码
*/
public function create_reffer_code() {
$d = substr(base_convert(md5(uniqid(md5(microtime(true)),true)), 16, 10), 0, 6);
$w['reffer_code'] = array('eq', $d);
$user_info = Db::name('user')->field("id")->where($w)->find();
if ($user_info) {
$this->create_invite_code();
}
return $d;
}
}