php 微信公众号支付 获取openId

我们经常遇到的一个场景是分享某个链接到微信群或个人,然后直接在微信内部打开进行购买支付。但有时会发现不能支付,提示你到外部浏览器打开,此时就需要微信公众号支付了,即JSAPI支付(微信内H5调起支付)。

JSAPI支付详情可查看官网,这里简要说明一下微信网页授权:

1、以snsapi_base为scope发起的网页授权,是用来获取进入页面的用户的openid的,并且是静默授权并自动跳转到回调页的。用户感知的就是直接进入了回调页(往往是业务页面)

2、以snsapi_userinfo为scope发起的网页授权,是用来获取用户的基本信息的。但这种授权需要用户手动同意,并且由于用户同意过,所以无须关注,就可在授权后获取该用户的基本信息。

3、用户管理类接口中的“获取用户基本信息接口”,是在用户和公众号产生消息交互或关注后事件推送后,才能根据用户OpenID来获取用户基本信息。这个接口,包括其他微信接口,都是需要该用户(即openid)关注了公众号后,才能调用成功的。

我用到的是第一种方式(不需要关注公众号),打开链接后显示正在登陆中,获取到用户的openId后跳转到自己的页面

wei_chat_jsapi.png

1、php + laravel

其中 mchid、appid、appKey、apiKey主要参数在微信商户申请平台自行申请,下面是获取openId的类,整理微信Demo和网上的一些参考,总之能用,有不正确的地方欢迎评论(php新手)

class WeJsApiPay
{
    protected $mchid;
    protected $appid;
    protected $appSecret;
    protected $apiKey;
    public $data = null;

    public function __construct($mchid, $appid, $appSecret, $apiKey)
    {
        $this->appid = $appid;
        $this->mchid = $mchid;
        $this->apiKey = $apiKey;
        $this->appSecret = $appSecret;
    }

    /**
     * 通过跳转获取用户的openid,跳转流程如下:
     * 1、设置自己需要调回的url及其其他参数,跳转到微信服务器https://open.weixin.qq.com/connect/oauth2/authorize
     * 2、微信服务处理完成之后会跳转回用户redirect_uri地址,此时会带上一些参数,如:code
     * @return 用户的openid
     */
    public function GetOpenid()
    {
        //通过code获得openid
        if (!isset($_GET['code'])) {
            //触发微信返回code码
            //$scheme = $_SERVER['HTTPS'] == 'on' ? 'https://' : 'http://';
            //$baseUrl = urlencode($scheme . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] . $_SERVER['QUERY_STRING']);
            $baseUrl = urlencode("https://xxx.xxx.com/xxx/xxx");
            $url = $this->__CreateOauthUrlForCode($baseUrl);
            Header("Location: $url");
            exit();
        } else {
            //获取code码,以获取openid
            $code = $_GET['code'];
            $openid = $this->getOpenidFromMp($code);
            return $openid;
        }
    }

    /**
     * 通过code从工作平台获取openid机器access_token
     * @param string $code 微信跳转回来带上的code
     * @return openid
     */
    public function GetOpenidFromMp($code)
    {
        try {
            $url = $this->__CreateOauthUrlForOpenid($code);
            $res = self::curlGet($url);
            //取出openid
            $data = json_decode($res, true);
            $this->data = $data;
            if (session('openid'))
                return;
            $openid = $data['openid'];
            return $openid;
        } catch (\Exception $e) {
            echo $e;
        }
    }

    /**
     * 构造获取open和access_toke的url地址
     * @param string $code,微信跳转带回的code
     * @return 请求的url
     */
    private function __CreateOauthUrlForOpenid($code)
    {
        $urlObj["appid"] = $this->appid;
        $urlObj["secret"] = $this->appSecret;
        $urlObj["code"] = $code;
        $urlObj["grant_type"] = "authorization_code";
        $bizString = $this->ToUrlParams($urlObj);
        return "https://api.weixin.qq.com/sns/oauth2/access_token?" . $bizString;
    }

    /**
     * 构造获取code的url连接
     * @param string $redirectUrl 微信服务器回跳的url,需要url编码
     * @return 返回构造好的url
     */
    private function __CreateOauthUrlForCode($redirectUrl)
    {
        $urlObj["appid"] = $this->appid;
        $urlObj["redirect_uri"] = "$redirectUrl";
        $urlObj["response_type"] = "code";
        $urlObj["scope"] = "snsapi_base";
        $urlObj["state"] = "STATE" . "#wechat_redirect";
        $bizString = $this->ToUrlParams($urlObj);
        return "https://open.weixin.qq.com/connect/oauth2/authorize?" . $bizString;
    }

