记录微信小游戏跳转到客服会话做公众号支付的坑

2,625 阅读2分钟

业务流程

由于ios不能在小游戏里接入支付,可在触发支付的时候跳转到客服会话,让小游戏客服触动被动回复 回复一个页面去做微信公众号支付,流程大概就是这样

自动回复遇到的坑

其他整个流程没有特别难的地方,就是微信的文档混乱导致细节的地方不知道怎么写

  1. 需要在小游戏后台配置消息推送的接口,此接口如果在配置确认时需要返回 微信传来 echostr 字段,否则确认不了

  2. 微信提供的php sdk的加密解密微信的方法 在php7已经失效 需要重新用open_ssl写过

php 加解密过程

//微信后台配置的 EncodingAesKey 
//$encryptData 为加密的数据

function decryptMsg($encodingAesKey,$encryptData){
    $iv=substr($encodingAesKey,0,16);
    $password=substr($encodingAesKey,0,32);
    $decrypted = openssl_decrypt($encryptData, 'AES-256-CBC', $password, OPENSSL_ZERO_PADDING, $iv);
    $result=$this->decode($decrypted);
    $content = substr($result, 16, strlen($result));
    $lenList = unpack("N", substr($content, 0, 4));
    //$content  如果你在微信后台配置的格式 是json 这里返回的就是json 如果是xml 这返回的就是xml
    
    return json_decode(substr($content, 4, $lenList[1]), true);
}

// $replyMsg 需要加密的xml $appId 对应的小游戏appId
function encryptMsg($replyMsg, $appId){
    $iv=substr($encodingAesKey,0,16);
    $password=substr($encodingAesKey,0,32);
    $random = Str::random();
    $text = $random . pack("N", strlen($replyMsg)) . $replyMsg . $appId;
    $text = $this->encode($text);
    
    return openssl_encrypt($text, 'AES-256-CBC', $password, OPENSSL_ZERO_PADDING, $iv);
}

function decode($text)
{
    $pad = ord(substr($text, -1));
    if ($pad < 1 || $pad > 32) {
        $pad = 0;
    }
    
    return substr($text, 0, (strlen($text) - $pad));
}

function encode($text){
    $blockSize = self::$blockSize;
    $textLength = strlen($text);
    //计算需要填充的位数
    $amountToPad = $blockSize - ($textLength % $blockSize);
    if ($amountToPad == 0) {
        $amountToPad = $blockSize;
    }
    //获得补位所用的字符
    $padChr = chr($amountToPad);
    $tmp = "";
    for ($index = 0; $index < $amountToPad; $index++) {
        $tmp .= $padChr;
    }
    return $text . $tmp;
}

3.原本以后可以在直接在同个接口return返回 加密好的xml格式即可,但是在调试过程中怎么也不成功,无奈选择了 主动调起客服发送消息的接口,token也是小游戏的token,但文档上没记载我们需要的链接格式,后面通过百度到...

{
    "touser": 123, //小游戏用户的openid
    "msgtype": "link",
    "link": {
        "title": 123,
        "description": "",
        "url": "URL", //跳转的链接
        "thumb_url": "THUMB_UTL" //封面图
    }
}

以上是自动回复的流程,接下来是公众号支付遇到的些问题

公众号支付需要在 微信支付平台 配置jsApi的目录(注意https 和 http),在公众号平台配置公众号授权域名 在小游戏客服回复 公众号授权地址, 用户点击会跳转到你写好的 支付页面,路由会带上code和自定义的state参数,然后前端请求服务端的 微信统一下单接口,生成参数给前端调起微信公众号支付,完成支付后,微信的服务端会通知我们的服务端完成了支付

1.安卓手机支付的时候进来就白屏,但是苹果可以顺利完成支付完成异步回调,推测是由于在调起支付的时候,微信浏览器的WeixinJSBridge还未生成 导致支付一直调不起来, ios和安卓可能在处理微信浏览器的生命周期有所不同..最后的解决方式是前端在调起公众号的支付时候加一段大概1s的延迟,就解决了