微信网页授权Oauth2.0 某高校合唱团报名表单

9 篇文章 2 订阅
7 篇文章 0 订阅

首先在Application/Weih5/gkchorus目录新建一个Oauth2.0授权登录页面gkchorus_oauth2.php

<meta charset="utf-8">
<?php
	// error_reporting(0);
	// $get_openid=$_GET['state'];
	$appid = '微信公众号appid';// 微信公众号appid
	$REDIRECT_URI = 'http://你的域名/index.php/Home/Gkchorus/gkchorus';
	
	// $SCOPE = 'snsapi_base';
	$SCOPE = 'snsapi_userinfo';
	// 
	$uri = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'&redirect_uri='.$REDIRECT_URI.'&response_type=code&scope='.$SCOPE.'&state=1314#wechat_redirect';
	header("Location:$uri");
?>

前面CommonController.class.php控制器中已经获取到了access_token和jsapi_ticket,新建GkchorusController.class.php

<?php
    namespace Home\Controller;

    Class GkchorusController extends CommonController{
	public function gkchorus(){
	    $this->display();
	}

	public function enrol(){
	    $data['nickname'] = I('post.nickname');
            $data['name'] = I('post.name');
            $data['dept'] = I('post.dept');
            $data['phone'] = I('post.phone');
            $data['chorus'] = I('post.chorus');
            $data['create'] = date("Y-m-d H:i:s");
             // dump($data);

        	if ($data!=''&&$data!=null) {
        		$db=M('enrol');
	        	$db->create();
	        	$rs = $db->add($data);
	        	if($rs){
	                print("
	                	<meta charset='utf-8'>
	                	<script src='https://res.wx.qq.com/open/libs/weuijs/1.0.0/weui.min.js'></script>
	                	<script src='http://res.wx.qq.com/open/js/jweixin-1.0.0.js'></script>
	                	<script>
	                        alert('".$data['name']." 同学,"."您已报名成功,期待你的加入!');
	                        setTimeout(function(){WeixinJSBridge.call('closeWindow');},200);
	                    </script>");
	            }
	            else{
					print("
						<meta charset='utf-8'>
						<script>
	                        alert('服务器繁忙,请重新报名!');
	                        window.history.back();
	                    </script>");
	            }
        	}
        }
    }

Application/Home/View/gkchorus目录新建一个模板,gkchorus.html模板

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=0">
    <link rel="stylesheet" href="__PUBLIC__/Weih5/gkchorus/main.css">
    <script src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
    <script src="https://res.wx.qq.com/open/libs/weuijs/1.0.0/weui.min.js"></script>
</head>
<body>
	<?php
		// 打开session
		// session_start();

		// 当用户授权登陆,openid出入session
		// if(!isset($_SESSION['openid'])){
			$code = $_GET['code'];	// 获取code
			// print_r($code);

			// curl请求,用于获取oauth2.0的access_token,微信openid等
			$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $appID . "&secret=" . $appSecret . "&code=" . $code . "&grant_type=authorization_code";

			// 获取oauth2.0的access_token,微信openid等
			$ch = curl_init($url); 
			curl_setopt($ch, CURLOPT_URL, $url);  
			curl_setopt($ch, CURLOPT_HEADER, 0);  			//不显示头部信息
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);// 这个是主要参数  
			$output = curl_exec($ch); 
			curl_close($ch);
			$jsoninfo = json_decode($output, true);
			$access_token = $jsoninfo["access_token"];		// oauth2的access_token
			$openid = $jsoninfo["openid"];					// openid

			// 当用户刷新页面,失去openid,跳转oauth2.php重新授权
			if (empty($openid)||$openid==null) {
				echo ("
					<script>
						window.location='http://你的域名/Weih5/gkchorus/gkchorus_oauth2.php';
					</script>
				");
			}

			// 将oauth2的access_token和openid,获取用户信息
			$url_info = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';

			$ch = curl_init($url_info); 
			curl_setopt($ch, CURLOPT_URL, $url_info);  
			curl_setopt($ch, CURLOPT_HEADER, 0);  			// 不显示头部信息
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);	// 这个是主要参数  
			$output_info = curl_exec($ch); 
			curl_close($ch);
			$jsonuser = json_decode($output_info, true);
			// var_dump($jsonuser);

	                // 存入数据库
	                $openid = $jsonuser['openid'];
    	                $nickname = $jsonuser['nickname'];
    	                $headimgurl = $jsonuser['headimgurl'];
		// }
	?>


  <div class="content_all">
    <div class="content_all_top">
      <div>
        <p><h2>广科合唱团报名</h2></p>
        <p><span>我们的梦想!在飞!在翱翔!</span></p>
      </div>
    </div>
    <div class="content_all_middle">
      <form name="chorusform" οnsubmit="return check()" action="{:U('Gkchorus/enrol')}" method="post">
    <?php 
      if ($nickname) {
      ?>
        <p><label>{$nickname}</label></p>
        <p><img src="{$headimgurl}" width="70" height="70"></p><br/>
      <?php 
      }
    ?>
        <p><input type="hidden" name="nickname" value="{$nickname}"></p>
        <p><label>姓名:<span>*</span></label></p>
        <p><input type="text" name="name" maxlength="10"></p><br/>
        <p><label>系别:<span>*</span></label></p>
        <p><input type="text" name="dept" maxlength="10"></p><br/>
        <p><label>手机:<span>*</span></label></p>
        <p><input type="number" name="phone" maxlength="11"></p><br/>
        <p><label>选择方向:<span>*</span></label></p>
        <p>
          <div class="radio" style="width: 85%!important;height: 100px;margin: auto;">
            <div><input type="radio" name="chorus" value="独唱歌手"/><span>独唱歌手</span></div>
            <div><input type="radio" name="chorus" value="钢琴伴奏"/><span>钢琴伴奏</span></div>
            <div><input type="radio" name="chorus" value="合唱团员"/><span>合唱团员</span></div>
          </div>
        </p>
        <div style="clear: both;"></div>
        <p><input class="submit" type="submit"></p>
      </form>
    </div>
    <div class="content_all_bottom">
      <p>By 广科合唱-Vegeta</p>
    </div>
  </div>
  

</body>
<script>
  /*
   * 注意:
   * 1. 所有的JS接口只能在公众号绑定的域名下调用,公众号开发者需要先登录微信公众平台进入“公众号设置”的“功能设置”里填写“JS接口安全域名”。
   * 2. 如果发现在 Android 不能分享自定义内容,请到官网下载最新的包覆盖安装,Android 自定义分享接口需升级至 6.0.2.58 版本及以上。
   * 3. 常见问题及完整 JS-SDK 文档地址:http://mp.weixin.qq.com/wiki/7/aaa137b55fb2e0456bf8dd9148dd613f.html
   *
   * 开发中遇到问题详见文档“附录5-常见错误及解决办法”解决,如仍未能解决可通过以下渠道反馈:
   * 邮箱地址:weixin-open@qq.com
   * 邮件主题:【微信JS-SDK反馈】具体问题
   * 邮件内容说明:用简明的语言描述问题所在,并交代清楚遇到该问题的场景,可附上截屏图片,微信团队会尽快处理你的反馈。
   */
  wx.config({
      debug: false,
      appId: '{$signPackage.appId}',
      timestamp: {$signPackage.timestamp},
      nonceStr: '{$signPackage.nonceStr}',
      signature: '{$signPackage.signature}',
      jsApiList:[
        'checkJsApi',
        'onMenuShareTimeline',
        'onMenuShareAppMessage',
        'onMenuShareQQ',
        'onMenuShareWeibo',
        'hideMenuItems',
        'showMenuItems',
        'hideAllNonBaseMenuItem',
        'showAllNonBaseMenuItem',
        'chooseImage',
        'previewImage',
        'uploadImage',
        'getNetworkType',
        'hideOptionMenu',
        'showOptionMenu']
  });

  wx.ready(function () {
    // config信息验证后会执行ready方法,所有接口调用都必须在config接口获得结果之后,config是一个客户端的异步操作,所以如果需要在页面加载时就调用相关接口,则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口,则可以直接调用,不需要放在ready函数中。
        
    // 注册分享朋友圈事件。
    wx.onMenuShareTimeline({
      title: '广科合唱团报名', // 分享标题
      link: 'http://你的域名/Weih5/gkchorus/gkchorus_oauth2.php', // 分享链接,该链接域名必须与当前企业的可信域名一致
      imgUrl: 'https://avatar.csdn.net/B/8/E/3_cai181191.jpg', // 分享图标
      success: function () {
          alert('success!');
      },
      cancel: function () {
          alert('cancel!');
      }
    });

	// 注册分享朋友事件
    wx.onMenuShareAppMessage({
      title: '广科合唱团报名', // 分享标题
      desc: '我们的梦想!在飞!在翱翔!',
      link: 'http://你的域名/Weih5/gkchorus/gkchorus_oauth2.php', // 分享链接,该链接域名必须与当前企业的可信域名一致
      imgUrl: 'https://avatar.csdn.net/B/8/E/3_cai181191.jpg', // 分享图标
      success: function () {
          alert('success!');
      },
      cancel: function () {
          alert('cancel!');
      }
    });
    

  });

  	wx.uploadImage({
	  localId: '', // 需要上传的图片的本地ID,由chooseImage接口获得
	  isShowProgressTips: 1, // 默认为1,显示进度提示
	  success: function (res) {
	    var serverId = res.serverId; // 返回图片的服务器端ID
	  }
	});

  wx.error(function(res){
      // config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名。
  });

</script>
<script type="text/javascript">
    function check(){
      var name = document.chorusform.name.value.trim();
      var dept = document.chorusform.dept.value.trim();
      var mobile = document.chorusform.phone.value.trim();
      var chorus = document.chorusform.chorus.value.trim();
      

      if(name == "") {
        alert("请输入姓名");
        document.chorusform.name.focus();
        return false;
      }  

      if(dept == "") {
        alert("请输入系别");
        document.chorusform.dept.focus();
        return false;
      }

      if(!(/^1[3|4|5|6|7|8|9][0-9]{9}$/.test(mobile))){
        alert("不是完整的11位手机号!");
        document.chorusform.phone.focus();
        return false;
      }

      if(chorus == "") {
        alert("请选择方向");
        return false;
      }

      else{
        return true;
      }
    }
  </script>
</html>

在Public/Weih5/gkchorus目录新建一个层叠样式表,main.css

*{margin: 0;padding: 0;font-family: "Microsoft YaHei";}
body{background-image: url(./bg.png);background-repeat: repeat;}
.content_all{width: 95%;min-width: 300px;background-color: #fff;margin: 2.5%;}

.content_all_top{width: 100%;height: 100px;margin:auto;border-bottom: 1px solid #eee;position: relative;}
.content_all_top div{width: 85%;margin: auto;position: relative;top: 15px;}
.content_all_top div h2{font-weight: 400!important;height:40px;line-height: 40px;}
.content_all_top div p span{height:30px;line-height:30px;font-size: 12px;}

.content_all_middle{width: 100%;margin:auto;background-color: #fff;}
.content_all_middle form p{width: 85%;margin: auto;}
.content_all_middle form p label{line-height: 30px;}
.content_all_middle form p input{width: 100%;height: 30px;outline: none;}

.content_all_middle form p label span{color: red}

.content_all_middle form div input{display: block;float: left;width: 15%;height: 20px;line-height: 25px;margin: 2.5px 0 2.5px 0;}
.content_all_middle form div span{display: block;float: left;width: 85%;height: 25px;line-height: 25px;font-size: 14px;}

.content_all_middle form .radio{width: 85%!important;height: 100px;margin: auto;}
.content_all_middle form p .submit{border-radius: 5px;height: 35px;color: #fff;border:0;outline: none;background-color: rgb(55,185,210);}

.content_all_bottom{width: 100%;margin:auto;background-color: #fff;border-top: 1px solid #eee;position: relative;margin: 30px 0 0 0;}
.content_all_bottom p{font-size: 12px;padding: 10px 0;text-align: center;}

将gkchorus.sql导入mysql数据库

-- phpMyAdmin SQL Dump
-- version 4.1.14
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: 2018-04-14 12:39:52
-- 服务器版本: 5.6.17
-- PHP Version: 5.5.12

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;

--
-- Database: `gkchorus`
--
CREATE DATABASE IF NOT EXISTS `gkchorus` DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;
USE `gkchorus`;

-- --------------------------------------------------------

--
-- 表的结构 `enrol`
--

CREATE TABLE IF NOT EXISTS `enrol` (
  `id` int(8) NOT NULL AUTO_INCREMENT,
  `name` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
  `dept` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
  `phone` bigint(15) NOT NULL,
  `chorus` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
  `create` datetime NOT NULL,
  `nickname` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

效果:


(网页授权Oauth2.0,分享到朋友圈接口,分享给朋友接口)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值