通过小程序UrlScheme跳转小程序

获取了小程序的scheme码,就可以像打开网页链接一样,通过短信、邮件、外部网页等微信以外的渠道拉起小程序,URL Scheme链接形式如weixin://dl/business/?t= *TICKET*

话不多说直接上代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
<?php

//获取小程序UrlScheme

//小程序的 AppID和 AppSecret
$appId = '*********';
$appSecret = '*********';

$us = getUrlScheme(getAccessToken($appId, $appSecret));

Header("Location: $us");


/**
* curl
*/
function httpRequest($url, $format = 'get', $data = null, $headerArray = [])
{
//设置头信息
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
if ($format == 'post') {
//post传值设置post传参
curl_setopt($curl, CURLOPT_POST, 1);
if ($data) {
$data = json_encode($data);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
if ($headerArray) {
curl_setopt($curl, CURLOPT_HTTPHEADER, $headerArray);
}
$data = json_decode(curl_exec($curl), true);
curl_close($curl);
//返回接口返回数据
return $data;
}

function getAccessToken($appId, $appSecret)
{
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);

$key = 'rout:accessToke';
$at = $redis->get($key);
if ($at) {
return $at;
}
$data = httpRequest(
'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appId . '&secret=' . $appSecret,
'get',
null,
array("Content-type:application/json;", "Accept:application/json")
);
$at = $data['access_token'] ?? '';
$redis->set('rout:accessToke', $at, 60 * 90);
return $at;
}

function getUrlScheme($accessToken)
{
$data = httpRequest(
'https://api.weixin.qq.com/wxa/generatescheme?access_token=' . $accessToken,
'post',
[
'jump_wxa' => [
'path' => "/pages/index/index",//跳转小程序地址
'query' => ""//跳转小程序额外参数
],
'expire_type' => 0
]
);
return $data['openlink'] ?? '';
}