    /**
     * 拼接签名字符串
     * @param array $urlObj
     * @return 返回已经拼接好的字符串
     */
    private function ToUrlParams($urlObj)
    {
        $buff = "";
        foreach ($urlObj as $k => $v) {
            if ($k != "sign") $buff .= $k . "=" . $v . "&";
        }
        $buff = trim($buff, "&");
        return $buff;
    }

    /**
     * 统一下单
     * @param string $openid 调用【网页授权获取用户信息】接口获取到用户在该公众号下的Openid
     * @param float $totalFee 收款总费用 单位元
     * @param string $outTradeNo 唯一的订单号
     * @param string $orderName 订单名称
     * @param string $notifyUrl 支付结果通知url 不要有问号
     * @param string $timestamp 支付时间
     * @return string
     */
    public function CreateJsBizPackage($openid, $totalFee, $outTradeNo, $orderName, $clientIp, $notifyUrl, $timestamp)
    {
        $config = array(
            'mch_id' => $this->mchid,
            'appid' => $this->appid,
            'key' => $this->apiKey,
        );
        $orderName = iconv('GBK', 'UTF-8', $orderName);
        $unified = array(
            'appid' => $config['appid'],
            'body' => $orderName,
            'mch_id' => $config['mch_id'],
            'nonce_str' => self::createNonceStr(),
            'notify_url' => $notifyUrl,
            'openid' => $openid,            //rade_type=JSAPI,此参数必传
            'out_trade_no' => $outTradeNo,
            'spbill_create_ip' => '127.0.0.1',
            'total_fee' => $totalFee,
            'trade_type' => 'JSAPI',
        );
        $unified['sign'] = self::getSign($unified, $config['key']);
        $responseXml = self::curlPost('https://api.mch.weixin.qq.com/pay/unifiedorder', self::arrayToXml($unified));
        $unifiedOrder = simplexml_load_string($responseXml, 'SimpleXMLElement', LIBXML_NOCDATA);
        if ($unifiedOrder === false) {
            die('parse xml error');
        }
        if ($unifiedOrder->return_code != 'SUCCESS') {
            die($unifiedOrder->return_msg);
        }
        if ($unifiedOrder->result_code != 'SUCCESS') {
            die($unifiedOrder->err_code);
        }
        $arr = array(
            "appId" => $config['appid'],
            "timeStamp" => "$timestamp",        //这里是字符串的时间戳,不是int,所以需加引号
            "nonceStr" => self::createNonceStr(),
            "package" => "prepay_id=" . $unifiedOrder->prepay_id,
            "signType" => 'MD5',
        );
        $arr['paySign'] = self::getSign($arr, $config['key']);

        return $arr;
    }

    public static function curlGet($url = '', $options = array())
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        if (!empty($options)) {
            curl_setopt_array($ch, $options);
        }
        //https请求 不验证证书和host
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }

    public static function curlPost($url = '', $postData = '', $options = array())
    {
        if (is_array($postData)) {
            $postData = http_build_query($postData);
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30); //设置cURL允许执行的最长秒数
        if (!empty($options)) {
            curl_setopt_array($ch, $options);
        }
        //https请求 不验证证书和host
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }

    public static function createNonceStr($length = 16)
    {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $str = '';
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    public static function arrayToXml($arr)
    {
        $xml = "";
        foreach ($arr as $key => $val) {
            if (is_numeric($val)) {
                $xml .= "<" . $key . ">" . $val . "";
            } else
                $xml .= "<" . $key . ">";
        }
        $xml .= "";
        return $xml;
    }

    public static function getSign($params, $key)
    {
        ksort($params, SORT_STRING);
        $unSignParaString = self::formatQueryParaMap($params, false);
        $signStr = strtoupper(md5($unSignParaString . "&key=" . $key));
        return $signStr;
    }

    protected static function formatQueryParaMap($paraMap, $urlEncode = false)
    {
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v) {
            if (null != $v && "null" != $v) {
                if ($urlEncode) {
                    $v = urlencode($v);
                }
                $buff .= $k . "=" . $v . "&";
            }
        }
        $reqPar = '';
        if (strlen($buff) > 0) {
            $reqPar = substr($buff, 0, strlen($buff) - 1);
        }
        return $reqPar;
    }
}

说明:
1、GetOpenid()方法,下面注释掉的两行是微信Demo原有的,但是打印出来与自己的不是很符合,索性直接写成固定的,在设置JSAPI支付授权目录 时填写到 https://xxx.xxx.com/xxx 即可.

