在上周绵阳动力网络公司为大家介绍了关于“在Yii2框架中可逆加密和解密的方法”的内容,今天绵阳动力网络公司为你介绍关于在YII2框架中制作微信公众号中表单提交功能的方法及代码:
客户的需求如下:
只能在数据库中存在的手机号看到表单。
表单可以重复提交。
第一次进入表单需要验证
分享出去的页面,别人进入后也需要验证。
因为每个手机在同一个公众号当中的openid是唯一性的。所以在手机查看这个表单页面的时候,就将这个openid存到数据库中,方便下次提交可以验证。
下面是我的代码。使用的是YII2框架。
Controller
//获得回调函数
public function actionCallback($code,$state){
$model = new tp_tstz_proposal();
$model1= new tp_tstz_staff();
// 微信开放平台网站应用的appid和秘钥secret
$appid = '';
$secret = '';
$curl = new curl\Curl();
//获取access_token
$wxresponse = $curl->get('https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appid
. '&secret=' . $secret . '&code=' . $code . '&grant_type=authorization_code');
$wxresult = json_decode($wxresponse);
if(isset($wxresult->errcode) && $wxresult->errcode > 0){
//分享出去,重新认证
return $this->render('login');
// 向微信请求授权时出错,打印错误码
// echo json_encode($wxresult);
// exit;
}
$openid=$wxresult->openid;
$result=$model1::find()->where(['openid'=>$openid])->one();
//如果OPENID存在就去表单
if(count($result)>0){
$key=123456;
return $this->render('view',['model'=>$model,'key'=>$key]);
}else{
return $this->render('tel',['model'=>$model1,'openid'=> $openid]);
}
}`
view层
很简单的重定向页面
header('Location:https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx8ba95fc51672e844
&redirect_uri=http%3a%2f%2fjifen.wendu.cn%2fts%2fweb%2findex.php%3fr%3dproposal%2fcallback &response_type=code&scope=snsapi_base&state=123asd#wechat_redirect');
返回的路径就是进入controller的路径。
在表单页面,我先做了一个简单的认证
if(!isset($key)){
header('Location:http://jifen.wendu.cn/ts/web/index.php?r=say/login');
}
判断是否是从分享的页面来的,如果是从分享的页面来就要重新验证,判断是否在数据库中有此手机的openid。没有就进行手机号码的验证。