通过小程序UrlScheme跳转小程序

510 阅读1分钟

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

话不多说直接上代码

<?php
/**
 * openlink.php
 * Author: K
 * Date: 2023/3/18 14:27
 */

//获取小程序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'] ?? '';
}