//$scheme = $_SERVER['HTTPS'] == 'on' ? 'https://' : 'http://';
//$baseUrl = urlencode($scheme . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] . $_SERVER['QUERY_STRING']);
$baseUrl = urlencode("https://xxx.xxx.com/xxx/xxx");

2、GetOpenidFromMp()方法,下面两行代码是自己添加的,不然在刷新时会报异常$data['openid']不存在.

if (session('openid'))
     return;

2、调用(laravel)

public function index()
{
     if ($this->isWeixinClient()) {
         $wxPay = new WeJsApiPay(
             Config::getMchId(),
             Config::getAppId(),
             Config::getAppSecret(),
             Config::getApiKey()
         );
         $openId = $wxPay->GetOpenid();   //获取openid
         if (isset($openId))
             session(['openid' => $openId]);

         return view('main');
     } else {
         // TODO
     }
}

3、支付订单

 /**
  * 微信内置浏览器    获取支付订单
  * @return string
  */
 protected function getWeJsApiPay()
 {
     $outTradeNo = $this->getOutTradeNo();    //商品订单号
     $payAmount = $this->getMoney() * 100;    //付款金额,单位:分
     $orderName = $this->getBody();    //订单标题
     $notifyUrl = Config::getWxPayJsApiNotify();
     $payTime = time();      //付款时间

     $wxPay = new WeJsApiPay(
         Config::getMchId(), Config::getAppId(),
         Config::getAppSecret(), Config::getApiKey()
     );
     $jsApiParameters = $wxPay->CreateJsBizPackage(session('openid'), $payAmount, $outTradeNo,
         $this->getClientIp(), $orderName, $notifyUrl, $payTime);

     return $jsApiParameters;
 }    

上面方法是提交订单到微信支付后台,成功后返回一个JSON字符串,然后将此信息 return 给前端即可支付.

{
     "appId":"wx2434b1c4yw0e2qc43b",     //公众号名称,由商户传入     
     "timeStamp":"1395712654",         //时间戳,自1970年以来的秒数     
     "nonceStr":"va8dv188sd6gfdsg366cccfbbb444", //随机串     
     "package":"prepay_id=u8023g1rwy1vz3gsdg888",     
     "signType":"MD5",         //微信签名方式:     
     "paySign":"70EA570631VE56VDS6534C63FF7FADD89" //微信签名 
}

VUE前端支付

export default {
    name: "XXXXX",
    data() {
        return {
             form:{}
        }
    },
    methods: {
        register() {
                this.$http.post('/register/xxx/xxx', this.form).then(response => {
                    const data = response.data;
                    if (data.success) {
                        if (data.hasOwnProperty('wejspay')) {
                            this.weixinPay(data.wejspay);  //微信自带浏览器支付
                        }  else {
                            this.$toast.top('注册失败,请稍后重试或联系客服');
                        }
                    }  
                }, () => {
                    this.$toast.top('请求异常,请稍后重试或联系客服');
                });
            }
        },
        weixinPay: function (data) {
            if (typeof WeixinJSBridge == "undefined") {
                if (document.addEventListener) {
                        document.addEventListener("WeixinJSBridgeReady", this.onBridgeReady(data), false);
                } else if (document.attachEvent) {
                    document.attachEvent("WeixinJSBridgeReady", this.onBridgeReady(data));
                    document.attachEvent("onWeixinJSBridgeReady", this.onBridgeReady(data));
                }
            } else {
                this.onBridgeReady(data);
            }
        },
        onBridgeReady: function (data) {
            WeixinJSBridge.invoke(
                "getBrandWCPayRequest",
                {
                    'appId': data.appId, //公众号名称,由商户传入
                    'timeStamp': data.timeStamp, //时间戳,自1970年以来的秒数
                    'nonceStr': data.nonceStr, //随机串
                    'package': data.package, //订单详情扩展字符串
                    'signType': data.signType, //微信签名方式:
                    'paySign': data.paySign, //微信签名
                },
                function (res) {
                    if (res.err_msg == "get_brand_wcpay_request:ok") {
                        this.$toast.top('充值成功,请稍后登录');
                        window.location.reload();
                    } else {
                        this.$toast.top('充值失败,请稍后重试或联系客服');
                        // alert(res.err_desc);
                    }
                }
            );
        }
    },
}

注意:
微信支付最让人难以忍受的就是官网返回值说明,在调试的时候都不知道具体是哪错了,可以使用 res.err_desc来查看具体的错误信息.

wei_chat_explain.png

你可能感兴趣的:(php 微信公众号支付 获取openId)