公衆號技術標籤
小程序
PHP
源碼
項目
php
ThinkPHP5.0目錄結構,新建一個模塊api,該模塊下面有controller、model 目錄,前者放控制器,寫API接口(這裏是簡單的api寫法)。後者是模型,進行數據庫處理。咱們先說一下數據庫的搭建。html
數據庫名稱:ziliao數據庫
表前綴:ziliao_編程
須要在ThinkPHP數據庫配置裏面填寫相應的數據庫信息json
下面是目錄結構圖小程序
SQL(表ziliao_user)api
CREATE TABLE `ziliao_user` (`id` int(6) NOT NULL AUTO_INCREMENT COMMENT 'id',`openid` varchar(100) DEFAULT NULL COMMENT '小程序openid',`nickname` varchar(50) DEFAULT NULL COMMENT '微信名稱',`sex` tinyint(1) DEFAULT NULL COMMENT '性別:1男0女',`image` varchar(255) DEFAULT NULL COMMENT '頭像',`jifen` int(6) DEFAULT NULL COMMENT '積分',`create_time` int(11) DEFAULT NULL COMMENT '加入時間',PRIMARY KEY (`id`)) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
Common控制器(獲取openid和access_token等公共類)微信
<?php namespace app\api\controller;use think\Controller;/** * 用戶類 */class Common extends Controller{private $appid = '你小程序的appid';private $secret = 'xxxxxx';//獲取openidpublic function getOpenid() {$code = input('code');//小程序傳來的code值 $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$this->appid.'&secret='.$this->secret.'&js_code='.$code.'&grant_type=authorization_code'; //yourAppid爲開發者appid.appSecret爲開發者的appsecret,均可以從微信公衆平臺獲取; $info = file_get_contents($url);//發送HTTPs請求並獲取返回的數據,推薦使用curl return json(['code'=>200,'msg'=>'獲取openid成功','data'=>$info]);}//獲取// getAccessToken.phppublic function getAccessToken () { $url='https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->$this->secret.'&secret='.$appsecret;$html = file_get_contents($url);$output = json_decode($html, true);$access_token = $output['access_token'];return $access_token;}}?>
User控制器(進行有關於用戶的接口)session
<?php namespace app\api\controller;use think\Controller;/** * 用戶類 */class User extends Controller{private $resp = ['code'=>-100,'msg'=>''];//首次受權登陸插入用戶數據public function insert_user( ) {$data = input();$model = model('User');if (empty($model->user_is_exit($data['openid']))) {$data['jifen'] = 20;//新用戶積分20$data['create_time'] = time();$result = $model->frist_insert_user($data);if ($result) {$this->resp['code'] = 200;$this->resp['msg'] = '新用戶插入成功';$this->resp['status'] = true;}else{$this->resp['msg'] = '新用戶插入失敗';$this->resp['status'] = false;}}else{$this->resp['code'] = 200;$this->resp['msg'] = '該用戶已存在';$this->resp['status'] = 'exit';}return json($this->resp);}}?>
User模型app
<?php namespace app\api\model;use think\Model;/** * User */class User extends Model{//判斷用戶是否存在public function user_is_exit($openid) {$is_exit = db('user')->where('openid',$openid)->find();return $is_exit;}//插入數據庫public function frist_insert_user($where) {$res = db('user')->data($where)->insert();return $res;}}?>
若是推送的文章中,你們承認的,別忘了轉發分享;
爲了你們更好的長久查看源碼及講解,閱讀後能夠收藏
長按下圖二維碼,與小編攜手編程之美