weixin_public.class.php 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. /**
  3. * 微信支付服务器端下单
  4. * 微信APP支付文档地址: https://pay.weixin.qq.com/wiki/doc/api/app.php?chapter=8_6
  5. * 使用示例
  6. * 构造方法参数
  7. * 'appid' => //填写微信分配的公众账号ID
  8. * 'mch_id' => //填写微信支付分配的商户号
  9. * 'notify_url'=> //填写微信支付结果回调地址
  10. * 'key' => //填写微信商户支付密钥
  11. * );
  12. * 统一下单方法
  13. * $WechatAppPay = new wechatAppPay($options);
  14. * $params['body'] = '商品描述'; //商品描述
  15. * $params['out_trade_no'] = '1217752501201407'; //自定义的订单号,不能重复
  16. * $params['total_fee'] = '100'; //订单金额 只能为整数 单位为分
  17. * $params['trade_type'] = 'APP'; //交易类型 JSAPI | NATIVE |APP | WAP
  18. * $wechatAppPay->unifiedOrder( $params );
  19. */
  20. class weixin_public
  21. {
  22. private $appid;
  23. private $seceret;
  24. private $uri;
  25. public function __construct($appid, $seceret, $uri)
  26. {
  27. $this->appid = $appid;
  28. $this->seceret = $seceret;
  29. $this->uri = $uri;
  30. }
  31. //获取code
  32. public function redirectWithCode()
  33. {
  34. $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$this->appid
  35. ."&redirect_uri=".$this->uri
  36. ."&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
  37. header('Location: '.$url);
  38. exit;
  39. }
  40. public function getAccessToken()
  41. {
  42. $rs = Baseconfig::getInfoByKey(TOKEN_BASE_KEY);
  43. if (empty($rs) || (time() - $rs["lastupdate"]) > TOKEN_LIMIT_TIME) {
  44. $accessToken = self::refreshToken();
  45. } else {
  46. $accessToken = $rs["value"];
  47. }
  48. return $accessToken;
  49. }
  50. public function refreshToken()
  51. {
  52. $token_access_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $this->appid . "&secret=" . $this->seceret;
  53. $res = file_get_contents($token_access_url); //
  54. $result = json_decode($res, true); //接受一个 JSON 格式的字符串并且把它转换为 PHP 变量s
  55. $access_token = $result['access_token'];
  56. $rs = Baseconfig::getInfoByKey(TOKEN_BASE_KEY);
  57. if ($rs) {
  58. $res = Baseconfig::updateByKey(TOKEN_BASE_KEY, array("value" => $access_token, "lastupdate" => time()));
  59. } else {
  60. $attrs = array(
  61. "key"=>TOKEN_BASE_KEY,
  62. "value"=>$access_token,
  63. "name"=>"token"
  64. );
  65. $res = Baseconfig::add($attrs);
  66. }
  67. if ($res) {
  68. return $access_token;
  69. }
  70. }
  71. }