技术文摘

php开发微信公众号文章付费阅读功能!

作者:雨祺   发表于:
浏览:34次    字数:12023  原创
级别: 站长   总稿: 68 篇,  月稿: 0

如上图,一看就懂,就是一片公众号文章,点进去显示标题,作者,时间,公众号名称和部分内容,要想阅读所有内容,那就支付0.01元就可以阅读所有的内容,这就是付费阅读!!!当然金额可以自定义....

其实这个开发原理很简单,无非就是在文章页面加一个微信支付的按钮,点击支付后把隐藏的部分给显示出来或者直接跳转到全文地址。

当然了,这个文章界面也是模仿官方来写的,你可以查看官方的样式,然后模仿就可以了,这个没啥难度。主要是加个按钮在这个页面,下面是这个页面的代码:

readpay.php
  1. <?php 
  2. header('Content-type:text/html; Charset=utf-8'); 
  3. $mchid = '微信支付商户号';          //微信支付商户号 
  4. $appid = '微信支付申请对应的公众号的APPID';  //微信支付申请对应的公众号的APPID 
  5. $appKey = '微信支付申请对应的公众号的APPSECRET';   //微信支付申请对应的公众号的APPSECRET 
  6. $apiKey = 'API密钥';   //帐户设置-安全设置-API安全-API密钥-设置API密钥 
  7. //①、获取用户openid 
  8. $wxPay = new WxpayService($mchid,$appid,$appKey,$apiKey); 
  9. $openId = $wxPay->GetOpenid();      //获取openid 
  10. if(!$openId) exit('获取openid失败'); 
  11. //②、统一下单 
  12. $outTradeNo = uniqid();     //你自己的商品订单号 
  13. $payAmount = 0.01;          //付款金额,单位:元 
  14. $orderName = 'test';    //订单标题 
  15. $notifyUrl = 'nofity.php';     //付款成功后的回调地址,一般放在本页面的同级目录即可 
  16. $payTime = time();      //付款时间 
  17. $jsApiParameters = $wxPay->createJsBizPackage($openId,$payAmount,$outTradeNo,$orderName,$notifyUrl,$payTime); 
  18. $jsApiParameters = json_encode($jsApiParameters); 
  19. ?> 
  20.   
  21.     <!--下面就是木方官方微信文章页面--> 
  22.     <html> 
  23.     <head> 
  24.         <meta charset="utf-8"
  25.         <meta name="viewport" content="width=device-width, initial-scale=1"/> 
  26.         <title>新版微信支持双开,王利芬庆祝“茅侃侃去世”文阅读10w+被批人血馒头</title> 
  27.         <script type="text/javascript"
  28.             //调用微信JS api 支付 
  29.             function jsApiCall() 
  30.             { 
  31.                 WeixinJSBridge.invoke( 
  32.                     'getBrandWCPayRequest'
  33.                     <?php echo $jsApiParameters; ?>, 
  34.                     function(res){ 
  35.                         WeixinJSBridge.log(res.err_msg); 
  36.                         //alert(res.err_code+res.err_desc+res.err_msg); 
  37.                         if(res.err_msg == "get_brand_wcpay_request:ok"){ 
  38.                             //支付成功跳转页面 
  39.                             window.location.href="这里填写支付成功后要跳转的查看全文文章地址"
  40.                         }else
  41.                             //支付失败/或取消支付跳转页面,自己自定义开发页面 
  42.                             window.location.href="false.html"
  43.                         } 
  44.                     } 
  45.                 ); 
  46.             } 
  47.             function callpay() 
  48.             { 
  49.                 if (typeof WeixinJSBridge == "undefined"){ 
  50.                     if( document.addEventListener ){ 
  51.                         document.addEventListener('WeixinJSBridgeReady', jsApiCall, false); 
  52.                     }else if (document.attachEvent){ 
  53.                         document.attachEvent('WeixinJSBridgeReady', jsApiCall); 
  54.                         document.attachEvent('onWeixinJSBridgeReady', jsApiCall); 
  55.                     } 
  56.                 }else
  57.                     jsApiCall(); 
  58.                 } 
  59.             } 
  60.         </script> 
  61.         <!--下面就是木方官方微信文章页面的CSS--> 
  62.         <style> 
  63.             #title{ 
  64.                    margin-bottom:10px; 
  65.                    line-height:1.4; 
  66.                    font-weight:400; 
  67.                    font-size:24px; 
  68.                    width: 97%; 
  69.                    margin:0 auto; 
  70.             } 
  71.              
  72.             #meta_content .time{ 
  73.                 color: #8C8C8C; 
  74.                 font-family: "SimHei"
  75.             } 
  76.   
  77.             .author{ 
  78.                 color: #8C8C8C; 
  79.                 font-family: "SimHei"
  80.             } 
  81.   
  82.             .name{ 
  83.                 color: #607fa6; 
  84.             } 
  85.   
  86.             #con{ 
  87.                 width:95%; 
  88.                 font-size: 15px; 
  89.                 margin:15px auto 25px; 
  90.                 color: #595757; 
  91.             } 
  92.         </style> 
  93.     </head> 
  94.     <body> 
  95.     <br/> 
  96.     <!--文章标题--> 
  97.     <h2 id="title">新版微信支持双开,王利芬庆祝“茅侃侃去世”文阅读10w+被批人血馒头</h2> 
  98.     <div id="meta_content"
  99.     <!--发布时间、作者、公众号昵称--> 
  100.        <span class="time">2018-01-27</span>   <span class="author">tanking</span>   <span class="name">里客云</span> 
  101.     </div> 
  102.     <!--显示的部分内容,未支付前显示的内容--> 
  103.     <div id="con"
  104.         这一周,公众号议论最多的有“周冲的影像声色”因洗稿被撕、80后创业者茅侃侃去世、刘亦菲分手......几乎每件事都能在朋友圈刷到相关报道。此外,视频大号“一条”又拿到了新一轮融资,你最关心哪一件事呢? 
  105.     </div> 
  106.     <!--支付按钮--> 
  107.     <div align="center"
  108.         <button style="width:180px; height:35px;background: none; border-radius: 5px;border:1px #1AAD19 solid; cursor: pointer;  color:#1AAD19;  font-size:15px;-webkit-tap-highlight-color:rgba(255,0,0,0);" type="button" οnclick="callpay()" >支付0.01阅读全文</button> 
  109.     </div> 
  110.     </body> 
  111.     </html> 
  112.     <!--下面是微信支付逻辑了--> 
  113. <?php 
  114. header("Content-Type:text/html; charset=utf-8"); 
  115. class WxpayService 
  116.     protected $mchid; 
  117.     protected $appid; 
  118.     protected $appKey; 
  119.     protected $apiKey; 
  120.     public $data = null
  121.     public function __construct($mchid, $appid, $appKey,$key) 
  122.     { 
  123.         $this->mchid = $mchid; //https://pay.weixin.qq.com 产品中心-开发配置-商户号 
  124.         $this->appid = $appid; //微信支付申请对应的公众号的APPID 
  125.         $this->appKey = $appKey; //微信支付申请对应的公众号的APP Key 
  126.         $this->apiKey = $key;   //https://pay.weixin.qq.com 帐户设置-安全设置-API安全-API密钥-设置API密钥 
  127.     } 
  128.     /** 
  129.      * 通过跳转获取用户的openid,跳转流程如下: 
  130.      * 1、设置自己需要调回的url及其其他参数,跳转到微信服务器https://open.weixin.qq.com/connect/oauth2/authorize 
  131.      * 2、微信服务处理完成之后会跳转回用户redirect_uri地址,此时会带上一些参数,如:code 
  132.      * @return 用户的openid 
  133.      */ 
  134.     public function GetOpenid() 
  135.     { 
  136.         //通过code获得openid 
  137.         if (!isset($_GET['code'])){ 
  138.             //触发微信返回code码 
  139.             $scheme = $_SERVER['HTTPS']=='on' ? 'https://' : 'http://'
  140.             $baseUrl = urlencode($scheme.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].$_SERVER['QUERY_STRING']); 
  141.             $url = $this->__CreateOauthUrlForCode($baseUrl); 
  142.             Header("Location: $url"); 
  143.             exit(); 
  144.         } else { 
  145.             //获取code码,以获取openid 
  146.             $code = $_GET['code']; 
  147.             $openid = $this->getOpenidFromMp($code); 
  148.             return $openid; 
  149.         } 
  150.     } 
  151.     /** 
  152.      * 通过code从工作平台获取openid机器access_token 
  153.      * @param string $code 微信跳转回来带上的code 
  154.      * @return openid 
  155.      */ 
  156.     public function GetOpenidFromMp($code) 
  157.     { 
  158.         $url = $this->__CreateOauthUrlForOpenid($code); 
  159.         $res = self::curlGet($url); 
  160.         //取出openid 
  161.         $data = json_decode($res,true); 
  162.         $this->data = $data; 
  163.         $openid = $data['openid']; 
  164.         return $openid; 
  165.     } 
  166.     /** 
  167.      * 构造获取open和access_toke的url地址 
  168.      * @param string $code,微信跳转带回的code 
  169.      * @return 请求的url 
  170.      */ 
  171.     private function __CreateOauthUrlForOpenid($code) 
  172.     { 
  173.         $urlObj["appid"] = $this->appid; 
  174.         $urlObj["secret"] = $this->appKey; 
  175.         $urlObj["code"] = $code; 
  176.         $urlObj["grant_type"] = "authorization_code"
  177.         $bizString = $this->ToUrlParams($urlObj); 
  178.         return "https://api.weixin.qq.com/sns/oauth2/access_token?".$bizString; 
  179.     } 
  180.     /** 
  181.      * 构造获取code的url连接 
  182.      * @param string $redirectUrl 微信服务器回跳的url,需要url编码 
  183.      * @return 返回构造好的url 
  184.      */ 
  185.     private function __CreateOauthUrlForCode($redirectUrl) 
  186.     { 
  187.         $urlObj["appid"] = $this->appid; 
  188.         $urlObj["redirect_uri"] = "$redirectUrl"
  189.         $urlObj["response_type"] = "code"
  190.         $urlObj["scope"] = "snsapi_base"
  191.         $urlObj["state"] = "STATE"."#wechat_redirect"
  192.         $bizString = $this->ToUrlParams($urlObj); 
  193.         return "https://open.weixin.qq.com/connect/oauth2/authorize?".$bizString; 
  194.     } 
  195.     /** 
  196.      * 拼接签名字符串 
  197.      * @param array $urlObj 
  198.      * @return 返回已经拼接好的字符串 
  199.      */ 
  200.     private function ToUrlParams($urlObj) 
  201.     { 
  202.         $buff = ""
  203.         foreach ($urlObj as $k => $v) 
  204.         { 
  205.             if($k != "sign") $buff .= $k . "=" . $v . "&"
  206.         } 
  207.         $buff = trim($buff, "&"); 
  208.         return $buff; 
  209.     } 
  210.     /** 
  211.      * 统一下单 
  212.      * @param string $openid 调用【网页授权获取用户信息】接口获取到用户在该公众号下的Openid 
  213.      * @param float $totalFee 收款总费用 单位元 
  214.      * @param string $outTradeNo 唯一的订单号 
  215.      * @param string $orderName 订单名称 
  216.      * @param string $notifyUrl 支付结果通知url 不要有问号 
  217.      * @param string $timestamp 支付时间 
  218.      * @return string 
  219.      */ 
  220.     public function createJsBizPackage($openid, $totalFee, $outTradeNo, $orderName, $notifyUrl, $timestamp) 
  221.     { 
  222.         $config = array( 
  223.             'mch_id' => $this->mchid, 
  224.             'appid' => $this->appid, 
  225.             'key' => $this->apiKey, 
  226.         ); 
  227.         $orderName = iconv('GBK','UTF-8',$orderName); 
  228.         $unified = array( 
  229.             'appid' => $config['appid'], 
  230.             'attach' => 'pay',             //商家数据包,原样返回,如果填写中文,请注意转换为utf-8 
  231.             'body' => $orderName, 
  232.             'mch_id' => $config['mch_id'], 
  233.             'nonce_str' => self::createNonceStr(), 
  234.             'notify_url' => $notifyUrl, 
  235.             'openid' => $openid,            //rade_type=JSAPI,此参数必传 
  236.             'out_trade_no' => $outTradeNo, 
  237.             'spbill_create_ip' => '127.0.0.1'
  238.             'total_fee' => intval($totalFee * 100),       //单位 转为分 
  239.             'trade_type' => 'JSAPI'
  240.         ); 
  241.         $unified['sign'] = self::getSign($unified, $config['key']); 
  242.         $responseXml = self::curlPost('https://api.mch.weixin.qq.com/pay/unifiedorder', self::arrayToXml($unified)); 
  243.         $unifiedOrder = simplexml_load_string($responseXml, 'SimpleXMLElement', LIBXML_NOCDATA); 
  244.         if ($unifiedOrder === false) { 
  245.             die('parse xml error'); 
  246.         } 
  247.         if ($unifiedOrder->return_code != 'SUCCESS') { 
  248.             die($unifiedOrder->return_msg); 
  249.         } 
  250.         if ($unifiedOrder->result_code != 'SUCCESS') { 
  251.             die($unifiedOrder->err_code); 
  252.         } 
  253.         $arr = array( 
  254.             "appId" => $config['appid'], 
  255.             "timeStamp" => "$timestamp",        //这里是字符串的时间戳,不是int,所以需加引号 
  256.             "nonceStr" => self::createNonceStr(), 
  257.             "package" => "prepay_id=" . $unifiedOrder->prepay_id, 
  258.             "signType" => 'MD5'
  259.         ); 
  260.         $arr['paySign'] = self::getSign($arr, $config['key']); 
  261.         return $arr; 
  262.     } 
  263.     public static function curlGet($url = '', $options = array()) 
  264.     { 
  265.         $ch = curl_init($url); 
  266.         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
  267.         curl_setopt($ch, CURLOPT_TIMEOUT, 30); 
  268.         if (!empty($options)) { 
  269.             curl_setopt_array($ch, $options); 
  270.         } 
  271.         //https请求 不验证证书和host 
  272.         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
  273.         curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); 
  274.         $data = curl_exec($ch); 
  275.         curl_close($ch); 
  276.         return $data; 
  277.     } 
  278.     public static function curlPost($url = '', $postData = '', $options = array()) 
  279.     { 
  280.         if (is_array($postData)) { 
  281.             $postData = http_build_query($postData); 
  282.         } 
  283.         $ch = curl_init(); 
  284.         curl_setopt($ch, CURLOPT_URL, $url); 
  285.         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
  286.         curl_setopt($ch, CURLOPT_POST, 1); 
  287.         curl_setopt($ch, CURLOPT_POSTFIELDS, $postData); 
  288.         curl_setopt($ch, CURLOPT_TIMEOUT, 30); //设置cURL允许执行的最长秒数 
  289.         if (!empty($options)) { 
  290.             curl_setopt_array($ch, $options); 
  291.         } 
  292.         //https请求 不验证证书和host 
  293.         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
  294.         curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); 
  295.         $data = curl_exec($ch); 
  296.         curl_close($ch); 
  297.         return $data; 
  298.     } 
  299.     public static function createNonceStr($length = 16) 
  300.     { 
  301.         $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
  302.         $str = ''
  303.         for ($i = 0; $i < $length; $i++) { 
  304.             $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1); 
  305.         } 
  306.         return $str; 
  307.     } 
  308.     public static function arrayToXml($arr) 
  309.     { 
  310.         $xml = "<xml>"
  311.         foreach ($arr as $key => $val) { 
  312.             if (is_numeric($val)) { 
  313.                 $xml .= "<" . $key . ">" . $val . "</" . $key . ">"
  314.             } else 
  315.                 $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">"
  316.         } 
  317.         $xml .= "</xml>"
  318.         return $xml; 
  319.     } 
  320.     public static function getSign($params, $key) 
  321.     { 
  322.         ksort($params, SORT_STRING); 
  323.         $unSignParaString = self::formatQueryParaMap($params, false); 
  324.         $signStr = strtoupper(md5($unSignParaString . "&key=" . $key)); 
  325.         return $signStr; 
  326.     } 
  327.     protected static function formatQueryParaMap($paraMap, $urlEncode = false
  328.     { 
  329.         $buff = ""
  330.         ksort($paraMap); 
  331.         foreach ($paraMap as $k => $v) { 
  332.             if (null != $v && "null" != $v) { 
  333.                 if ($urlEncode) { 
  334.                     $v = urlencode($v); 
  335.                 } 
  336.                 $buff .= $k . "=" . $v . "&"
  337.             } 
  338.         } 
  339.         $reqPar = ''
  340.         if (strlen($buff) > 0) { 
  341.             $reqPar = substr($buff, 0, strlen($buff) - 1); 
  342.         } 
  343.         return $reqPar; 
  344.     } 
  345. ?> 
nofity.php
  1. <?php 
  2. /** 
  3.  * 原生支付(扫码支付)及公众号支付的异步回调通知 
  4.  * 说明:需要在native.php或者jsapi.php中的填写回调地址。例如:http://www.xxx.com/wx/notify.php 
  5.  * 付款成功后,微信服务器会将付款结果通知到该页面 
  6.  */ 
  7. header('Content-type:text/html; Charset=utf-8'); 
  8. $mchid = '微信支付商户号'
  9. $appid = '公众号APPID';  
  10. $apiKey = 'API密钥';  
  11. $wxPay = new WxpayService($mchid,$appid,$apiKey); 
  12. $result = $wxPay->notify(); 
  13. if($result){ 
  14.     //完成你的逻辑 
  15.     //例如连接数据库,获取付款金额$result['cash_fee'],获取订单号$result['out_trade_no'],修改数据库中的订单状态等; 
  16. }else
  17.     echo 'pay error'
  18. class WxpayService 
  19.     protected $mchid; 
  20.     protected $appid; 
  21.     protected $apiKey; 
  22.     public function __construct($mchid, $appid, $key) 
  23.     { 
  24.         $this->mchid = $mchid; 
  25.         $this->appid = $appid; 
  26.         $this->apiKey = $key; 
  27.     } 
  28.     public function notify() 
  29.     { 
  30.         $config = array( 
  31.             'mch_id' => $this->mchid, 
  32.             'appid' => $this->appid, 
  33.             'key' => $this->apiKey, 
  34.         ); 
  35.         $postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; 
  36.         $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); 
  37.         if ($postObj === false) { 
  38.             die('parse xml error'); 
  39.         } 
  40.         if ($postObj->return_code != 'SUCCESS') { 
  41.             die($postObj->return_msg); 
  42.         } 
  43.         if ($postObj->result_code != 'SUCCESS') { 
  44.             die($postObj->err_code); 
  45.         } 
  46.         $arr = (array)$postObj; 
  47.         unset($arr['sign']); 
  48.         if (self::getSign($arr, $config['key']) == $postObj->sign) { 
  49.             echo '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>'
  50.             return $arr; 
  51.         } 
  52.     } 
  53.     /** 
  54.      * 获取签名 
  55.      */ 
  56.     public static function getSign($params, $key) 
  57.     { 
  58.         ksort($params, SORT_STRING); 
  59.         $unSignParaString = self::formatQueryParaMap($params, false); 
  60.         $signStr = strtoupper(md5($unSignParaString . "&key=" . $key)); 
  61.         return $signStr; 
  62.     } 
  63.     protected static function formatQueryParaMap($paraMap, $urlEncode = false
  64.     { 
  65.         $buff = ""
  66.         ksort($paraMap); 
  67.         foreach ($paraMap as $k => $v) { 
  68.             if (null != $v && "null" != $v) { 
  69.                 if ($urlEncode) { 
  70.                     $v = urlencode($v); 
  71.                 } 
  72.                 $buff .= $k . "=" . $v . "&"
  73.             } 
  74.         } 
  75.         $reqPar = ''
  76.         if (strlen($buff) > 0) { 
  77.             $reqPar = substr($buff, 0, strlen($buff) - 1); 
  78.         } 
  79.         return $reqPar; 
  80.     } 
简单说明:

1】新建readpay.php,拷贝上面的代码,修改商户号、appid、appsecret、密钥即可,还有下面的回调地址的路径(nofity.php),至于支付成功和支付失败跳转的页面按自己的需求修改即可。
支付金额、文章标题】时间、作者、公账号名称等根据自己的需求修改。

要注意,订单标题不能为中文,否则会提示body参数错误什么的。

2】新建nofity.php

把上面的代码拷贝上去,修改商户号、appid、密钥即可。

上传到支付授权目录,然后访问readpay.php页面测试。

3】新建false.html,这个是支付失败的页面,至于支付失败要显示什么或者输出什么,这个根据你的业务来自定义开发。

【审核人:站长】

收藏   加好友   生成海报   分享
点赞(0)
打赏
Tags: 功能 付费阅读 文章 微信公众号 php开发
评论(0人参与,0条评论) 雨祺
0/0
  • 请先说点什么
    最新评论

    发布者资料

    热门文章

    技术文摘

    查看更多技术文摘
    首页
    栏目
    搜索
    会员
    投稿