背景:当前很多h5页面或者app需要一键跳转到微信小程序
微信官方获取 URL Scheme
官方文档: 获取 URL Scheme
前端代码
<html lang="zh"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>微信小程序</title> </head> <body> <a href="{$openlink}">点击跳转微信小程序</a> <!--自动打开微信小程序代码--> <!--<input type="hidden" id="timestamp" value="{{$openlink}}">--> <!--<p style="text-align: center">跳转中.....</p>--> </body> <script src="/js/jquery.min.js"></script> <!--自动打开微信小程序代码--> <!--<script>--> <!-- var timestamp = $('#timestamp').val();--> <!-- location.href = timestamp;--> <!--</script>--> </html>
后端php版本代码
public function getScheme() { $appid = '';//微信小程序appid $secret = '';//微信小程序secret //path是要跳转的小城页面地址,query为要携带的参数 $body = ['jump_wxa' => ['path' => '/pages/index/index', 'query' => 'pid=1']]; $tokenurl = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . $secret; $data = file_get_contents($tokenurl); $data = json_decode($data, true); $token = $data['access_token']; $url = "https://api.weixin.qq.com/wxa/generatescheme?access_token=" . $token; $data = $this->curl_post($url, null, $body); $this->assign('openlink', $data['openlink']); return $this->fetch(); } public function curl_post($url, $herder, $body) { //一般框架都会自带GuzzleHttp,没有的请手动安装,或者利用curl post请求 $client = new \GuzzleHttp\Client(); try { $pram = $client->post($url, [ 'headers' => $herder, 'json' => $body, ]); $content = json_decode($pram->getBody()->getContents(), true); return $content; } catch (ErrorException $exception) { return $exception->getCode(); } }