微信公众平台会员注册机制:网页授权,得到code后在当前页面获取openid,js+php实现跨域请求
笔者开发情景:
需要引导微信公众平台用户点击链接进入注册页面,在注册页面需要获取用户微信的openid。技术核心是需要借助网页授权,并且在得到授权code时通过js立刻获取openid。
网上关于网页授权后一步步获取openid的文章大多是理论步骤的解说,落实到代码上具体怎么尽可能快的拿到openid的内容很少。笔者十分愤怒,决定写下代码和大家分享
这个过程需要一个前端页面代码和一个后端辅助程序,我这里前端是html+js,后端是php。
直接上代码,代码里注释解释的比较清楚:
前端:index.html
><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><meta name="viewport" content="width=device-width,height=device-height,inital-scale=1.0,maximum-scale=1.0,user-scalable=no;"><meta name="apple-mobile-web-app-capable" content="yes"><meta name="apple-mobile-web-app-status-bar-style" content="black"><meta name="format-detection" content="telephone=no"><title>会员注册</title><script type="text/javascript" src="jquery.js"></script><script type="text/javascript"> function callback(result) { alert('cucess'); alert(result); //输出openid } function getQueryString(name) { var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); var r = window.location.search.substr(1).match(reg); if (r != null) return unescape(r[2]); return null; }var code = getQueryString("code");$.ajax({ async: false, url: "http://arvon2012.sinaapp.com/oauth2.php", //这是我的服务端处理文件php的 type: "GET", //下面几行是jsoup,如果去掉下面几行的注释,后端对应的返回结果也要去掉注释 // dataType: 'jsonp', // jsonp: 'callback', //jsonp的值自定义,如果使用jsoncallback,那么服务器端,要返回一个jsoncallback的值对应的对象. // jsonpCallback:'callback', data: {code:code}, //传递本页面获取的code到后台,以便后台获取openid timeout: 5000, success: function (result) { callback(result); }, error: function (jqXHR, textStatus, errorThrown) { alert(textStatus); } });</script>
<?php $code = $_GET['code'];//前端传来的code值$appid = "xxxxxxxxxxxxxxxx";$appsecret = "xxxxxxxxxxxxxxxxxxxxxx";//获取openid$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$appsecret&code=$code&grant_type=authorization_code";$result = https_request($url);$jsoninfo = json_decode($result, true);$openid = $jsoninfo["openid"];//从返回json结果中读出openid$callback=$_GET['callback']; // echo $callback."({result:'".$openid."'})"; echo $openid; //把openid 送回前端function https_request($url,$data = null){ $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE); if (!empty($data)){ curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, $data); } curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $output = curl_exec($curl); curl_close($curl); return $output;}?>

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Alipay PHP...

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo
